diff --git a/com.oracle.truffle.r.pkgs/rJava/DESCRIPTION b/com.oracle.truffle.r.pkgs/rJava/DESCRIPTION
index 22b6b722cc2bf4bf2c7ee8830d129ea8a50f8272..96dd453eab726cd2d4f27e0fc37f5d87c134d25f 100644
--- a/com.oracle.truffle.r.pkgs/rJava/DESCRIPTION
+++ b/com.oracle.truffle.r.pkgs/rJava/DESCRIPTION
@@ -1,11 +1,11 @@
 Package: rJava
-Type: Package
-Title: FastR rJava compatibility layer
-Version: 1.0
-Date: 2017-05-18
-Author: Tomas Stupka
-Maintainer: Tomas Stupka <tomas.stupka@oracle.com>
-Description: Provides rJava R interface backed by FastR interoperability builtins.
+Version: (populated by mkdist!)
+Title: Low-Level R to Java Interface
+Author: Simon Urbanek <simon.urbanek@r-project.org>
+Maintainer: Simon Urbanek <simon.urbanek@r-project.org>
+Depends: R (>= 2.5.0), methods
+Description: Low-level interface to Java VM very much like .C/.Call and friends. Allows creation of objects, calling methods and accessing fields.
 License: GPL-2
-Suggests: testthat
-RoxygenNote: 6.0.1
+URL: http://www.rforge.net/rJava/
+SystemRequirements: Java JDK 1.2 or higher (for JRI/REngine JDK 1.4 or higher), GNU make
+BugReports: https://github.com/s-u/rJava/issues
diff --git a/com.oracle.truffle.r.pkgs/rJava/NAMESPACE b/com.oracle.truffle.r.pkgs/rJava/NAMESPACE
index b3ee338a3a3c9097a7fd84c642938fbe94438e60..89e01631b7c6987a9a74f40810b2b02fab8b6c68 100644
--- a/com.oracle.truffle.r.pkgs/rJava/NAMESPACE
+++ b/com.oracle.truffle.r.pkgs/rJava/NAMESPACE
@@ -1,27 +1,49 @@
-# Generated by roxygen2: do not edit by hand
-
-export(.jaddClassPath)
-export(.jaddLibrary)
-export(.jarray)
-export(.jbyte)
-export(.jcall)
-export(.jcast)
-export(.jchar)
-export(.jcheck)
-export(.jclear)
-export(.jevalArray)
-export(.jfield)
-export(.jfindClass)
-export(.jfloat)
-export(.jgetEx)
-export(.jinit)
-export(.jlong)
-export(.jnew)
-export(.jnull)
-export(.jpackage)
-export(.jshort)
-export(.jsimplify)
-export(.jstrVal)
-export(.jthrow)
-export(J)
-export(is.jnull)
+exportPattern("^\\.j")
+export( "J" )
+export( "%instanceof%" )
+
+export( clone )
+S3method( clone, default ) 
+export(is.jnull, .r2j, .rJava.base.path, toJava)
+exportClasses(jobjRef, jarrayRef, jrectRef, jfloat, jlong, jbyte, jchar, jclassName)
+exportMethods(show, "$", "$<-", 
+	"==", "!=", "<", ">", "<=", ">=", 
+	names, new, as.character, length, head, tail, 
+	"[", "[[", "[[<-", str, "dim<-", 
+	unique, duplicated, anyDuplicated, 
+	sort, rev, 
+	min, max, range, 
+	rep, 
+	clone )
+import(methods)
+importFrom(utils,head)
+importFrom(utils,tail)
+importFrom(utils,str)
+importFrom(utils, assignInNamespace)
+
+S3method(with, jobjRef)
+S3method(with, jarrayRef)
+S3method(with, jclassName)
+
+S3method(within, jobjRef)
+S3method(within, jarrayRef)
+S3method(within, jclassName)
+
+# within requires that with.jobjRef is visible outside
+export(with.jobjRef)
+
+if( exists( ".DollarNames", asNamespace("utils") ) ) importFrom( utils, .DollarNames )
+S3method(.DollarNames, jobjRef)
+S3method(.DollarNames, jarrayRef)
+S3method(.DollarNames, jrectRef)
+S3method(.DollarNames, jclassName)
+
+S3method( as.list, jobjRef )
+S3method( as.list, jarrayRef )
+S3method( as.list, jrectRef )
+
+S3method( "$", "Throwable" )
+S3method( "$<-", "Throwable" )
+
+export( javaImport )
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/NEWS b/com.oracle.truffle.r.pkgs/rJava/NEWS
new file mode 100644
index 0000000000000000000000000000000000000000..6ca423893e8480bee092a77a97ab7c42109e6ed3
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/NEWS
@@ -0,0 +1,620 @@
+ NEWS/ChangeLog for rJava
+--------------------------
+
+0.9-9	2017-10-11
+    o	add support for --disable-Xrs configure option in case java -Xrs
+	is so broken that it cannot even be tested - reportedly the case
+	with Docker (see #63).
+
+    o	add optional class.loader= argument to .jnew() which allows to
+	use a custom loader in special cases.
+
+    o	change target to 1.6 and higher since Java 1.9 breaks when asked
+	to compile anything older than that. There is no technical reason,
+	so you can still build 1.2/1.4 targets by reverting 992828b and
+	using a JDK that won't break on 1.4 targets.
+
+    o	Process events on Widnows while in rniIndle. (#23)
+
+    o	Add a work-around for a bug in Oracle Java on Linux which causes
+	segfaults due to stack truncation. (#102)
+
+    o	Work around a change in registry location on Windows for Oracle
+	Java 1.9. (#120)
+
+
+0.9-8	2016-01-06
+    o	Work around a bug on Oracle's Java on OS X by pre-loading jli
+
+    o	Work around DYLD_FALLBACK_LIBRARY_PATH being dropped in OS X 10.11
+
+
+0.9-7	2015-07-27
+    o	explicitly set -classpath in configure for getps since the user
+	may have set CLASSPATH and thus override the default
+	(see #3)
+
+    o	when constructing String references from character vectors,
+	treat NA as null on the Java side (see #15)
+
+    o	add .jsimplify(..., promote=TRUE) option to promote int
+	to double if integer NAs are to be interpreted literally as
+	-2147483648 values. (see #39)
+
+    o	fix .jarray(.jshort(...)) to respect the `jshort` tag (see #40)
+
+
+0.9-6	2012-12-23
+    o	bugfix: the first JVM parameters was shadowed by headless
+	mode parameter if enabled (default on OS X).
+
+
+0.9-5	2012-12-03
+    o	add more debugging information in RJavaClassLoader to trace
+	cases where class path entries are invalid or discarded
+
+    o	detect support for -Xrs and enable it by default (this prevents
+	Java from killing R process on interrupt)
+
+    o	restore locales after Java initialization (some JVMs clobber
+	locales with incompatible settings).
+
+    o	add --enable-headless option which sets the java.awt.headless
+	to true. In the auto mode this flag is only enabled on Mac OS X.
+	Note that it is only set upon initialization, it does not
+	affect already running JVMs.
+
+0.9-4	2013-03-11
+    o	added support for unboxing of Double[], Integer[] and Boolean[]
+	to .jevalArray(.., simplify=TRUE) and thus also to .jcall()
+
+    o	Windows: add Java configuartion paths before existing PATH
+	entries
+
+    o	Windows: honor a new option "java.home" to override JAVA_HOME
+	environment variable and system settings to allow co-existence
+	of other tools that may require differen Java paths.
+
+    o	Windows: fix a buglet in error reporting when no Java is installed
+
+    o	raise an error if the number of arguments to a Java call exceeds
+	maxJavaPars. Previously, calls woud be silently truncated.
+	Note that maxJavaPars can be raised by compiling rJava, e.g. with:
+	PKG_CFLAGS=-DmaxJavaPars=96 R CMD INSTAL rJava_...
+
+0.9-3	2011-12-10
+    o	bugfix: .jinit() was failing on Java 1.4 with
+	"cannot obtain Class.getSimpleName method ID"
+	since the method is only present in Java 1.5+
+	This was inadvertent, rJava aims to support Java 1.2+
+
+0.9-2	2011-10-26
+    o	When NOAWT is set, rJava will enable headless mode in the JVM
+	by setting the java.awt.headless property to true during
+	initialization in .jinit()
+
+    o	All C-level entry points are now pre-cached when rJava is
+	loaded such that calls can be made much faster since symbols
+	don't need to be looked up. This should speed up calls to
+	methods that take very little time as well as other parts
+	such as checking for exceptions.
+
+0.9-1	2011-06-28
+    o	fixed Java detection from registry on Windows (bug introduced
+	in 0.9-0)
+
+0.9-0	2011-06-22
+    o	fixes issues introduced by several new features in the late
+	0.8 series. Most imporantly .jarray() and .jevalArray() behave
+	as intended (and as implemented in previous versions). The
+	same applies to .jcall() behavior with respect to arrays and
+	its evalArray arument. The defaults for some new arguments
+	have been changed to reflect the original behavior.
+
+    o	.jevalArray() has an additional argument `simplify' which allows
+	multi-dimensional arrays to be converted to native R
+	types. Use with care - it may convert more recursive types in
+	the future so it should be used preferrably where you have
+	control over the types converted.
+
+    o	fixed a bug in .jevalArray that was not simplifying string
+	vectors correctly when the array type was not specified
+	(.jclass returns dot notation whereas signatures use JNI
+	notation so a conversion was necessary)
+
+    o	use install.libs.R in R 2.13.1 to install multi-arch JRI
+
+
+0.8-8	2010-12-20
+    o	Add support for r.arch in RJavaClassLoader on Windows as well
+
+    o   javaImport was only able to import java packages from the system class
+        loader (not from additional jars)
+
+0.8-7	2010-10-18
+    o	Windows updates to accomodate changes in R 2.12 and layout
+	changes in recent Sun Java installations.
+
+0.8-6	2010-09-17
+    o	JRI 0.5-4: rniStop() provides several ways to notify R on unix.
+	It improves handing of user interrupts via rniStop() by
+	allowing to avoid signals (signals can cause problems in some
+	recent JVM implementations).
+
+0.8-5	2010-09-02
+    o	fix a bug introduced in 0.8-2 where .jclassPath() would not
+	show the real class path
+
+    o	if the rJava class loader is used as a primary loader it will
+	also register as the context class loader. Some projects
+	rely on the thread context class loader instead of
+	Class.getClassLoader() [which is still more reliable] 
+	so those will now work as well.
+
+    o	JRI 0.5-3 (bugfixes)
+
+
+0.8-4	2010-04-28
+    o	JRI 0.5-2
+	IMPORTANT NOTE: handling of NAs in character vectors has been
+	fixed, NAs were	incorrectly passed as "NA" from R to Java
+	instead of nulls (it was correct the other way round). Any
+	code that relies on such incorrect behavior will need to be
+	fixed!
+
+	Other changes in JRI are mostly related to Windows support
+	(bugfixes R 2.11.0 and Windows 64-bit support)
+
+    o	run.bat is now installed as part of JRI
+
+0.8-3	2010-03-16
+    o	REngine and JRIEngine classes are now included in rJava/JRI
+	although they are not loaded by default.
+
+    o	.r2j now has convert parameter to allow the creation of
+	pure references (convert=FALSE)
+
+    o	toJava() is a new function equivalent to .r2j but resulting
+	in REngine API references (instances of REXPReference).
+	By default the references are not resolved since the primary
+	use is to pass R functions to Java for callbacks.
+
+    o	set text mode for stdin on Windows (thanks to Brian Ripley)
+
+    o	fix support of NULL arguments in new(J("SomeClass"), ...)
+
+    o	fixed issues in with() and within() when used on jobjRef;
+	also the evaluation environment is now the parent frame as
+	expected
+
+    o	disable AWT tests if NOAWT is set; enable a few more tests
+
+
+0.8-2	2010-01-22
+    o	faster class loader implementation
+
+    o	added support for 64-bit Windows (thanks to Brian Ripley)
+
+
+0.8-1	2009-10-30
+    o	fixed exception handling on Windows: the access to "call"
+	was off for Windows builds causing incorrect "call" entries
+	in exceptions which broke when encountered in try().
+
+    o	fixed .jcall() which had inadvertently the default for
+	use.true.class argument set to TRUE. That is considered
+	a bug since it breaks the original behavior and is against the
+	idea of .jcall being the low-level interface.
+
+
+0.8-0	2009-10-27
+    o	new exception handling was introduced:
+
+	Java exceptions are mapped to Exception conditions which can
+	be used to catch the exception at R level using e.g tryCatch. 
+	
+	The class name automatically contains "Exception", "error"
+	and "condition", as well as all the names (without package path)
+	of the classes in the inheritance tree of the actual class of the 
+	Exception. This allows targetted handlers:
+	tryCatch(.jnew("foo"), NoClassDefFoundError=function(e) ...)
+
+	In addition JNI code now causes an error instead of a warning,
+	however, some errors internal to JNI may not have an associated
+	Java exception and thus will fire the usual simpleError
+	condition.
+
+	As a consequence of the new error handling exception objects
+	are now supplied in e$jobj of the handler and .jgetEx()
+	becomes obsolete.
+
+    o	added new high-level API using the "J" function. It replaces
+	the previously used .J()/.jrnew() and .jrcall().
+
+	New Java objects are created using new(J("class"), ...) and
+	static methods and fields are accessed using J("class")$...
+	The corresponding implementation uses reflection in all cases.
+
+	An additional class "jclassName" was created to support static
+	calls to accessor methods such as $ and calls to new().
+	
+    o   [RF] arrays are now split in two classes : "jrectRef" for rectangular
+        arrays, similar to R arrays, and jarrayRef for rugged arrays. 
+        Indexing of all arrays is supported using the double bracket 
+        indexer "[[" and "[[<-"
+        
+        The single indexer "[" is only currently implemented for 
+        rectangular arrays. This is experimental. Replacement ([<-) 
+        is not supported yet.
+
+    o   [RF] with.jclassName and within.jclassName is added to support
+        "with" semantics on static fields and methods of java classes. 
+        
+        Double <- J("java.lang.Double" )
+        with( Double, parseDouble( "10.2" ) )
+        
+
+    o   [RF] length.jarrayRef queries the number
+        of objects in a java array. An exception is generated if the 
+        object is not an array. Also array$length can be used 
+        similary to array.length in java
+        
+    o   [RF] .jcast gains arguments "check" and "convert.array". Their 
+             default value is FALSE for backwards compatibility with 
+             previous releases of rJava
+             
+    o   [RF] Binary operators <, >, <=, >= to compare two objects where 
+             at least one is a java object reference. 
+             d <- new( J("java.lang.Double"), 0.0 )
+             d < 1.0
+             d < 1L
+             Comparison of arrays is not currently supported
+             
+    o   [RF] lapply and sapply may now be used on Iterable java objects
+             such as Vector and java arrays. see ?as.list.jobjRef
+             
+    o   [RF] The generic "clone" function is added, and an implementation for 
+             java objects. an Object must implement the Cloneable 
+             interface, otherwise an exception will be raised. 
+             Furthermore, careful reading of the java documentation 
+             of Object#clone is recommended since this is not standard
+             java behaviour. Currently "clone" is not supported on 
+             arrays
+             
+    o   [RF] A mechanism for "attach"ing java packages has been introduced, 
+             following the mechanism of the RObjectTables package
+             from the OmegaHat project. This allows to "attach" a set of
+             java package paths to R's search path: 
+             
+             > attach( javaImport( "java.util", "java.lang" ) )
+             
+             and then use classes from this package like this :
+             
+             > new( Vector )
+             > new( HashMap )
+             > new( Double, 10.2 )
+             > new( Integer, 10L ) 
+             > Collections$EMPTY_MAP
+             
+             This feature is currently __very__ experimental and is as
+             dangerous as any other use of attach
+
+
+0.7-1	(never released)
+    o	[RF] added .J high-level java constructor (based on reflection 
+	as opposed to complete match as .jnew does)
+
+    o	[RF] added .jinstanceof and instanceof operator
+
+    o	when loaded into another JVM (e.g. via JRI), rJava would crash
+	on any call if .jinit() was missing. Now it correctly reports
+	the error.
+
+    o	fixed synchronization issues in both JRI and REngine
+
+0.7-0	2009-08-22
+    o	fixed bug in $ getter of fields using old .jfield API
+
+    o	fixed a bug in .jevalArray which failed when the signature
+	was specified directly (and subsequently .jfield failed in
+	most cases)
+
+    o	improve speed of reflection-based API (.jrcall and `$')
+	by using native array support in rJava
+
+    o	reflection API now returns NULL invisibly for void results
+
+    o	try to find the best match in reflection-based API
+	using internal Java code (code and idea by
+	Romain Francois)
+
+    o	added with() method for jobjRef (by Romain Francois), see
+	http://romainfrancois.blog.free.fr/index.php?
+	post/2009/06/17/with-semantics-for-java-objects-in-rJava
+
+    o	added names() method for jobjRef to facilitate code
+	completion (based on code by RF: http://tr.im/w33B)
+
+    o	update to JRI 0.5-0
+
+0.6-3	2009-06-14
+    o	update to JRI 0.4-3 (adds REngine API, enhanced support for
+	environments and references)
+
+    o	allow signatures longer than 256 bytes
+
+    o	added lib.loc parameter to .jpackage()
+
+0.6-2	2009-01-26
+    o	fix --enable-debug to really enable debug code
+
+    o	improve Windows setup (add only paths if they are not already
+	listed and check thier presence first) and warn if the system
+	suffers from PATH truncation bug (or PATH is truncated in
+	general)
+
+[0.6-branch is created as a stable branch -- see trunk for development]
+
+
+0.6-1	2008-12-23
+    o	substitute $(JAVA_HOME) in configuration flags when necessary
+
+    o	flag generated strings as UTF-8 and convert incoming strings
+	into UTF-8 (see note in ?.jcall for details)
+	This should improve interoperability in non-UTF-8 locales
+	(most prominent example is Windows)
+
+
+0.6-0	2008-09-22
+    o	add support for object cache - see .jcache() - based
+	on Java serialization
+
+
+0.5-2	(never released, turned into 0.6-0)
+    o	add direct support for raw vectors as method parameters
+	(before .jarray(r) had to be used)
+
+    o	add .jserialize() and .junserialize() functions for
+	Java-serialization (do not confuse with R serialization!)
+
+
+0.5-1	2007-11-05
+    o	fix crashes in Windows when Java calls the vfprintf hook
+
+    o	enhance Java environment checks, add more specific errors
+
+    o	add support for r.arch system property which allows multi-arch
+	support on platforms that don't have fat binaries (e.g. Linux)
+
+
+0.5-0	2007-08-22
+    o	**API CHANGE**
+	The order of arguments of .jfield has been changed to match
+	the order used in .jcall and the return value is as expected
+	and doesn't need .jsimplify anymore.
+
+    o	The implementation of .jfield no longer uses reflection
+	it supports static fields and .jfield<-() was added.
+
+    o	Consolidate interface code for static/non-static calls.
+	It is now possible to call a static method using a non-static
+	object.
+
+    o	Add .jpackage function for initialization of Java packages.
+	See documentation for details, packages should no longer
+	use .jinit in their initialization code.
+
+    o	Add preliminary JRI support from R (see .jengine)
+
+    o	Prepare hooks for de-serialization
+
+    o	Add support for short Java type
+
+    o	Add support for convertors
+
+    o	Fix R-devel compatibility issues
+
+    o	Fix a memory leak in string array handling
+
+    o	Use Java settings from R for compilation
+
+    o	Add a custom class loader
+
+    o	Fix a bug in .jcastToArray that produced invalid signatures
+
+    o	Added support for [Z in .jevalArray
+
+    o	Fix a bug in .jarray missing [ prefix for native type arrays
+
+
+
+0.4 branch has been branched off the trunk, see 0.4-branch for NEWS
+
+0.4-13	2007-01-14
+    o	Fix Java-side memory leaks (temporary parameters to methods
+	were not propery released, thanks to Erik van Barneveld for
+	supplying a reproducible example).
+
+    o	Fix a bug that caused only the first VM parameter to be passed
+	on during initialization (thanks to Bernard Rosman for
+	reporting).
+
+    o	.jmkref now accepts plain class names (with .)
+
+    o	Fix bug in .jarray (and underlying RcreateArray) that was
+	returning wrong class name if the contents class was an array.
+
+    o	Add --enable-callbacks option to configure (disabled by
+	default). The callbacks support is currently incomplete and
+	experimental.
+
+    o	Update URL to http://www.rforge.net/rJava/
+
+    o	Update to JRI 0.3-7 (LCons, createRJavaRef, assign XT_NONE) 
+
+0.4-12	2006-11-29
+    o	Added documentation for .jthrow, .jclear and .jgetEx and
+	a bugfix in .jgetEx
+
+    o	rJava now uses a namespace. This is still somewhat experimental,
+	because rJava needs to perform some dirty tricks to unseal
+	the namespace during initialization. Please test and report!
+
+    o	Update to JRI 0.3-6 (GIJ fix and fix for R-devel interface changes)
+
+0.4-11  2006-10-10
+    o	Replace variadic macros with wrappers (for compilers that don't
+	support ISO C99).
+
+    o	Modify JNI error reporting - use warnings instead of direct stderr.
+
+    o	Update to JRI 0.3-5
+
+0.4-10	2006-09-14
+    o	Removed obsolete JNI 1.1 support that is no longer provided
+	in JDK 1.6 and thus prevented rJava from being used with JDK 1.6
+
+    o	Update to JRI 0.3-4 (change compilation to force Java 1.4
+	compatibility even when more recent JDK is used)
+
+0.4-9	2006-09-12
+    o	Update to JRI 0.3-3 which fixes API version mistake which
+
+0.4-8	2006-09-11
+    o	Added --enable-jri=auto option which will build JRI only if R
+	shared library is present. It is now the default.
+
+    o	Update to JRI 0.3-2 (added boolean support)
+
+0.4-7	2006-09-05
+    o	.jevalArray now works with Java objects that have not been
+	cast to a Java array explicitly. The function is now also
+	documented properly.
+
+    o	Added .jgetEx and .jclear functions for querying and clearing
+	of Java exceptions/throwables.
+
+    o	Added .jthrow to allow throwing of exceptions from R code.
+
+    o	Fixed a typo in .jrcall when handling string return values.
+
+0.4-6	2006-08-20
+    o	Fixed bug in initialization on Windows, introduced in 0.4-4
+
+0.4-5	2006-06-24
+    o	Added support for scalar bytes as .jbyte (byte arrays are still
+	natively represented as RAW vectors)
+
+    o	Added .r2j function which allows to push R objects into Java as
+	references. This works only if R is run via JRI, because it
+	requires a working Rengine instance.
+
+0.4-4	2006-06-21
+    o	Fixed bug that prevented loading into existing VM
+	if the classpath contained duplicate items.
+	.jmergeClassPath now filters out duplicate paths.
+
+    o	.jcall and .jnew discard all named parameters that are passed
+	as `...'. Named parameters are now reserved for future call options
+
+    o	Converted all S3-methods into S4 methods.
+	Also `show' is now used instead of `print' and the
+	output format was changed.
+
+    o	Protoype for jobjRef is now a valid null-Object
+
+    o	Added .jequals and corresponding ==, != op methods.
+	Currently == and != operators feature the same behavior as
+	.jequals(...,strict=FALSE), i.e. scalar non-Java objects are
+	converted into Java objects if possible and then compared, so
+	 s <- .jnew("java/lang/String","foo")
+	 s == "foo"  # returns TRUE
+
+    o	Added .jinherits which allows to check Java-side
+	inheritance using JNI (= isAssignableTo).
+
+    o   Added .jfindClass and .jclassRef that return Java
+	class object
+
+    o	Added check parameter to .jcall and .jnew that allows the caller
+	to prevent implicit call to .jcheck
+	It is mainly useful in cases where silent operation
+	is desired (e.g. in conjunction with try).
+	Additionally, silent parameter was added to .jnew
+
+    o	Added is.jnull which is like is.null but also returns
+	TRUE if the supplied Java object is a null-reference
+
+    o	Added jlong class and .jlong function. Those were documented in
+	the tutorial but never really implemented. Still, they may not
+	be supported in all parts of rJava.
+	WARNING: conversion between Java's long and R's jlong is lossy!
+	R stores jlong in doubles so the conversion implies loss of
+	precision.
+
+0.4-3	2006-05-16
+    o	improved, documented and fixed handling of fields
+	.jfield is dedicated accessor with more options
+
+0.4-2	2006-05-08
+    o	Update to JRI 0.2-5 (no change in rJava)
+
+0.4-1	2006-05-05
+    o	Fixed bug in Windows initialization
+
+0.4-0	2006-05-03
+    o	JRI is now included in rJava
+
+0.3-9	2006-04-20
+     o	fixed a minor bug in Rglue.c that may prevent older
+	compilers from compiling it.
+
+0.3-8	2006-04-17
+     o	.jinit has an additional parameter 'parameters' that allows
+	users to pass additional parameters to the VM (such as -X...)
+
+     o	.jinit now uses a hack (defined in .jmergeClassPath) that
+	allows us to modify the class path of a running VM. This may
+	or may not work for a specific VM, because it is an ugly hack
+	exploiting some implementational features of the VM.
+	See .jmergeClassPath source for reference and explanation.
+
+     o	.jarray now supports the use of .jarray(x) where x is a Java
+	reference. The documentation requires you to use
+	.jarray(list(x)), but since the use of .jarray(x) seems to be
+	a very common mistake, we may as well silently support it.
+
+     o	.jarray has an optional parameter contents.class which allows
+	the global specification of the class type for arrays of
+	objects. (Untested, use with care! In most cases .jcast is
+	probably what you really want.)
+
+     o	Added some more support for floats, longs and byte arrays.
+	(Again, untested)
+
+0.3-7	2006-01-31 (non-public release)
+     o	New, experimental feature has been added - JNI cache. This
+	feature can be enabled by passing --enable-jni-cache argument
+	to configure. Normally, each time we access JVM we retrieve
+	new JNI environment to make sure there are no threading
+	issues. In single-threaded environment this is superfluous, so
+	we may as well cache it. The idea is to reduce the
+	overhead. However, the gain is not as huge as expected, so it
+	is not enabled by default. Also note that threads and
+	jni-cache are mutually exclusive.
+
+     o	Another even more experimental feature has been added -
+	support for threads. This feature is enabled by using
+	--enable-threads configure argument. When threads support is
+	enabled, JVM is started on a thread separate from the main
+	thread. Some implementations of AWT classes require
+	this. However, it is not always safe to use, because R event
+	loop is unaware of the separate thread and can deadlock it.
+
+0.3-6	2006-01-30
+0.3-5	2006-01-02
+0.3-4	2005-12-28
+0.3-3	2005-12-20
+0.3	2005-12-19	[finalizers, arrays]
+0.2	2005-09-03	[S4 classes]
+0.1	2003-08-26	[initial release]
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/0classes.R b/com.oracle.truffle.r.pkgs/rJava/R/0classes.R
new file mode 100644
index 0000000000000000000000000000000000000000..5c0a08e069054f06f4332be32f3948d123ed3112
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/0classes.R
@@ -0,0 +1,51 @@
+## S4 classes (jobjRef is re-defined in .First.lib to contain valid jobj)                                                                                                  
+#' java object reference
+setClass("jobjRef", representation(jobj="externalptr", jclass="character"), 
+	prototype=list(jobj=NULL, jclass="java/lang/Object"))
+
+#' rugged arrays
+setClass("jarrayRef", representation("jobjRef", jsig="character"))
+
+#' rectangular java arrays double[][] d = new double[m][n]
+setClass("jrectRef", 
+	representation("jarrayRef", dimension="integer" ) ) 
+
+
+
+# we extend array here so that we can keep dimensions
+# in the helper functions below, the storage mode is 
+# set when the objects are built
+# TODO: maybe an initialize method is needed here
+# TODO: maybe a validate method is needed here as well
+setClass("jfloat", representation("array" ) )
+setClass("jlong", representation("array" )  )
+setClass("jbyte", representation("array" )  )
+setClass("jshort", representation("array" ) )
+setClass("jchar", representation("array" )  )
+
+# there is no way to distinguish between double and float in R, so we need to mark floats specifically
+.jfloat <- function(x) {
+	storage.mode( x ) <- "double"
+	new("jfloat", x )
+}
+# the same applies to long
+.jlong <- function(x) {
+	storage.mode( x ) <- "double"
+	new("jlong", x)
+}
+# and byte
+.jbyte <- function(x) {
+	storage.mode( x ) <- "integer"
+	new("jbyte", x)
+}
+# and short
+.jshort <- function(x){
+	storage.mode( x ) <- "integer"
+	new("jshort", x)
+}
+# and char (experimental)
+.jchar <- function(x){
+	storage.mode( x ) <- "integer"
+	new("jchar", as.integer(x))
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/J.R b/com.oracle.truffle.r.pkgs/rJava/R/J.R
new file mode 100644
index 0000000000000000000000000000000000000000..e4044c9f21e7fb6e7a27ff63628b9a4b0389aea0
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/J.R
@@ -0,0 +1,35 @@
+setClass("jclassName", representation(name="character", jobj="jobjRef"))
+jclassName <- function(class){
+	if( is( class, "jobjRef" ) && .jinherits(class, "java/lang/Class" ) ){
+		jobj <- class
+		name <- .jcall( class, "Ljava/lang/String;", "getName", evalString = TRUE )
+	} else{
+		name <- gsub("/",".",as.character(class))
+		jobj <- .jfindClass(as.character(class))
+	}
+	new("jclassName", name=name, jobj=jobj)
+}
+
+setGeneric("new")
+setMethod("new", signature(Class="jclassName"), function(Class, ...) .J(Class@name, ...))
+
+setMethod("$", c(x="jclassName"), function(x, name) {
+	if( name == "class" ){
+		x@jobj
+	} else if (classHasField(x@jobj, name, TRUE)){
+		.jfield(x@name, , name) 
+	} else if (classHasMethod(x@jobj, name, TRUE)){
+		function(...) .jrcall(x@name, name, ...) 
+	} else if( classHasClass(x@jobj, name, FALSE) ){
+		inner.cl <- .jcall( "RJavaTools", "Ljava/lang/Class;", "getClass", x@jobj, name, FALSE ) 
+		new("jclassName", name=.jcall(inner.cl, "S", "getName"), jobj=inner.cl)
+	} else {
+		stop("no static field, method or inner class called `", name, "' in `", x@name, "'")
+	}
+})
+setMethod("$<-", c(x="jclassName"), function(x, name, value) .jfield(x@name, name) <- value)
+setMethod("show", c(object="jclassName"), function(object) invisible(show(paste("Java-Class-Name:",object@name))))
+setMethod("as.character", c(x="jclassName"), function(x, ...) x@name)
+
+## the magic `J'
+J<-function(class, method, ...) if (nargs() == 1L && missing(method)) jclassName(class) else .jrcall(class, method, ...)
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/arrays.R b/com.oracle.truffle.r.pkgs/rJava/R/arrays.R
new file mode 100644
index 0000000000000000000000000000000000000000..71c64d4e54368fa6cbc8d4c88ce1a33489f42bce
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/arrays.R
@@ -0,0 +1,725 @@
+# :tabSize=4:indentSize=4:noTabs=false:folding=explicit:collapseFolds=1:
+ 
+# {{{ utilities to deal with arrays
+#' Indicates if a object refers to a java array
+#' 
+#' @param o object 
+#' @return TRUE if the object is a java array, FALSE if not
+#'         (including when the object is not even a java reference)
+isJavaArray <- function( o ){
+	if( ( is( o, "jobjRef" ) || is( o, "jarrayRef") || is( o, "jrectRef") ) && !is.jnull(o) ){
+		.jcall( "RJavaArrayTools", "Z", "isArray", .jcast(o) )
+	} else FALSE
+}
+._must_be_java_array <- function( o, message = "object is not a java array" ){
+	if( !isJavaArray(o ) ){
+		stop( message )
+	}
+}
+isJavaArraySignature <- function( sig ){
+	identical( substr( sig, 1, 1 ), '[' )
+}
+
+#' get the component type of a java array
+getComponentType <- function( o, check = TRUE ){
+	if( check ) ._must_be_java_array( o )
+	.jcall( .jcall( o, "Ljava/lang/Class;", "getClass" ), "Ljava/lang/Class;", "getComponentType" )
+}
+
+._jarray_simplify <- function( x ){
+	._must_be_java_array( x )
+	clname <- .jclass(x, true = TRUE )
+	
+	Array <- "java/lang/reflect/Array"
+	obj <- switch( clname, 
+		# deal with array of primitive first
+		"[I"                  = .Call(RgetIntArrayCont   , x@jobj), 
+		"[J"                  = .Call(RgetLongArrayCont  , x@jobj), 
+		"[Z"                  = .Call(RgetBoolArrayCont  , x@jobj) , 
+		"[B"                  = .Call(RgetByteArrayCont  , x@jobj) ,
+		"[D"                  = .Call(RgetDoubleArrayCont, x@jobj) ,
+		"[S"                  = .Call(RgetShortArrayCont , x@jobj) , 
+		"[C"                  = .Call(RgetCharArrayCont  , x@jobj) ,
+		"[F"                  = .Call(RgetFloatArrayCont , x@jobj) , 
+		"[Ljava.lang.String;" = .Call(RgetStringArrayCont, x@jobj),
+		
+		# otherwise, just get the object
+		x )
+	obj
+}
+# }}}
+
+# {{{ length
+#' get the length of the array
+._length_java_array <- function(x){
+	if( isJavaArray( x ) ){
+		.jcall( "java/lang/reflect/Array", "I", "getLength", .jcast( x, check = FALSE, convert.array = FALSE) ) 
+	} else{
+		stop( "the supplied object is not a java array" ) 
+	}
+}
+
+setMethod( "length", "jarrayRef", ._length_java_array )
+setMethod( "length", "jrectRef", ._length_java_array )
+
+setGeneric( "str" )
+setMethod("str", "jarrayRef", function(object, ...){
+	txt <- sprintf( "Formal class 'jarrayRef' [package \"rJava\"] with 2 slots
+  ..@ jobj  :<externalptr>
+  ..@ jclass: chr \"%s\"
+  ..@ jsig  : chr \"%s\"
+", object@jclass, object@jsig )
+    cat( txt )
+} )
+setMethod("str", "jrectRef", function(object, ...){
+	dim <- object@dimension
+	dim.txt <- if( length( dim ) == 1L ){
+		sprintf( "int %d", dim )
+	} else {
+		sprintf( "int[1:%d] %s", length(dim), paste( if( length(dim) > 6 ) c( dim[1:6], "...") else dim, collapse = " ") )
+	}
+	txt <- sprintf( "Formal class 'jrectRef' [package \"rJava\"] with 2 slots
+  ..@ jobj     :<externalptr>
+  ..@ jclass   : chr \"%s\"
+  ..@ jsig     : chr \"%s\"
+  ..@ dimension: %s
+", object@jclass, object@jsig, dim.txt )
+    cat( txt )
+} )
+# }}}
+
+# {{{ single bracket indexing : [
+
+# indexing of .jarrayRef
+# is is not quite clear what the proper result should be, because technically
+# [ should always return a jarrayRef, but it's not the most useful thing to do.
+# the code below (ab)uses drop to try to deal with that, but it's not optimal ... 
+
+# ._jctype <- function(x) if (is.jnull(x)) NA else if(is(x, "jarrayRef")) x@jsig else paste("L", x@jclass, ";", sep='')
+
+# #' index a java array
+# #' 
+# #' @param x a reference to a java array
+# #' @param i indexer (only 1D indexing supported so far)
+# #' @param drop if the result if of length 1, just return the java object instead of an array of length one
+# #' @param simplify further simplify the result
+# ._java_array_single_indexer <- function( x, i, j, drop, simplify = FALSE, silent = FALSE, ... ){
+# 	# arrays only
+# 	
+# 	if( !silent ){
+# 		if( ! missing( j ) ){
+# 			warning( "only one dimensional indexing is currently supported in i, ignoring j argument" )
+# 		}
+# 		dots <- list( ... )
+# 		if( length(dots) ){
+# 			unnamed.dots <- dots[ names(dots) == "" ]
+# 			if( length( unnamed.dots ) ){
+# 				warning( "only one dimensional indexing is currently supported in [, ignoring ... arguments" ) 
+# 			}
+# 		}
+# 	}
+# 	
+# 	# the component type of the array - maybe used to make 
+# 	# arrays with the same component type, but of length 0
+# 	component.type <- getComponentType( x, check = FALSE )
+# 	
+# 	# 'eval' the array
+# 	ja <- .jevalArray( x )
+# 	
+# 	# native type - use R subsetting and maybe remap to java 
+# 	if (!is.list(ja)) { 
+# 		# perform the subset
+# 		o <- ja[i]
+# 		
+# 		# return native type if simplify
+# 		if( simplify ){
+# 			return(o) 
+# 		}
+# 		
+# 		if( length(o) == 0L) {
+# 				# return an array of the same component type as the original array
+# 				# but of length 0
+# 				return( .jcall( "java/lang/reflect/Array", "Ljava/lang/Object;", "newInstance", component.type, 0L  ) )
+# 		} else {
+# 			# drop makes no sense here
+# 			return( .jarray( o ) )
+# 		}
+# 	}
+# 	
+# 	# the result an array of java objects
+# 	sl <- ja[i]
+# 	
+# 	if( length( sl ) == 0L ){
+# 		# TODO: make simplify influencial here
+# 		#       for example if x is int[] then we want to get integer(0)
+# 		return( .jcall( "java/lang/reflect/Array", "Ljava/lang/Object;", "newInstance", component.type, 0L  ) )
+# 	} else{
+# 		# just return the array
+# 		return( .jarray( sl ) )
+# 	}
+# }
+
+# ## this is all weird - we need to distinguish between x[i] and x[i,] yet S4 fails to do so ...
+setMethod( "[", signature( x = "jarrayRef" ), 
+	function(x, i, j, ..., drop = FALSE){
+		# the code above is not good enough
+		.NotYetImplemented()
+	} )
+# }}}
+
+# {{{ double bracket indexing : [[
+._collectIndex <- function( i, j, ...){
+	dots <- list( ... )
+	unnamed.dots <- if( length( dots ) ){
+		dots[ names(dots) == "" ]
+	}
+	
+	firstInteger <- function(.) as.integer(.)[1]
+	firstIntegerOfEach <- function(.) sapply( ., firstInteger )
+	
+	index <- c( 
+		if( !missing(i) ) firstInteger(i), 
+		if( !missing(j) ) firstInteger(j), 
+		if( !is.null(unnamed.dots) && length(unnamed.dots) ) firstIntegerOfEach( unnamed.dots )
+		)
+}
+
+# R version of RJavaArrayTools#getDimensionLength
+# it only works on the signature so should be used with caution
+getDimensionLength <- function( x, true.class = TRUE ){
+	nchar( sub( "[^[]+", "", .jclass(x, true = true.class) ) )
+}
+
+# R version of RJavaArrayTools#getObjectTypeName
+getObjectTypeName <- function( x, true.class=TRUE){
+	sub( "^[[]*(.*);?$", "\\1", .jclass(x, true = true.class) )
+}
+
+._java_array_double_indexer <- function( x, i, j, ..., evalArray = FALSE, evalString = FALSE ){
+	# initial checks
+	._must_be_java_array( x )
+	index <- ._collectIndex( i, j, ... )
+	
+	if( !length(index) || is.null(index) ){
+		# return the full object
+		x
+	} else{
+		
+		# shift one left (java style indexing starts from 0 )
+		index <- index - 1L
+		depth <- getDimensionLength( x )
+		typename <- getObjectTypeName( x )
+		
+		if( length( index) == depth ){
+			# we need to dispatch primitive 
+			if( isPrimitiveTypeName( typename ) ){ 
+				res <- switch( typename, 
+					# deal with array of primitive first
+					"I"                  =  .jcall( "RJavaArrayTools", "I", "getInt"    , .jcast(x), index ) , 
+					"J"                  =  .jcall( "RJavaArrayTools", "J", "getLong"   , .jcast(x), index ) , 
+					"Z"                  =  .jcall( "RJavaArrayTools", "Z", "getBoolean", .jcast(x), index ) , 
+					"B"                  =  .jcall( "RJavaArrayTools", "B", "getByte"   , .jcast(x), index ) ,
+					"D"                  =  .jcall( "RJavaArrayTools", "D", "getDouble" , .jcast(x), index ) ,
+					"S"                  =  .jcall( "RJavaArrayTools", "S", "getShort"  , .jcast(x), index ) , 
+					"C"                  =  .jcall( "RJavaArrayTools", "C", "getChar"   , .jcast(x), index ) ,
+					"F"                  =  .jcall( "RJavaArrayTools", "F", "getFloat"  , .jcast(x), index ), 
+					stop( "wrong primitive" ) # should never happen 
+				)
+				return( res )
+			} 
+			
+		}
+		
+		# otherwise use the Object version
+		.jcall( "RJavaArrayTools", "Ljava/lang/Object;", "get",  .jcast(x), index, 
+			evalArray = evalArray, evalString = evalString ) 
+	}
+
+}
+
+# this is the only case that makes sense: i is an integer or a numeric of length one
+# we cannot use logical indexing or indexing by name because there is no such thing in java
+setMethod( "[[", signature( x = "jarrayRef" ), 
+	function(x, i, j, ...){
+		._java_array_double_indexer( x, i, j, ... )
+	} )
+
+._java_array_double_replacer <- function( x, i, j, ..., value ){
+	# initial checks
+	._must_be_java_array( x )
+	
+	index <- ._collectIndex( i, j, ... )
+	
+	if( !length(index) || is.null(index) ){
+		# allow for x[[]] <- value
+		newArray( value , simplify = FALSE )
+	} else{
+		jvalue <- ._java_valid_object( value )
+		if( ._isPrimitiveReference( value ) ){
+			# then use a primitive version
+			.jcall( "RJavaArrayTools", "V", "set",  .jcast(x),
+				index - 1L, value )  
+		} else{
+			# use the Object version
+			.jcall( "RJavaArrayTools", "V", "set",  .jcast(x),
+				index - 1L, .jcast( jvalue ) )
+			if( isJavaArray( jvalue ) ){
+				# rectangularity might have changed
+				# we have no choice but to reset the array
+				x <- newArray( jobj = x@jobj, signature = x@jsig )
+			}
+		}
+		x
+	}
+	
+}
+
+setReplaceMethod( "[[", signature( x = "jarrayRef" ), 
+function(x, i, j, ..., value ){
+	._java_array_double_replacer( x, i, j, ..., value = value)
+} )
+# }}}
+
+# {{{ head and tail
+setGeneric( "head" )
+setMethod("head", signature( x = "jarrayRef" ), function(x, n = 6L, ... ){
+	if( !isJavaArray( x ) ){
+		stop( "not a java array" )
+	}
+	# FIXME : this only makes sense for 1d arays
+	n_objs <- length(x)
+	if( abs( n ) >= n_objs ){
+		return( x )
+	}
+	len <- if( n > 0L ) n else n_objs + n
+	x[seq_len(n), ... ]
+} )
+
+setGeneric( "tail" )
+setMethod("tail", signature( x = "jarrayRef" ), function(x, n = 6L, ... ){
+	if( !isJavaArray( x ) ){
+		stop( "not a java array" )
+	}
+	# FIXME : this only makes sense for 1d arays
+	n_objs <- length(x)
+	if( abs( n ) >= n_objs ) return(x)
+	if( n < 0L){ 
+		n <- n_objs + n
+	}
+	return( x[ seq.int( n_objs-n+1, n_objs ) , ... ] )
+} )
+# }}}
+
+# {{{ newArray - dispatch to jarrayRef or jrectRef
+#' creates a new jarrayRef or jrectRef depending on the rectangularity
+#' of the array
+#' 
+#' @param o a jobjRef object
+#' @param simplify if TRUE and the result is a rectangular array 
+#' of primitives, simplify it to an R object
+newArray <- function( o, simplify = TRUE, jobj, signature ){
+	if( !missing(jobj) ){
+		o <- new("jobjRef", jobj = jobj, jclass = signature)
+	}
+	if( !isJavaArray( o ) ){
+		stop( "o does not refer to a java array" )
+	}
+	if( inherits( o, "jrectRef" ) ){
+		# no need to go further
+		return(o)
+	}
+	
+	clazz <- tojni( .jclass( o, true = TRUE ) )
+	wrapper <- .jnew("ArrayWrapper", .jcast(o) )
+	isRect <- .jcall( wrapper, "Z", "isRectangular" )
+	if( isRect ){
+		dims <- .jcall( wrapper, "[I", "getDimensions" )
+		
+		if( !simplify ){
+			# no need to go further down, return a reference 
+			return( new( "jrectRef", jobj = o@jobj, jsig = clazz, jclass = clazz, 
+				dimension = dims ) )
+		}
+		
+		isprim <- .jcall( wrapper, "Z", "isPrimitive" )
+		typename <- .jcall( wrapper, "Ljava/lang/String;", "getObjectTypeName" )
+		isstrings <- identical( typename, "java.lang.String" )
+		
+		if( !isprim && !isstrings ){
+			# cannot simplify, return a reference
+			return( new( "jrectRef", jobj = o@jobj, jsig = clazz, jclass = clazz, 
+				dimension = dims ) )
+		}
+		
+		if( isprim || isstrings ){
+			# array of java primitives, we can translate this to R array
+			out <- structure( switch( typename , 
+				"I"                = .jcall( wrapper, "[I"                 , "flat_int" ), 
+				"Z"                = .jcall( wrapper, "[Z"                 , "flat_boolean" ),
+				"B"                = .jcall( wrapper, "[B"                 , "flat_byte" ),
+				"J"                = .jlong( .jcall( wrapper, "[J"                 , "flat_long" ) ),
+				"S"                = .jshort( .jcall( wrapper, "[T"                 , "flat_short" ) ), # [T is remapped to [S in .jcall 
+				"D"                = .jcall( wrapper, "[D"                 , "flat_double" ),
+				"C"                = .jchar( .jcall( wrapper, "[C"                 , "flat_char" ) ),
+				"F"                = .jfloat( .jcall( wrapper, "[F"                 , "flat_float" ) ), 
+				"java.lang.String" = .jcall( wrapper, "[Ljava/lang/String;", "flat_String" ), 
+				stop( sprintf("cannot simplify type : ", typename) ) # this should not happen
+				), dim = dims )
+			return( out )
+		}
+		
+	} else {
+		# not a rectangular array -> jarrayRef
+		new( "jarrayRef", jobj = o@jobj, jsig = clazz, jclass = clazz ) 
+	}
+}
+# }}}
+
+# {{{ [ indexing of rectangular arrays
+setMethod( "[", signature( x = "jrectRef" ), 
+	function(x, i, j, ..., simplify = FALSE, drop = TRUE ){
+		
+		# first we extract th data as a flat (one dimensional) R array
+		# called 'flat'
+		
+		dim <- x@dimension
+		wrapper <- .jnew( "ArrayWrapper", .jcast(x) )
+		
+		typename <- .jcall( wrapper, "Ljava/lang/String;", "getObjectTypeName" )
+		isprim   <- .jcall( wrapper, "Z", "isPrimitive" )
+		
+		flat <- switch( typename, 
+			"I"                = .jcall( wrapper, "[I"                  , "flat_int"     , evalArray = TRUE ), 
+			"Z"                = .jcall( wrapper, "[Z"                  , "flat_boolean" , evalArray = TRUE ),
+			"B"                = .jcall( wrapper, "[B"                  , "flat_byte"    , evalArray = TRUE ),
+			"J"                = .jcall( wrapper, "[J"                  , "flat_long"    , evalArray = TRUE ),
+			"S"                = .jcall( wrapper, "[T"                  , "flat_short"   , evalArray = TRUE ), # [T is remapped to [S in .jcall 
+			"D"                = .jcall( wrapper, "[D"                  , "flat_double"  , evalArray = TRUE ),
+			"C"                = .jcall( wrapper, "[C"                  , "flat_char"    , evalArray = TRUE ) ,
+			"F"                = .jcall( wrapper, "[F"                  , "flat_float"   , evalArray = TRUE ), 
+			"java.lang.String" = .jcall( wrapper, "[Ljava/lang/String;" , "flat_String"  , evalArray = TRUE ), 
+			                     .jcall( wrapper, "[Ljava/lang/Object;" , "flat_Object"  , evalArray = TRUE ) )
+			                     
+        # then we give to flat the correct dimensions
+		if( length(dim) != 1L ){
+			 dim( flat ) <- dim
+		}
+		
+		# now we construct the call to '[' on flat.
+		# this call uses all the regular R indexing 
+		call <- match.call(  call = sys.call(sys.parent()) )
+		n.args <- nargs( )
+		
+		e <- as.list( call )[ -(1:2) ]
+		names.e <- names(e)
+		if( any( have.name <- (names.e != "") ) ){
+			# we need to extract drop and simplify
+			nam <- names.e[ have.name ]
+			if( !all( nam %in% c("simplify", "drop", "i", "j" ) ) ){
+				stop( "only 'drop' and 'simplify' are allowed as named arguments, they need to be written exactly" ) 
+			}
+		}
+		
+		if( missing(i) && missing(j) && all( names.e != "" ) ){
+			# special case with no indexing at all
+			actual.call <- sprintf( "flat[  , drop = %s ]", as.character(drop) )
+		} else if( !missing(i) && missing(j) && all( names.e != "" ) ){
+			# special case where there is only one index
+			actual.call <- sprintf( "flat[ %s , drop = %s ]", deparse(i), as.character(drop) ) 
+		} else{
+			# we need to be careful about the missing's
+			# we cannot just do things like list(...) because with missings
+			# it just does not work
+			actual.call <- "flat["
+			
+			itoken <- if( missing(i ) ) " " else deparse(i)
+			jtoken <- if( missing(j ) ) " " else deparse(j)
+			
+			actual.call <- sprintf( "flat[ %s , %s", itoken, jtoken )
+			
+			iii <- 1L
+			for( a in e ){
+				if( missing(a) ){
+					actual.call <- sprintf( "%s , ", actual.call )
+				} else if( have.name[iii] ) {
+					# we put both at the end
+				} else {
+					# not missing, not named
+					actual.call <- sprintf( "%s, %s", actual.call, deparse(a) )
+				}
+				iii <- iii + 1L 
+			}
+			actual.call <- sprintf( "%s, drop = %s ]", actual.call, as.character(drop) )
+		}
+		
+		# now we eval the call 
+		subs <- eval( parse( text = actual.call ) )
+		
+		# now if we need and can simplify it, we return the subsetted array as is
+		# otherwise, we rewrap it to java
+		if( simplify && (typename == "java.lang.String" || isprim ) ) subs else .jarray( subs, dispatch = TRUE )
+
+	} )
+# }}}
+
+# {{{ dim.jrectRef 
+setMethod( "dim", signature( x = "jrectRef" ), function(x) x@dimension )
+setReplaceMethod( "dim", signature( x = "jrectRef" ), function(x, value){
+	
+	expected_prod <- prod( x@dimension )
+	
+	if( is.null( value ) ){
+		value <- expected_prod
+	} else{
+		received_prod <- prod(value)
+		if( received_prod != expected_prod ){
+			stop( sprintf("dims [product %d] do not match the length of object [%d]", received_prod, expected_prod ) ) 
+		}
+	}
+	dim <- x@dimension
+	wrapper <- .jnew( "ArrayWrapper", .jcast(x) )
+	
+	typename <- .jcall( wrapper, "Ljava/lang/String;", "getObjectTypeName" )
+	
+	flat <- structure( 
+			switch( typename, 
+			"I"                = .jcall( wrapper, "[I"                  , "flat_int"     , evalArray = TRUE ), 
+			"Z"                = .jcall( wrapper, "[Z"                  , "flat_boolean" , evalArray = TRUE ),
+			"B"                = .jcall( wrapper, "[B"                  , "flat_byte"    , evalArray = TRUE ),
+			"J"                = .jcall( wrapper, "[J"                  , "flat_long"    , evalArray = TRUE ),
+			"S"                = .jcall( wrapper, "[T"                  , "flat_short"   , evalArray = TRUE ), # [T is remapped to [S in .jcall 
+			"D"                = .jcall( wrapper, "[D"                  , "flat_double"  , evalArray = TRUE ),
+			"C"                = .jcall( wrapper, "[C"                  , "flat_char"    , evalArray = TRUE ) ,
+			"F"                = .jcall( wrapper, "[F"                  , "flat_float"   , evalArray = TRUE ), 
+			"java.lang.String" = .jcall( wrapper, "[Ljava/lang/String;" , "flat_String"  , evalArray = TRUE ), 
+			                     .jcall( wrapper, "[Ljava/lang/Object;" , "flat_Object"  , evalArray = TRUE ) ) , 
+		dim = value )
+		                     
+	.jarray(flat, dispatch = TRUE)
+	
+} )
+# }}}
+
+PRIMITIVE_TYPES <- c( "I",  "Z",  "B",  "J",  "S",  "D",  "C",  "F" )
+isPrimitiveTypeName <- function( type, include.strings = TRUE ){
+	type %in% PRIMITIVE_TYPES || ( include.strings && identical( type, "java.lang.String" ) )
+}
+PRIMITIVE_TYPES_RX <- sprintf( "^[[]+[%s]$" , paste( PRIMITIVE_TYPES, collapse = "" ) )
+isPrimitiveArraySignature <- function( x, ... ){
+	regexpr( PRIMITIVE_TYPES_RX, x, ... ) > 0
+}
+isArraySignature <- function( x ){
+	substr( x, 1, 1 ) == "["
+}
+
+# {{{ unique.jarrayRef
+setGeneric( "unique" )
+._unique_jrectRef <- function( x, incomparables = FALSE, ...){
+	
+	dim <- x@dimension
+	
+	if( length( dim ) > 1L ){
+		stop( "'unique' only implemented for 1d array so far" )
+	}
+	
+	typename <- .jcall( "RJavaArrayTools", "Ljava/lang/String;", 
+		"getObjectTypeName", .jcast(x) )
+	
+	if( isPrimitiveTypeName( typename, include.strings = TRUE ) ){
+		.jarray( unique( .jevalArray( x ) ), dispatch = TRUE )
+	} else{
+		.jcall( "RJavaArrayTools", "[Ljava/lang/Object;", "unique",
+			.jcast( x, "[Ljava/lang/Object;" ), evalArray = TRUE, simplify = TRUE )
+	}
+}
+
+setMethod( "unique", "jarrayRef", function(x, incomparables = FALSE, ...){
+	.NotYetImplemented()
+} )
+setMethod( "unique", "jrectRef", ._unique_jrectRef )
+# }}}
+
+# {{{ duplicated
+setGeneric( "duplicated" )
+._duplicated_jrectRef <- function( x, incomparables = FALSE, ...){
+	
+	dim <- x@dimension
+	
+	if( length( dim ) > 1L ){
+		stop( "'duplicated' only implemented for 1d array so far" )
+	}
+	
+	typename <- .jcall( "RJavaArrayTools", "Ljava/lang/String;", 
+		"getObjectTypeName", .jcast(x) )
+	
+	if( isPrimitiveTypeName( typename, include.strings = TRUE ) ){
+		duplicated( .jevalArray( x ) )
+	} else{
+		.jcall( "RJavaArrayTools", "[Z", "duplicated",
+			.jcast( x, "[Ljava/lang/Object;" ), evalArray = TRUE )
+	}
+}
+setMethod( "duplicated", "jrectRef", ._duplicated_jrectRef )
+setMethod( "duplicated", "jarrayRef", function( x, incomparables = FALSE, ...){
+	.NotYetImplemented()
+})
+# }}}
+
+# {{{ anyDuplicated
+.base.has.anyDuplicated <- exists("anyDuplicated", asNamespace("base"))
+if (!.base.has.anyDuplicated) {
+	anyDuplicated <- function(x, incomparables = FALSE, ...) UseMethod("anyDuplicated")
+}
+setGeneric( "anyDuplicated" )
+._anyduplicated_jrectRef <- function( x, incomparables = FALSE, ...){
+	
+	dim <- x@dimension
+	if( length( dim ) > 1L ){
+		stop( "'anyDuplicated' only implemented for 1d array so far" )
+	}
+	typename <- .jcall( "RJavaArrayTools", "Ljava/lang/String;", 
+		"getObjectTypeName", .jcast(x) )
+	if( isPrimitiveTypeName( typename, include.strings = TRUE ) ){
+		anyDuplicated( .jevalArray( x ) )
+	} else{
+		.jcall( "RJavaArrayTools", "I", "anyDuplicated",
+			.jcast( x, "[Ljava/lang/Object;" ), evalArray = TRUE ) + 1L
+	}
+}
+setMethod( "anyDuplicated", "jrectRef", ._anyduplicated_jrectRef )
+setMethod( "anyDuplicated", "jarrayRef", function( x, incomparables = FALSE, ...){
+	.NotYetImplemented()
+})
+# }}}
+
+# {{{ flat
+#' utility to flatten an array
+flat <- function(x, simplify = FALSE){
+	stop( "undefined" ) 
+}
+setGeneric( "flat")
+._flat_jrectRef <- function( x, simplify = FALSE ){
+	dim <- dim(x)
+	if( length(dim) == 1L ) {
+		if( !simplify) x else x[ simplify = TRUE ]
+	} else {
+		x[ seq_len(prod(dim)), drop = TRUE, simplify = simplify ]
+	}
+}
+setMethod( "flat", "jrectRef", ._flat_jrectRef )
+setMethod( "flat", "jarrayRef", function(x, simplify=FALSE){
+	.NotYetImplemented()
+} )
+# }}}
+
+# {{{ sort
+setGeneric( "sort" )
+._sort_jrectRef <- function( x, decreasing = FALSE, ...){
+	
+	x <- flat( x ) 
+	dim <- x@dimension
+	typename <- .jcall( "RJavaArrayTools", "Ljava/lang/String;", 
+		"getObjectTypeName", .jcast(x) )
+	
+	if( isPrimitiveTypeName( typename, include.strings = TRUE ) ){
+		.jarray( sort( .jevalArray( x ), decreasing = decreasing ), dispatch = TRUE )
+	} else{
+		.jcall( "RJavaArrayTools", "[Ljava/lang/Object;", "sort",
+			.jcast( x, "[Ljava/lang/Object;" ), decreasing, evalArray = TRUE, simplify = TRUE )
+	}
+
+}
+setMethod( "sort", "jrectRef", ._sort_jrectRef )
+setMethod( "sort", "jarrayRef", function(x, decreasing=FALSE, ...){
+	.NotYetImplemented()
+})
+# }}}
+
+# {{{ rev
+setGeneric( "rev" )
+setMethod( "rev", "jrectRef", function(x){
+	x <- flat( x ) 
+	dim <- x@dimension
+	typename <- .jcall( "RJavaArrayTools", "Ljava/lang/String;", 
+		"getObjectTypeName", .jcast(x) )
+	
+	if( isPrimitiveTypeName( typename, include.strings = TRUE ) ){
+		.jarray( rev( .jevalArray( x ) ), dispatch = TRUE )
+	} else{
+		.jcall( "RJavaArrayTools", "[Ljava/lang/Object;", "rev",
+			.jcast( x, "[Ljava/lang/Object;" ), evalArray = TRUE, simplify = TRUE )
+	}
+
+} )
+setMethod( "rev", "jarrayRef", function(x){
+	.NotYetImplemented()
+}) 
+# }}}
+
+# {{{ as.list
+# S4 dispatch does not work
+as.list.jarrayRef <- function(x, ... ){
+	.jevalArray( x )
+}
+as.list.jrectRef <- function( x, ...){
+	.jevalArray( x )
+}
+as.list.jobjRef <- function( x, ... ){
+	if( ! .jinstanceof( x, "java.lang.Iterable" ) ){
+ 		stop( "only objects that implements java.lang.Iterable can be converted to lists" )
+ 	}
+ 	.jcall( "RJavaArrayTools", "[Ljava/lang/Object;", 
+ 		"getIterableContent", .jcast(x, "java/lang/Iterable") , evalArray = TRUE, ... )
+}
+# }}}
+
+# {{{ min, max, range
+setMethod("min", "jrectRef", function(x, ...,na.rm=TRUE){ 
+	
+	dim <- x@dimension
+	typename <- .jcall( "RJavaArrayTools", "Ljava/lang/String;", 
+		"getObjectTypeName", .jcast(x) )
+	if( isPrimitiveTypeName( typename, include.strings = TRUE ) ){
+		min( x[simplify=TRUE], na.rm = na.rm )
+	} else{
+		summarizer <- .jnew( "RectangularArraySummary", .jcast(x), dim )
+		.jcall( summarizer, "Ljava/lang/Object;", "min", na.rm )
+	}
+	
+} )
+setMethod("min", "jarrayRef", function(x, ...,na.rm=TRUE){ 
+	.NotYetImplemented()
+}) 
+setMethod("max", "jrectRef", function(x, ..., na.rm=TRUE){ 
+	
+	dim <- x@dimension
+	typename <- .jcall( "RJavaArrayTools", "Ljava/lang/String;", 
+		"getObjectTypeName", .jcast(x) )
+	if( isPrimitiveTypeName( typename, include.strings = TRUE ) ){
+		max( x[simplify=TRUE], na.rm = na.rm )
+	} else{
+		summarizer <- .jnew( "RectangularArraySummary", .jcast(x), dim )
+		.jcall( summarizer, "Ljava/lang/Object;", "max", na.rm )
+	}
+	
+} )
+setMethod("max", "jarrayRef", function(x, ..., na.rm=TRUE){
+	.NotYetImplemented()
+} )
+setMethod("range", "jrectRef", function(x, ..., na.rm=TRUE){ 
+	
+	dim <- x@dimension
+	typename <- .jcall( "RJavaArrayTools", "Ljava/lang/String;", 
+		"getObjectTypeName", .jcast(x) )
+	if( isPrimitiveTypeName( typename, include.strings = TRUE ) ){
+		range( x[simplify=TRUE], na.rm = na.rm )
+	} else{
+		summarizer <- .jnew( "RectangularArraySummary", .jcast(x), dim )
+		.jcall( summarizer, "[Ljava/lang/Object;", "range", na.rm, evalArray = TRUE, simplify = TRUE )
+	}
+	
+} )
+setMethod("range", "jarrayRef", function(x, ..., na.rm=TRUE){ 
+	.NotYetImplemented()
+}) 
+# }}}
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/call.R b/com.oracle.truffle.r.pkgs/rJava/R/call.R
new file mode 100644
index 0000000000000000000000000000000000000000..9ffcc20ff3c4ff16a237c53bff816bf09014e205
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/call.R
@@ -0,0 +1,388 @@
+## This file is part of the rJava package - low-level R/Java interface
+## (C)2006 Simon Urbanek <simon.urbanek@r-project.org>
+## For license terms see DESCRIPTION and/or LICENSE
+##
+## $Id$
+
+# create a new object
+.jnew <- function(class, ..., check=TRUE, silent=!check, class.loader=NULL) {
+  class <- gsub("\\.", "/", as.character(class)) # allow non-JNI specifiation
+  # TODO: should this do "S" > "java/lang/String", ... like .jcall
+  
+  if (check) .jcheck(silent=TRUE)
+  o<-.External(RcreateObject, class, ..., silent=silent, class.loader=class.loader)
+  if (check) .jcheck(silent=silent)
+  if (is.null(o)) {
+  	  if (!silent) {
+    	  stop("Failed to create object of class `",class,"'")
+      } else {
+    	  o <- .jzeroRef
+      }
+  }
+  new("jobjRef", jobj=o, jclass=class)
+}
+
+# create a new object reference manually (avoid! for backward compat only!) 
+# the problem with this is that you need a valid `jobj' which 
+# is implementation-dependent so it is undefined outside rJava internals
+# it is now used by JRI.createRJavaRef, though
+.jmkref <- function(jobj, jclass="java/lang/Object") {
+  new("jobjRef", jobj=jobj, jclass=gsub('\\.','/',as.character(jclass)))
+}
+
+# evaluates an array reference. If rawJNIRefSignature is set, then obj is not assumed to be
+# jarrayRef, but rather direct JNI reference with the corresponding signature
+.jevalArray <- function(obj, rawJNIRefSignature=NULL, silent=FALSE, simplify=FALSE) {
+  jobj<-obj
+  sig<-rawJNIRefSignature
+  if (is.null(rawJNIRefSignature)) {
+    if(!inherits(obj,"jarrayRef")) {
+      if (!inherits(obj,"jobjRef"))
+        stop("object is not a Java object reference (jobjRef/jarrayRef).")
+      cl <- gsub("\\.","/",.jclass(obj))
+      if (is.null(cl) || !isJavaArraySignature(cl) )
+        stop("object is not a Java array.")
+      sig <- cl
+    } else sig <- obj@jsig
+    jobj<-obj@jobj
+  } else if (is(obj, "jobjRef")) jobj<-obj@jobj
+  if (sig=="[I")
+    return(.Call(RgetIntArrayCont, jobj))
+  else if (sig=="[J")
+    return(.Call(RgetLongArrayCont, jobj))
+  else if (sig=="[Z")
+    return(.Call(RgetBoolArrayCont, jobj))
+  else if (sig=="[B")
+    return(.Call(RgetByteArrayCont, jobj))
+  else if (sig=="[D")
+    return(.Call(RgetDoubleArrayCont, jobj))
+  else if (sig=="[S")
+    return(.Call(RgetShortArrayCont, jobj))
+  else if (sig=="[C")
+    return(.Call(RgetCharArrayCont, jobj))
+  else if (sig=="[F")
+    return(.Call(RgetFloatArrayCont, jobj))
+  else if (sig=="[Ljava/lang/String;")
+    return(.Call(RgetStringArrayCont, jobj))
+  else if (sig=="[Ljava/lang/Double;" && simplify) {
+    obj@jclass <- sig; return(.jcall("RJavaArrayTools", "[D", "unboxDoubles", obj)) }
+  else if (sig=="[Ljava/lang/Integer;" && simplify) {
+    obj@jclass <- sig; return(.jcall("RJavaArrayTools", "[I", "unboxIntegers", obj)) }
+  else if (sig=="[Ljava/lang/Boolean;" && simplify) {
+    obj@jclass <- sig; return(as.logical(.jcall("RJavaArrayTools", "[I", "unboxBooleans", obj))) }
+  else if (substr(sig,1,2)=="[L")
+    return(lapply(.Call(RgetObjectArrayCont, jobj),
+                  function(x) new("jobjRef", jobj=x, jclass=substr(sig, 3, nchar(sig)-1)) ))
+  else if (substr(sig,1,2)=="[[") {
+    if (simplify) { # try to figure out if this is a rectangular array in which case we can do better
+      o <- newArray(simplify=TRUE, jobj=jobj, signature=sig)
+      # if o is not a reference then we were able to simplify it
+      if (!is(o, "jobjRef")) return(o)
+    }
+    # otherwise simplify has no effect
+    return(lapply(.Call(RgetObjectArrayCont, jobj),
+                  function(x) newArray(jobj=x, signature=substr(sig, 2, 999), simplify=simplify)))
+  }
+  # if we don't know how to evaluate this, issue a warning and return the jarrayRef
+  if (!silent)
+    warning(paste("I don't know how to evaluate an array with signature",sig,". Returning a reference."))
+  newArray(jobj = jobj, signature = sig, simplify = FALSE)
+}
+
+.jcall <- function(obj, returnSig="V", method, ..., evalArray=TRUE, 
+	evalString=TRUE, check=TRUE, interface="RcallMethod", 
+	simplify=FALSE, use.true.class = FALSE) {
+  if (check) .jcheck()
+  iaddr <- .env[[interface]]
+  interface <- if (is.null(iaddr)) getNativeSymbolInfo(interface, "rJava", TRUE, FALSE)$address else iaddr
+  r<-NULL
+  # S is a shortcut for Ljava/lang/String;
+  if (returnSig=="S")
+    returnSig<-"Ljava/lang/String;"
+  if (returnSig=="[S")
+    returnSig<-"[Ljava/lang/String;"
+  # original S (short) is now mapped to T so we need to re-map it (we don't really support short, though)
+  if (returnSig=="T") returnSig <- "S"
+  if (returnSig=="[T") returnSig <- "[S"
+  
+  if (inherits(obj,"jobjRef") || inherits(obj,"jarrayRef") || inherits(obj,"jrectRef") )
+    r<-.External(interface, obj@jobj, returnSig, method, ...)
+  else
+    r<-.External(interface, as.character(obj), returnSig, method, ...)
+  if (returnSig=="V") return(invisible(NULL))
+  
+  if( use.true.class && !is.null( r ) ){
+  	  if( ! ( isPrimitiveTypeName(returnSig) || isArraySignature(returnSig) ) ){
+  	  	  # avoid calling .jcall since we work on external pointers directly here
+  	  	  clazz     <- .External(interface, r    , "Ljava/lang/Class;", "getClass")
+  	  	  clazzname <- .External(interface, clazz, "Ljava/lang/String;", "getName")
+  	  	  clazzname <- .External(RgetStringValue, clazzname)
+  	  	  returnSig <- tojniSignature( clazzname ) 
+  	  }
+  }
+  
+  if (isJavaArraySignature(returnSig)) {
+      # eval or return a reference
+      r <- if (evalArray) .jevalArray(r, rawJNIRefSignature=returnSig, simplify=simplify) else newArray(jobj = r, signature = returnSig, simplify = FALSE)
+  } else if ( substr(returnSig,1,1)=="L") {
+  	  if (is.null(r)){
+  	  	  if( check ) .jcheck( silent = FALSE )
+  	  	  return(r)
+  	  }
+    
+  	if (returnSig=="Ljava/lang/String;" && evalString){
+      if( check ) .jcheck( silent = FALSE )
+  	  return(.External(RgetStringValue, r))
+    }
+    r <- new("jobjRef", jobj=r, jclass=substr(returnSig,2,nchar(returnSig)-1))
+  }
+  if (check) .jcheck()
+  if (.conv.in$.) .convert.in(r) else r
+}
+
+.jstrVal <- function(obj) {
+  # .jstrVal(.jstrVal(...)) = .jstrVal(...)
+  if (is.character(obj))
+    return(obj)
+  r<-NULL
+  if (!is(obj,"jobjRef"))
+    stop("can get value of Java objects only")
+  if (!is.null(obj@jclass) && obj@jclass=="lang/java/String")
+    r<-.External(RgetStringValue, obj@jobj)
+  else
+    r<-.External(RtoString, obj@jobj)
+  r
+}
+
+#' casts java object into new.class
+#' 
+#' @param obj a java object reference
+#' @param new.class the new class (in JNI or Java)
+#' @param check logical. If TRUE the cast if checked
+#' @param convert.array logical. If TRUE and the new class represents an array, then a jarrayRef object is made
+.jcast <- function(obj, new.class="java/lang/Object", check = FALSE, convert.array = FALSE) {
+  if (!is(obj,"jobjRef"))
+    stop("cannot cast anything but Java objects")
+  if( check && !.jinstanceof( obj, new.class) ){
+  	  stop( sprintf( "cannot cast object to '%s'", new.class ) ) 
+  }
+  
+  new.class <- gsub("\\.","/", as.character(new.class)) # allow non-JNI specifiation
+  if( convert.array && !is( obj, "jarrayRef" ) && isJavaArray( obj ) ){
+  	 r <- .jcastToArray( obj, signature = new.class)
+  } else {
+  	 r <- obj
+  	 r@jclass <- new.class
+  }
+  r
+}
+
+# makes sure that a given object is jarrayRef 
+.jcastToArray <- function(obj, signature=NULL, class="", quiet=FALSE) {
+  if (!is(obj, "jobjRef"))
+    return(.jarray(obj))
+  if (is.null(signature)) {
+  	  # TODO: factor out these two calls into a separate function
+    cl <- .jcall(obj, "Ljava/lang/Class;", "getClass")
+    cn <- .jcall(cl, "Ljava/lang/String;", "getName")
+    if ( !isJavaArraySignature(cn) ) {
+      if (quiet)
+        return(obj)
+      else
+        stop("cannot cast to array, object signature is unknown and class name is not an array")
+    }
+    signature <- cn
+  } else{
+  	  if( !isJavaArraySignature(signature) ){
+  	  	  if( quiet ) {
+  	  	  	  return( obj )
+  	  	  } else{
+  	  	  	  stop( "cannot cast to array, signature is not an array signature" )
+  	  	  }
+  	  }
+  }
+  signature <- gsub('\\.', '/', signature)
+  if (inherits(obj, "jarrayRef")) {
+    obj@jsig <- signature
+    return(obj)
+  }
+  newArray(obj, simplify=FALSE)
+}
+
+# creates a new "null" object of the specified class
+# although it sounds weird, the class is important when passed as
+# a parameter (you can even cast the result)
+.jnull <- function(class="java/lang/Object") { 
+  new("jobjRef", jobj=.jzeroRef, jclass=as.character(class))
+}
+
+.jcheck <- function(silent=FALSE) invisible(.Call(RJavaCheckExceptions, silent))
+
+.jproperty <- function(key) {
+  if (length(key)>1)
+    sapply(key, .jproperty)
+  else
+    .jcall("java/lang/System", "S", "getProperty", as.character(key)[1])
+}
+
+#' gets the dim of an array, or its length if it is just a vector
+getDim <- function(x){
+	dim <- dim(x)
+	if( is.null( dim ) ) dim <- length(x)
+	dim
+}
+
+.jarray <- function(x, contents.class = NULL, dispatch = FALSE) {
+	# this already is an array, so don't bother
+	if( isJavaArray( x ) ) return( newArray( x, simplify = FALSE) ) 
+	
+	# this is a two stage process, first we need to convert into 
+	# a flat array using the jni code
+	# TODO: but this needs to move to the internal jni world to avoid 
+	#       too many copies
+	
+	# common mistake is to not specify a list but just a single Java object
+	# but, well, people just keep doing it so we may as well support it 
+	dim <- if (inherits(x,"jobjRef")) {
+		x <- list(x)
+		1L
+	} else getDim(x)
+
+	# the jni call
+	array <- .Call(RcreateArray, x, contents.class)
+	
+	if (!dispatch) return( array )
+	
+	if( is.list( x ) ){
+		# if the input of RcreateArray was a list, we need some more care
+		# because we cannot be sure the array is rectangular so we have to 
+		# check it 
+		newArray( array, simplify = FALSE )
+	} else {
+	
+		# then we transform this to a rectangular array of the proper dimensions
+		if( length( dim ) == 1L ) {
+			# single dimension array
+			new( "jrectRef", jobj = array@jobj, jsig = array@jsig, 
+					jclass = array@jclass, dimension = dim )
+		} else {
+			builder <- .jnew( "RectangularArrayBuilder", .jcast(array), dim )
+			clazz <- .jcall( builder, "Ljava/lang/String;", "getArrayClassName" )
+			
+			# we cannot use .jcall here since it will try to simplify the array
+			# or go back to java to calculate its dimensions, ...
+			r <- .External( "RcallMethod", builder@jobj, 
+				"Ljava/lang/Object;", "getArray", PACKAGE="rJava")
+			
+			new( "jrectRef", jobj = r, dimension = dim, 
+				jclass = clazz, jsig = tojni( clazz ) ) 
+		}  
+	}
+}
+
+# works on EXTPTR or jobjRef or NULL. NULL is always silently converted to .jzeroRef
+.jidenticalRef <- function(a,b) {        
+  if (is(a,"jobjRef")) a<-a@jobj
+  if (is(b,"jobjRef")) b<-b@jobj
+  if (is.null(a)) a <- .jzeroRef
+  if (is.null(b)) b <- .jzeroRef
+  if (!inherits(a,"externalptr") || !inherits(b,"externalptr")) stop("Invalid argument to .jidenticalRef, must be a pointer or jobjRef")
+  .Call(RidenticalRef,a,b)
+}
+
+# returns TRUE only for NULL or jobjRef with jobj=0x0
+is.jnull <- function(x) {
+  (is.null(x) || (is(x,"jobjRef") && .jidenticalRef(x@jobj,.jzeroRef)))
+}
+
+# should we move this to C?
+.jclassRef <- function(x, silent=FALSE) {
+  if (is.jnull(x)) {
+    if (silent) return(NULL) else stop("null reference has no class")
+  }
+  if (!is(x, "jobjRef")) {
+    if (silent) return(NULL) else stop("invalid object")
+  }
+  cl <- NULL
+  try(cl <- .jcall(x, "Ljava/lang/Class;", "getClass", check=FALSE))
+  .jcheck(silent=TRUE)
+  if (is.jnull(cl) && !silent) stop("cannot get class object")
+  cl
+}
+
+# return class object for a given class name; silent determines whether
+# an error should be thrown on failure (FALSE) or just null reference (TRUE)
+.jfindClass <- function(cl, silent=FALSE) {
+  if (inherits(cl, "jclassName")) return(cl@jobj)
+  if (!is.character(cl) || length(cl)!=1)
+    stop("invalid class name")
+  cl<-gsub("/",".",cl)
+  a <- NULL
+  if (!is.jnull(.rJava.class.loader))
+    try(a <- .jcall("java/lang/Class","Ljava/lang/Class;","forName",cl,TRUE,.jcast(.rJava.class.loader,"java.lang.ClassLoader"), check=FALSE))
+  else
+    try(a <- .jcall("java/lang/Class","Ljava/lang/Class;","forName",cl,check=FALSE))
+  # this is really .jcheck but we don't want it to appear on the call stack
+  .Call(RJavaCheckExceptions, silent)
+  if (!silent && is.jnull(a)) stop("class not found")
+  a
+}
+
+# Java-side inheritance check; NULL inherits from any class, because 
+# it can be cast to any class type; cl can be a class name or a jobjRef to a class object
+.jinherits <- function(o, cl) {
+  if (is.jnull(o)) return(TRUE)
+  if (!is(o, "jobjRef")) stop("invalid object")
+  if (is.character(cl)) cl <- .jfindClass(cl) else if (inherits(cl, "jclassName")) cl <- cl@jobj
+  if (!is(cl, "jobjRef")) stop("invalid class object")  
+  ocl <- .jclassRef(o)
+  .Call(RisAssignableFrom, ocl@jobj, cl@jobj)
+}
+
+# compares two things which may be Java objects. invokes Object.equals if applicable and thus even different pointers can be equal. if one parameter is not Java object, but scalar string/int/number/boolean then a corresponding Java object is created for comparison
+# strict comparison returns FALSE if Java-reference is compared with non-reference. otherwise conversion into Java scalar object is attempted
+.jequals <- function(a, b, strict=FALSE) {
+  if (is.null(a)) a <- new("jobjRef")
+  if (is.null(b)) b <- new("jobjRef")
+  if (is(a,"jobjRef")) o <- a else
+    if (is(b,"jobjRef")) { o <- b; b <- a } else
+    return(all.equal(a,b))
+  if (!is(b,"jobjRef")) {
+    if (strict) return(FALSE)
+    if (length(b)!=1) { warning("comparison of non-scalar values is always FALSE"); return(FALSE) }
+    if (is.character(b)) b <- .jnew("java/lang/String",b) else
+    if (is.integer(b)) b <- .jnew("java/lang/Integer",b) else
+    if (is.numeric(b)) b <- .jnew("java/lang/Double",b) else
+    if (is.logical(b)) b <- .jnew("java/lang/Boolean", b) else
+    { warning("comparison of non-trivial values to Java objects is always FALSE"); return(FALSE) }
+  }
+  if (is.jnull(a))
+    is.jnull(b)
+  else
+    .jcall(o, "Z", "equals", .jcast(b, "java/lang/Object"))
+}
+
+.jfield <- function(o, sig=NULL, name, true.class=is.null(sig), convert=TRUE) {
+  if (length(sig)) {
+    if (sig=='S') sig<-"Ljava/lang/String;"
+    if (sig=='T') sig<-"S"
+    if (sig=='[S') sig<-"[Ljava/lang/String;"
+    if (sig=='[T') sig<-"[S"
+  }
+  r <- .Call(RgetField, o, sig, as.character(name), as.integer(true.class))
+  if (inherits(r, "jobjRef")) {
+    if (isJavaArraySignature(r@jclass)) {
+    	r <- if (convert) .jevalArray(r, rawJNIRefSignature=r@jclass, simplify=TRUE) else newArray(r, simplify=FALSE)
+    }
+    if (convert && inherits(r, "jobjRef")) {
+      if (r@jclass == "java/lang/String")
+        return(.External(RgetStringValue, r@jobj))
+      if (.conv.in$.) return(.convert.in(r))
+    }
+  }
+  r
+}
+
+".jfield<-" <- function(o, name, value)
+  .Call(RsetField, o, name, value)
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/comparison.R b/com.oracle.truffle.r.pkgs/rJava/R/comparison.R
new file mode 100644
index 0000000000000000000000000000000000000000..820fca016f56c46e60f5a9d8c3f6f72cad844007
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/comparison.R
@@ -0,0 +1,49 @@
+
+#' if a and b are compatable, 
+#' in the sense of the java.util.Comparable interface
+#' then the result of the compareTo method is returned
+#' otherwise an error message is generated
+.jcompare <- function(a, b) {
+  if (is.null(a)) a <- new("jobjRef")
+  if (is.null(b)) b <- new("jobjRef")
+  
+  if( isJavaArray(a) || isJavaArray(b) ){
+  	  stop( "comparison (<,>,<=,>=) is not implemented for java arrays yet" )
+  }
+  
+  if( !is(a, "jobjRef" ) ) a <- ._java_valid_object( a )
+  if( !is(b, "jobjRef" ) ) b <- ._java_valid_object( b )
+  
+  .jcall( "RJavaComparator", "I", "compare", .jcast(a), .jcast(b) )
+  
+}
+._lower <- function(e1, e2){
+	.jcompare( e1, e2 ) <= 0L
+}
+._greater <- function(e1, e2 ){
+	.jcompare( e1, e2 ) >= 0L
+}
+._strictly_lower <- function(e1, e2 ){
+	.jcompare( e1, e2 ) < 0L
+}
+._strictly_greater <- function(e1, e2 ){
+	.jcompare( e1, e2 ) > 0L
+}
+
+setMethod("<" , c(e1="jobjRef",e2="jobjRef"), ._strictly_lower )
+setMethod("<" , c(e1="jobjRef")             , ._strictly_lower )
+setMethod("<" , c(e2="jobjRef")             , ._strictly_lower )
+              
+setMethod(">" , c(e1="jobjRef",e2="jobjRef"), ._strictly_greater )
+setMethod(">" , c(e1="jobjRef")             , ._strictly_greater )
+setMethod(">" , c(e2="jobjRef")             , ._strictly_greater )
+
+setMethod("<=", c(e1="jobjRef",e2="jobjRef"), ._lower )
+setMethod("<=", c(e1="jobjRef")             , ._lower )
+setMethod("<=", c(e2="jobjRef")             , ._lower )
+                                               
+setMethod(">=", c(e1="jobjRef",e2="jobjRef"), ._greater )
+setMethod(">=", c(e1="jobjRef")             , ._greater )
+setMethod(">=", c(e2="jobjRef")             , ._greater )
+
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/completion.R b/com.oracle.truffle.r.pkgs/rJava/R/completion.R
new file mode 100644
index 0000000000000000000000000000000000000000..b307690f1cb13ac3c55d78ff766abfa4d68063d1
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/completion.R
@@ -0,0 +1,56 @@
+# :tabSize=4:indentSize=4:noTabs=false:folding=explicit:collapseFolds=1:
+
+# S4 dispatch does not work for .DollarNames, so we'll use S3
+# {{{ bring .DollarNames from the future if necessary
+if( !exists( ".DollarNames", envir = asNamespace("utils") ) ){
+	.DollarNames <- function(x, pattern)
+    	UseMethod(".DollarNames")
+} 
+# }}}
+
+# {{{ support function to retrieve completion names from RJavaTools
+### get completion names from RJavaTools
+classNamesMethod <- function (cl, static.only = TRUE ) {
+	# TODO: return both from java instead of two java calls
+  fieldnames <- .jcall( "RJavaTools", "[Ljava/lang/String;", 
+  	"getFieldNames", cl, static.only ) 
+  methodnames <- .jcall( "RJavaTools", "[Ljava/lang/String;", 
+  	"getMethodNames", cl, static.only )
+  c(fieldnames, methodnames)
+}
+# }}}
+
+# {{{ jclassName
+._names_jclassName <- function(x){
+	c( "class", classNamesMethod(x@jobj, static.only = TRUE ) )
+}
+.DollarNames.jclassName <- function(x, pattern = "" ){
+	grep( pattern, ._names_jclassName(x), value = TRUE ) 
+}
+
+setMethod("names", c(x="jclassName"), ._names_jclassName )
+# }}}
+
+# {{{ jobjRef
+._names_jobjRef <- function(x){
+	classNamesMethod(.jcall(x, "Ljava/lang/Class;", "getClass"), static.only = FALSE )
+}
+.DollarNames.jobjRef <- function(x, pattern = "" ){
+	grep( pattern, ._names_jobjRef(x), value = TRUE )
+}
+setMethod("names", c(x="jobjRef"), ._names_jobjRef )
+# }}}
+
+# {{{ jarrayRef and jrectRef
+._names_jarrayRef <- function(x ){
+	c("length", classNamesMethod(.jcall(x, "Ljava/lang/Class;", "getClass"), static.only = FALSE ) )
+}
+.DollarNames.jarrayRef <- .DollarNames.jrectRef <- function(x, pattern = ""){
+	grep( pattern, ._names_jarrayRef(x), value = TRUE )
+}
+
+setMethod("names", c(x="jarrayRef"), ._names_jarrayRef )
+setMethod("names", c(x="jrectRef"), ._names_jarrayRef )
+
+
+# }}}
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/converter.R b/com.oracle.truffle.r.pkgs/rJava/R/converter.R
new file mode 100644
index 0000000000000000000000000000000000000000..66798dab48387ba9878c9e67a3c66586beeb5ae1
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/converter.R
@@ -0,0 +1,43 @@
+# in: Java -> R
+.conv.in <- new.env(parent=emptyenv())
+.conv.in$. <- FALSE
+# out: R -> Java
+.conv.out <- new.env(parent=emptyenv())
+.conv.out$. <- FALSE
+
+# --- internal fns
+.convert.in <- function(jobj, verify.class=TRUE) {  
+  jcl <- if (verify.class) .jclass(jobj) else gsub("/",".",jobj@jclass)
+  cv <- .conv.in[[jcl]]
+  if (!is.null(cv)) jobj else cv$fn(jobj)
+}
+
+.convert.out <- function(robj) {
+  for (cl in class(robj)) {
+    cv <- .conv.out[[cl]]
+    if (!is.null(cv)) return(cv$fn(robj))
+  }
+  robj
+}
+
+# external fns
+.jsetJConvertor <- function(java.class, fn) {
+  if (is.null(fn)) {
+    rm(list=java.class, envir=.conv.in)
+    if (!length(ls(.conv.in))) .conv.in$. <- FALSE
+  } else {
+    .conv.in$. <- TRUE
+    .conv.in[[java.class]] <- list(fn=fn)
+  }
+}
+
+.jsetRConvertor <- function(r.class, fn) {
+  if (is.null(fn)) {
+    rm(list=r.class, envir=.conv.out)
+    if (!length(ls(.conv.out))) .conv.out$. <- FALSE
+  } else {
+    .conv.out$. <- TRUE
+    .conv.out[[r.class]] <- list(fn=fn)
+  }
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/exceptions.R b/com.oracle.truffle.r.pkgs/rJava/R/exceptions.R
new file mode 100644
index 0000000000000000000000000000000000000000..c5c752cfc7c5d870d226a3bc58374517420d078e
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/exceptions.R
@@ -0,0 +1,48 @@
+## functions for some basic exception handling
+
+# FIXME: should all these actually be deprecated or defunct
+
+## poll for an exception
+.jgetEx <- function(clear=FALSE) {
+  exo <- .Call(RpollException)
+  if (is.null(exo)) return(NULL)
+  x <- new("jobjRef", jobj=exo, jclass="java/lang/Throwable")
+  if (clear) .jclear()
+  x
+}
+
+## explicitly clear any pending exceptions
+.jclear <- function() {
+  .C(RclearException)
+  invisible(NULL)
+}
+
+## throw an exception
+.jthrow <- function(exception, message=NULL) {
+  if (is.character(exception))
+    exception <- .jnew(exception, as.character(message))
+  if (is(exception, "jobjRef"))
+    .Call(RthrowException, exception)
+  else
+    stop("Invalid exception.")
+}
+
+
+"$.Throwable" <- function( x, name ){
+	if( name %in% names(c(x)) ){
+		c(x)[[ name ]]
+	} else{
+		._jobjRef_dollar( x[["jobj"]], name )
+	}
+}
+
+"$<-.Throwable" <- function( x, name, value ){
+	if( name %in% names(x) ){
+		x[[ name ]] <- value
+	} else{
+		._jobjRef_dollargets( x[["jobj"]], name, value )
+	}
+	x
+	
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/import.R b/com.oracle.truffle.r.pkgs/rJava/R/import.R
new file mode 100644
index 0000000000000000000000000000000000000000..7235ebb3da8ada73963ab3be244922e784bde31f
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/import.R
@@ -0,0 +1,144 @@
+
+IMPORTER <- ".__rjava__import"
+
+java_class_importers <- new.env()
+assign( ".namespaces", NULL, envir = java_class_importers )
+
+getImporterFromNamespace <- function( nm, create = TRUE ){
+	.namespaces <- get(".namespaces", envir = java_class_importers )
+	if( !is.null( .namespaces ) ){
+		for( item in .namespaces ){
+			if( identical( item$nm, nm ) ){
+				return( item$importer )
+			}
+		}
+	}
+	if( create ){
+		addImporterNamespace(nm)
+	}
+	
+}
+addImporterNamespace <- function( nm ){
+	importer <- .jnew( "RJavaImport", .jcast( .rJava.class.loader, "java/lang/ClassLoader" ) )
+	assign( ".namespaces",	
+		append( list( list( nm = nm, importer = importer ) ), get(".namespaces", envir = java_class_importers ) ), 
+		envir = java_class_importers )
+	importer
+}
+
+getImporterFromEnvironment <- function(env, create = TRUE){
+	if( isNamespace( env ) ){
+		getImporterFromNamespace( env )
+	} else if( exists(IMPORTER, envir = env ) ){
+		get( IMPORTER, envir = env )
+	} else if( create ){
+		addImporterNamespace(env)
+	}
+}
+
+getImporterFromGlobalEnv <- function( ){
+	if( exists( "global", envir = java_class_importers ) ){
+		get( "global", envir = java_class_importers ) 
+	} else{
+		initGlobalEnvImporter()
+	}
+}
+initGlobalEnvImporter <- function(){
+	importer <- .jnew( "RJavaImport", .jcast( .rJava.class.loader, "java/lang/ClassLoader" ) )
+	assign( "global", importer , envir = java_class_importers )
+	importer
+}
+
+import <- function( package = "java.util", env = sys.frame(sys.parent()) ){
+	
+	if( missing(env) ){
+		caller <- sys.function(-1)
+		env <- environment( caller ) 
+		if( isNamespace( env ) ){
+			importer <- getImporterFromNamespace( env )
+		}
+	} else{
+		force(env)
+	
+		if( !is.environment( env ) ){
+			stop( "env is not an environment" ) 
+		}
+		
+		if( ! exists( IMPORTER, env ) || is.jnull( get( IMPORTER, envir = env ) ) ){
+			importer <- .jnew( "RJavaImport", .jcast( .rJava.class.loader, "java/lang/ClassLoader" ) )
+			if( isNamespace(env) ){
+				unlockBinding( IMPORTER, env = env )
+				assignInNamespace( IMPORTER, importer, envir = env ) 
+			}
+			assign( IMPORTER, importer, envir = env ) 
+		} else{
+			importer <- get( IMPORTER, envir = env )
+		}
+	}
+	mustbe.importer( importer )
+	.jcall( importer, "V", "importPackage", package )
+	
+}
+
+is.importer <- function(x){
+	is( x, "jobjRef" ) && .jinherits( x, "RJavaImport" )
+}
+mustbe.importer <- function(x){
+	if( !is.importer(x) ){
+		stop( "object not a suitable java package importer" )
+	}
+}
+
+#' collect importers
+getAvailableImporters <- function( frames = TRUE, namespace = TRUE, 
+	global = TRUE, caller = sys.function(-1L) ){
+	
+	importers <- .jnew( "java/util/HashSet" )
+	
+	addImporter <- function( importer ){
+		if( is.importer( importer ) ){
+			.jcall( importers, "Z", "add", .jcast(importer) )
+		}
+	}
+	if( isTRUE( global ) ){
+		addImporter( getImporterFromGlobalEnv() )
+	}
+	
+	if( isTRUE( frames ) ){
+		frames <- sys.frames()
+		if( length(frames) > 1L ){
+			sapply( head( frames, -1L ), function(env) {
+				if( !identical( env, .GlobalEnv ) ){
+					addImporter( getImporterFromEnvironment( env ) )
+				}
+			} )
+		}
+	}
+	
+	if( isTRUE( namespace ) ){
+		force(caller)
+		env <- environment( caller ) 
+		if( isNamespace( env ) ){
+			addImporter( getImporterFromNamespace( env ) )
+		}
+	}
+	
+	importers
+}
+
+#' lookup for a class name in the available importers
+lookup <- function( name = "Object", ..., caller = sys.function(-1L) ){
+	force(caller)
+	importers <- getAvailableImporters(..., caller = caller)
+	.jcall( "RJavaImport", "Ljava/lang/Class;", "lookup", 
+		name, .jcast( importers, "java/util/Set" )  )
+}
+
+
+javaImport <- function( packages = "java.lang" ){
+	importer <- .jnew( "RJavaImport", .jcast( .rJava.class.loader, "java/lang/ClassLoader" ) )
+	.jcall( importer, "V", "importPackage", packages )
+	.Call( "newRJavaLookupTable" , importer, 
+		PACKAGE = "rJava" )
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/instanceof.R b/com.oracle.truffle.r.pkgs/rJava/R/instanceof.R
new file mode 100644
index 0000000000000000000000000000000000000000..7f28b2e124f8d4be7ecf7e7cfd731b101efbb07e
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/instanceof.R
@@ -0,0 +1,25 @@
+`%instanceof%` <- .jinstanceof <- function( o, cl ){
+	
+	if( !inherits( o, "jobjRef" ) ){
+		stop( "o is not a java object" )
+	}
+	
+	# first get the class object that represents cl
+	if( inherits( cl, "jobjRef" ) ){
+		if( .jclass( cl ) == "java.lang.Class" ){
+			clazz <- cl
+		} else {
+			clazz <- .jcall( cl, "Ljava/lang/Class;", "getClass" ) 
+		}
+	} else if( inherits( cl, "jclassName" ) ) {
+		clazz <- cl@jobj
+	} else if( inherits( cl, "character" ) ){
+		clazz <- .jfindClass(cl)
+	} else {
+		return(FALSE)
+	}
+	
+	# then find out if o is an instance of the class
+	.jcall( clazz , "Z", "isInstance", .jcast(o, "java/lang/Object" ) )
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/jfirst.R b/com.oracle.truffle.r.pkgs/rJava/R/jfirst.R
new file mode 100644
index 0000000000000000000000000000000000000000..b7ca55418b2e5ac8d62c9bbeb94a5f499849744f
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/jfirst.R
@@ -0,0 +1,49 @@
+# this part is common to all platforms and must be invoked
+# from .First.lib after library.dynam
+
+# actual namespace environment of this package
+.env <- environment()
+
+# variables in the rJava environment that will be initialized *after* the package is loaded
+# they need to be pre-created at load time and populated later by .jinit
+.delayed.export.variables <- c(".jniInitialized", ".jclassObject", ".jclassString", ".jclassClass",
+                               ".jclass.int", ".jclass.double", ".jclass.float", ".jclass.boolean",
+                               ".jclass.void", ".jinit.merge.error")
+# variables that are delayed but not exported are added here
+.delayed.variables <- c(.delayed.export.variables, ".rJava.class.loader")
+
+# C entry points to register
+.register.addr <- c( # .Call
+                    "PushToREXP", "RJava_checkJVM", "RJava_needs_init", "RJava_new_class_loader",
+                    "RJava_primary_class_loader", "RJava_set_class_loader", "RJava_set_memprof", "RJavaCheckExceptions",
+                    "RcreateArray", "RgetBoolArrayCont", "RgetByteArrayCont", "RgetCharArrayCont",
+                    "RgetDoubleArrayCont", "RgetField", "RgetFloatArrayCont", "RgetIntArrayCont",
+                    "RgetLongArrayCont", "RgetNullReference", "RgetObjectArrayCont",
+                    "RgetShortArrayCont", "RgetStringArrayCont", "RidenticalRef",
+                    "RisAssignableFrom", "RpollException", "RsetField", "RthrowException",
+                    "javaObjectCache",
+                     # .External
+                    "RcreateObject", "RgetStringValue", "RinitJVM", "RtoString",
+                     # .C
+                    "RclearException", "RuseJNICache"
+                    )
+
+.jfirst <- function(libname, pkgname) {
+  # register all C entry points
+  addr <- getNativeSymbolInfo(.register.addr, pkgname)
+  for (name in .register.addr)
+     .env[[name]] <- addr[[name]]$address
+
+  assign(".rJava.base.path", paste(libname, pkgname, sep=.Platform$file.sep), .env)
+  assign(".jzeroRef", .Call(RgetNullReference), .env)
+
+  for (x in .delayed.variables) assign(x, NULL, .env)
+  assign(".jniInitialized", FALSE, .env)
+
+  # default JVM initialization parameters
+  if (is.null(getOption("java.parameters")))
+    options("java.parameters"="-Xmx512m")
+  
+  ## S4 classes update - all classes are created earlier in classes.R, but jobjRef's prototype is only valid after the dylib is loaded
+  setClass("jobjRef", representation(jobj="externalptr", jclass="character"), prototype=list(jobj=.jzeroRef, jclass="java/lang/Object"), where=.env)  
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/jinit.R b/com.oracle.truffle.r.pkgs/rJava/R/jinit.R
new file mode 100644
index 0000000000000000000000000000000000000000..fef2d752a12818a075092883e62e045308b33cdb
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/jinit.R
@@ -0,0 +1,238 @@
+## This file is part of the rJava package - low-level R/Java interface
+## (C)2006 Simon Urbanek <simon.urbanek@r-project.org>
+## For license terms see DESCRIPTION and/or LICENSE
+##
+## $Id$
+
+.check.JVM <- function() 
+    .Call(RJava_checkJVM)
+.need.init <- function()
+    .Call(RJava_needs_init)
+
+## initialization
+.jinit <- function(classpath=NULL, parameters=getOption("java.parameters"), ..., silent=FALSE, force.init=FALSE) {
+  running.classpath <- character()
+  if (!.need.init()) {
+    running.classpath <- .jclassPath()
+    if (!force.init) {
+      if (length(classpath)) {
+        cpc <- unique(unlist(strsplit(classpath, .Platform$path.sep)))
+        if (length(cpc)) .jaddClassPath(cpc)
+      }
+      return(0)
+    }
+  }
+
+  ## determine path separator
+  path.sep <- .Platform$path.sep
+
+  if (!is.null(classpath)) {
+    classpath <- as.character(classpath)
+    if (length(classpath))
+      classpath <- paste(classpath,collapse=path.sep)
+  }
+  
+  # merge CLASSPATH environment variable if present
+  cp<-Sys.getenv("CLASSPATH")
+  if (!is.null(cp)) {
+    if (is.null(classpath))
+      classpath<-cp
+    else
+      classpath<-paste(classpath,cp,sep=path.sep)
+  }
+  
+  # set rJava/java/boot for boostrap (so we can get RJavaClassLoader)
+  boot.classpath <- file.path(.rJava.base.path,"java","boot")
+
+  # if running in a sub-arch, append -Dr.arch in case someone gets the idea to start JRI
+  if (is.character(.Platform$r_arch) && nzchar(.Platform$r_arch) && length(grep("-Dr.arch", parameters, fixed=TRUE)) == 0L)
+    parameters <- c(paste("-Dr.arch=/", .Platform$r_arch, sep=''), as.character(parameters))
+
+  ## unfortunately Sys/setlocale()/Sys.getlocale() have incompatible interfaces so there
+  ## is no good way to get/set locales -- so we have to hack around it ...
+  locale.list <- c("LC_COLLATE", "LC_CTYPE", "LC_MONETARY", "LC_NUMERIC", "LC_TIME", "LC_MESSAGES", "LC_PAPER", "LC_MEASUREMENT")
+  locales <- sapply(locale.list, Sys.getlocale)
+  loc.sig <- Sys.getlocale()
+
+  #cat(">> init CLASSPATH =",classpath,"\n")
+  #cat(">> boot class path: ", boot.classpath,"\n")
+  # call the corresponding C routine to initialize JVM
+  xr <- .External(RinitJVM, boot.classpath, parameters)
+
+  ## we have to re-set the locales right away
+  suppressWarnings(try(if (!identical(Sys.getlocale(), loc.sig)) for (i in names(locales)) try(Sys.setlocale(i, locales[i]), silent=TRUE),
+      silent=TRUE))
+
+  if (xr==-1) stop("Unable to initialize JVM.")
+  if (xr==-2) stop("Another VM is already running and rJava was unable to attach to that VM.")
+  # we'll handle xr==1 later because we need fully initialized rJava for that
+
+  # this should remove any lingering .jclass objects from the global env
+  # left there by previous versions of rJava
+  pj <- grep("^\\.jclass",ls(1,all.names=TRUE),value=TRUE)
+  if (length(pj)>0) { 
+    rm(list=pj,pos=1)
+    if (exists(".jniInitialized",1)) rm(list=".jniInitialized",pos=1)
+    if (!silent) warning("rJava found hidden Java objects in your workspace. Internal objects from previous versions of rJava were deleted. Please note that Java objects cannot be saved in the workspace.")
+  }
+
+  ##--- HACK-WARNING: we're operating directly on the namespace environment
+  ##                  this could be dangerous.
+  for (x in .delayed.variables) unlockBinding(x, .env)
+  assign(".jniInitialized", TRUE, .env)
+  # get cached class objects for reflection
+  assign(".jclassObject", .jcall("java/lang/Class","Ljava/lang/Class;","forName","java.lang.Object"), .env)
+  assign(".jclassClass", .jcall("java/lang/Class","Ljava/lang/Class;","forName","java.lang.Class"), .env)
+  assign(".jclassString", .jcall("java/lang/Class","Ljava/lang/Class;","forName","java.lang.String"), .env)
+
+  ic <- .jcall("java/lang/Class","Ljava/lang/Class;","forName","java.lang.Integer")
+  f<-.jcall(ic,"Ljava/lang/reflect/Field;","getField", "TYPE")
+  assign(".jclass.int", .jcast(.jcall(f,"Ljava/lang/Object;","get",.jcast(ic,"java/lang/Object")),"java/lang/Class"), .env)
+  ic <- .jcall("java/lang/Class","Ljava/lang/Class;","forName","java.lang.Double")
+  f<-.jcall(ic,"Ljava/lang/reflect/Field;","getField", "TYPE")
+  assign(".jclass.double", .jcast(.jcall(f,"Ljava/lang/Object;","get",.jcast(ic,"java/lang/Object")),"java/lang/Class"), .env)
+  ic <- .jcall("java/lang/Class","Ljava/lang/Class;","forName","java.lang.Float")
+  f<-.jcall(ic,"Ljava/lang/reflect/Field;","getField", "TYPE")
+  assign(".jclass.float", .jcast(.jcall(f,"Ljava/lang/Object;","get",.jcast(ic,"java/lang/Object")),"java/lang/Class"), .env)
+  ic <- .jcall("java/lang/Class","Ljava/lang/Class;","forName","java.lang.Boolean")
+  f<-.jcall(ic,"Ljava/lang/reflect/Field;","getField", "TYPE")
+  assign(".jclass.boolean", .jcast(.jcall(f,"Ljava/lang/Object;","get",.jcast(ic,"java/lang/Object")),"java/lang/Class"), .env)
+  ic <- .jcall("java/lang/Class","Ljava/lang/Class;","forName","java.lang.Void")
+  f<-.jcall(ic,"Ljava/lang/reflect/Field;","getField", "TYPE")
+  assign(".jclass.void", .jcast(.jcall(f,"Ljava/lang/Object;","get",.jcast(ic,"java/lang/Object")),"java/lang/Class"), .env)
+
+  ## if NOAWT is set, set AWT to headless
+  if (nzchar(Sys.getenv("NOAWT"))) .jcall("java/lang/System","S","setProperty","java.awt.headless","true")
+
+  lib <- "libs"
+  if (nchar(.Platform$r_arch)) lib <- file.path("libs", .Platform$r_arch)
+
+  rjcl <- NULL
+  if (xr==1) { # && nchar(classpath)>0) {
+    # ok, so we're attached to some other JVM - now we need to make sure that
+    # we can load our class loader. If we can't then we have to use our bad hack
+    # to be able to squeeze our loader in
+
+    # first, see if this is actually JRIBootstrap so we have a loader already
+    rjcl <- .Call(RJava_primary_class_loader)
+    if (is.null(rjcl) || .jidenticalRef(rjcl,.jzeroRef)) rjcl <- NULL
+    else rjcl <- new("jobjRef", jobj=rjcl, jclass="RJavaClassLoader")
+    if (is.jnull(rjcl))
+      rjcl <- .jnew("RJavaClassLoader", .rJava.base.path,
+                                      file.path(.rJava.base.path, lib), check=FALSE)
+    .jcheck(silent=TRUE)
+    if (is.jnull(rjcl)) {
+      ## it's a hack, so we run it in try(..) in case BadThings(TM) happen ...
+      cpr <- try(.jmergeClassPath(boot.classpath), silent=TRUE)
+      if (inherits(cpr, "try-error")) {
+        .jcheck(silent=TRUE)
+        if (!silent) warning("Another VM is running already and the VM did not allow me to append paths to the class path.")
+        assign(".jinit.merge.error", cpr, .env)
+      }
+      if (length(parameters)>0 && any(parameters!=getOption("java.parameters")) && !silent)
+        warning("Cannot set VM parameters, because VM is running already.")
+    }
+  }
+
+  if (is.jnull(rjcl))
+    rjcl <- .jnew("RJavaClassLoader", .rJava.base.path,
+                  file.path(.rJava.base.path, lib), check=FALSE )
+
+  if (!is.jnull(rjcl)) {
+    ## init class loader
+    assign(".rJava.class.loader", rjcl, .env)
+
+    ##-- set the class for native code
+    .Call(RJava_set_class_loader, .env$.rJava.class.loader@jobj)
+
+    ## now it's time to add any additional class paths
+    cpc <- unique(strsplit(classpath, .Platform$path.sep)[[1]])
+    if (length(cpc)) .jaddClassPath(cpc)
+  } else stop("Unable to create a Java class loader.")
+  
+  ##.Call(RJava_new_class_loader, .rJava.base.path, file.path(.rJava.base.path, lib))
+
+  ## lock namespace bindings
+  for (x in .delayed.variables) lockBinding(x, .env)
+  
+  ## now we need to update the attached namespace (package env)  as well
+  m <- match(paste("package", getNamespaceName(.env), sep = ":"), search())[1]
+  if (!is.na(m)) { ## only is it is attached
+    pe <- as.environment(m)
+    for (x in .delayed.export.variables) {
+      unlockBinding(x, pe)
+      pe[[x]] <- .env[[x]]
+      lockBinding(x, pe)
+    }
+  }
+  
+  # FIXME: is this the best place or should this be done 
+  #        internally right after the RJavaClassLoader is instanciated
+  # init the cached RJavaTools class in the jni side
+  .Call( "initRJavaTools", PACKAGE = "rJava" ) 
+  
+  # not yet
+  # import( c( "java.lang", "java.util") )
+  
+  invisible(xr)
+}
+
+# FIXME: this is not always true: osgi, eclipse etc use a different
+#        class loader strategy, we should add some sort of hook to let people
+#        define how they want this to be done
+.jmergeClassPath <- function(cp) {
+  ccp <- .jcall("java/lang/System","S","getProperty","java.class.path")
+  ccpc <- strsplit(ccp, .Platform$path.sep)[[1]]
+  cpc <- strsplit(cp, .Platform$path.sep)[[1]]
+  rcp <- unique(cpc[!(cpc %in% ccpc)])
+  if (length(rcp) > 0) {
+    # the loader requires directories to include trailing slash
+    # Windows: need / or \ ? (untested)
+    dirs <- which(file.info(rcp)$isdir)
+    for (i in dirs)
+      if (substr(rcp[i],nchar(rcp[i]),nchar(rcp[i]))!=.Platform$file.sep)
+        rcp[i]<-paste(rcp[i], .Platform$file.sep, sep='')
+
+    ## this is a hack, really, that exploits the fact that the system class loader
+    ## is in fact a subclass of URLClassLoader and it also subverts protection
+    ## of the addURL class using reflection - yes, bad hack, but we use it
+    ## only if the boot class path doesn't contain our own class loader so
+    ## we cannot replace the system loader with our own (this will happen when we
+    ## need to attach to an existing VM)
+    ## The original discussion and code for this hack was at:
+    ## http://forum.java.sun.com/thread.jspa?threadID=300557&start=15&tstart=0
+
+    ## it should probably be run in try(..) because chances are that it will
+    ## break if Sun changes something...
+    cl <- .jcall("java/lang/ClassLoader", "Ljava/lang/ClassLoader;", "getSystemClassLoader")
+    urlc <- .jcall("java/lang/Class", "Ljava/lang/Class;", "forName", "java.net.URL")
+    clc <- .jcall("java/lang/Class", "Ljava/lang/Class;", "forName", "java.net.URLClassLoader")
+    ar <- .jcall("java/lang/reflect/Array", "Ljava/lang/Object;",
+                         "newInstance", .jclassClass, 1:1)
+    .jcall("java/lang/reflect/Array", "V", "set",
+                  .jcast(ar, "java/lang/Object"), 0:0,
+                  .jcast(urlc, "java/lang/Object"))
+    m<-.jcall(clc, "Ljava/lang/reflect/Method;", "getDeclaredMethod", "addURL", .jcast(ar,"[Ljava/lang/Class;"))
+    .jcall(m, "V", "setAccessible", TRUE)
+
+    ar <- .jcall("java/lang/reflect/Array", "Ljava/lang/Object;",
+                 "newInstance", .jclassObject, 1:1)
+    
+    for (fn in rcp) {
+      f <- .jnew("java/io/File", fn)
+      url <- .jcall(f, "Ljava/net/URL;", "toURL")
+      .jcall("java/lang/reflect/Array", "V", "set",
+             .jcast(ar, "java/lang/Object"), 0:0,
+             .jcast(url, "java/lang/Object"))
+      .jcall(m, "Ljava/lang/Object;", "invoke",
+             .jcast(cl, "java/lang/Object"), .jcast(ar, "[Ljava/lang/Object;"))
+    }
+
+    # also adjust the java.class.path property to not confuse others
+    if (length(ccp)>1 || (length(ccp)==1 && nchar(ccp[1])>0))
+      rcp <- c(ccp, rcp)
+    acp <- paste(rcp, collapse=.Platform$path.sep)
+    .jcall("java/lang/System","S","setProperty","java.class.path",as.character(acp))
+  } # if #rcp>0
+  invisible(.jcall("java/lang/System","S","getProperty","java.class.path"))
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/jri.R b/com.oracle.truffle.r.pkgs/rJava/R/jri.R
new file mode 100644
index 0000000000000000000000000000000000000000..ede262cdfb394b5a4fbe886e0f058a8b8b7f8a06
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/jri.R
@@ -0,0 +1,86 @@
+## bindings into JRI
+
+## warning: JRI REXP class has currently no finalizers! (RReleaseREXP must be used manually for now)
+## warning: this produces JRI-API pbjects - that should go away! use toJava below
+.r2j <- function(x, engine = NULL, convert = TRUE) {
+  if (is.null(engine)) engine <- .jcall("org/rosuda/JRI/Rengine","Lorg/rosuda/JRI/Rengine;","getMainEngine")
+  if (!is(engine, "jobjRef")) stop("invalid or non-existent engine")
+  new("jobjRef",jobj=.Call(PushToREXP,"org/rosuda/JRI/REXP",engine@jobj,engine@jclass,x,convert),jclass="org/rosuda/JRI/REXP")
+}
+
+toJava <- function(x, engine = NULL) {
+  ## this is really the wrong place for all this REngine checking stuff, but so far .jengine uses JRI API only and legacy code may rely on that
+  ## so this is the only place that assumes REngine API and thus will load it ...
+  ec <- .jfindClass("org.rosuda.JRI.Rengine", silent=TRUE)
+  if (is.jnull(ec)) {
+    .jcheck(TRUE)
+    stop("JRI is not loaded. Please start JRI first - see ?.jengine")
+  }
+  ec <- .jfindClass("org.rosuda.REngine.REngine", silent=TRUE)
+  if (is.jnull(ec)) {
+    .jcheck(TRUE)
+    fn <- system.file("jri","REngine.jar",package="rJava")
+    if (nzchar(fn)) .jaddClassPath(fn)
+    fn <- system.file("jri","JRIEngine.jar",package="rJava")
+    if (nzchar(fn)) .jaddClassPath(fn)
+    ec <- .jfindClass("org.rosuda.REngine.REngine", silent=TRUE)
+    if (is.jnull(ec)) {
+      .jcheck(TRUE)
+      stop("Cannot find REngine API classes. Please make sure you have installed and loaded the REngine API")
+    }
+  }
+  if (is.null(engine)) engine <- .jcall("org/rosuda/REngine/REngine","Lorg/rosuda/REngine/REngine;","getLastEngine")
+  if (is.jnull(engine)) { # no last engine, but there may be JRI engine already running ...
+    me <- .jcall("org/rosuda/JRI/Rengine","Lorg/rosuda/JRI/Rengine;","getMainEngine", check=FALSE)
+    .jcheck(TRUE)
+    if (is.jnull(me)) stop("JRI is not running. Please start JRI first - see ?.jengine")
+    engine <- .jnew("org/rosuda/REngine/JRI/JRIEngine", me)
+    .jcheck(TRUE)
+  }
+  .jcheck(TRUE)
+  if (!is(engine, "jobjRef")) stop("invalid or non-existent engine")
+  new("jobjRef",jobj=.Call(PushToREXP,"org/rosuda/REngine/REXPReference",engine@jobj,"org/rosuda/REngine/REngine",x,NULL),jclass="org/rosuda/REngine/REXPReference")
+}
+
+.setupJRI <- function(new=TRUE) {
+  ec <- .jfindClass("org.rosuda.JRI.Rengine", silent=TRUE)
+  if (is.jnull(ec)) {
+    .jcheck(TRUE)
+    .jaddClassPath(system.file("jri","JRI.jar",package="rJava"))
+    ec <- .jfindClass("org.rosuda.JRI.Rengine", silent=TRUE)
+    .jcheck(TRUE)
+    if (is.jnull(ec))
+      stop("Cannot find JRI classes")
+  }
+  me <- .jcall("org/rosuda/JRI/Rengine","Lorg/rosuda/JRI/Rengine;","getMainEngine", check=FALSE)
+  .jcheck(TRUE)
+  if (!is.jnull(me)) {
+    if (!new) return(TRUE)
+    warning("JRI engine is already running.")
+    return(FALSE)
+  }
+  e <- .jnew("org/rosuda/JRI/Rengine")
+  !is.jnull(e)
+}
+
+.jengine <- function(start=FALSE, silent=FALSE) {
+  me <- NULL
+  ec <- .jfindClass("org.rosuda.JRI.Rengine", silent=TRUE)
+  .jcheck(TRUE)
+  if (!is.jnull(ec)) {
+    me <- .jcall("org/rosuda/JRI/Rengine","Lorg/rosuda/JRI/Rengine;","getMainEngine", check=FALSE)
+    .jcheck(TRUE)
+  }
+  if (is.jnull(me)) {
+    if (!start) {
+      if (silent) return(NULL)
+      stop("JRI engine is not running.")
+    }
+    .setupJRI(FALSE)
+    me <- .jcall("org/rosuda/JRI/Rengine","Lorg/rosuda/JRI/Rengine;","getMainEngine", check=FALSE)
+    .jcheck(TRUE)
+  }
+  if (is.jnull(me) && !silent)
+    stop("JRI engine is not running.")
+  me
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/loader.R b/com.oracle.truffle.r.pkgs/rJava/R/loader.R
new file mode 100644
index 0000000000000000000000000000000000000000..0e2adb81f58bbf373a0d64a6d5881e929afe3b78
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/loader.R
@@ -0,0 +1,64 @@
+.jaddClassPath <- function(path) {
+    if (!length(path)) return(invisible(NULL))
+    if (!is.jnull(.rJava.class.loader))
+        invisible(.jcall(.rJava.class.loader,"V","addClassPath",as.character(path)))
+    else {
+        cpr <- try(.jmergeClassPath(paste(path,collapse=.Platform$path.sep)), silent=TRUE)
+        invisible(!inherits(cpr, "try-error"))
+    }
+}
+
+.jclassPath <- function() {
+    if (is.jnull(.rJava.class.loader)) {
+        cp <- .jcall("java/lang/System", "S", "getProperty", "java.class.path")
+        unlist(strsplit(cp, .Platform$path.sep))
+    } else {
+        .jcall(.rJava.class.loader,"[Ljava/lang/String;","getClassPath")
+    }
+}
+
+.jaddLibrary <- function(name, path) {
+    if (!is.jnull(.rJava.class.loader))
+        invisible(.jcall(.rJava.class.loader, "V", "addRLibrary", as.character(name)[1], as.character(path)[1]))
+}
+
+.jrmLibrary <- function(name) {
+  ## FIXME: unimplemented
+}
+
+.jclassLoader <- function() {
+    .rJava.class.loader
+}
+
+.jpackage <- function(name, jars='*', morePaths='', nativeLibrary=FALSE, lib.loc=NULL) {
+  if (!.jniInitialized) .jinit()
+  classes <- system.file("java", package=name, lib.loc=lib.loc)
+  if (nchar(classes)) {
+    .jaddClassPath(classes)
+    if (length(jars)) {
+      if (length(jars)==1 && jars=='*') {
+        jars <- grep(".*\\.jar",list.files(classes,full.names=TRUE),TRUE,value=TRUE)
+        if (length(jars)) .jaddClassPath(jars)
+      } else .jaddClassPath(paste(classes,jars,sep=.Platform$file.sep))
+    }
+  }  
+  if (any(nchar(morePaths))) {
+    cl <- as.character(morePaths)
+    cl <- cl[nchar(cl)>0]
+    .jaddClassPath(cl)
+  }
+  if (is.logical(nativeLibrary)) {
+    if (nativeLibrary) {
+      libs <- "libs"
+      if (nchar(.Platform$r_arch)) lib <- file.path("libs", .Platform$r_arch)
+      lib <- system.file(libs, paste(name, .Platform$dynlib.ext, sep=''), package=name, lib.loc=lib.loc)
+      if (nchar(lib))
+        .jaddLibrary(name, lib)
+      else
+        warning("Native library for `",name,"' could not be found.")
+    }
+  } else {
+    .jaddLibrary(name, nativeLibrary)
+  }
+  invisible(TRUE)
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/memprof.R b/com.oracle.truffle.r.pkgs/rJava/R/memprof.R
new file mode 100644
index 0000000000000000000000000000000000000000..8fd6c2bec52390dae3725bc0c1040a48eab9b601
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/memprof.R
@@ -0,0 +1,4 @@
+.jmemprof <- function(file = "-") {
+  if (is.null(file)) file <- ""
+  invisible(.Call(RJava_set_memprof, as.character(file)))
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/methods.R b/com.oracle.truffle.r.pkgs/rJava/R/methods.R
new file mode 100644
index 0000000000000000000000000000000000000000..c86d4b876c122b3bf3e6ced26cfb679fd1b0450e
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/methods.R
@@ -0,0 +1,27 @@
+## methods for jobjRef class
+##
+## additional methods ($ and $<-) are defined in reflection.R
+
+# show method
+# FIXME: this should show the class of the object instead of Java-Object
+setMethod("show", c(object="jobjRef"), function(object) {
+  if (is.jnull(object)) show("Java-Object<null>") else show(paste("Java-Object{", .jstrVal(object), "}", sep=''))
+  invisible(NULL)
+})
+
+setMethod("show", c(object="jarrayRef"), function(object) {
+  show(paste("Java-Array-Object",object@jsig,":", .jstrVal(object), sep=''))
+  invisible(NULL)
+})
+
+# map R comparison operators to .jequals
+setMethod("==", c(e1="jobjRef",e2="jobjRef"), function(e1,e2) .jequals(e1,e2))
+setMethod("==", c(e1="jobjRef"), function(e1,e2) .jequals(e1,e2))
+setMethod("==", c(e2="jobjRef"), function(e1,e2) .jequals(e1,e2))
+
+setMethod("!=", c(e1="jobjRef",e2="jobjRef"), function(e1,e2) !.jequals(e1,e2))
+setMethod("!=", c(e1="jobjRef"), function(e1,e2) !.jequals(e1,e2))
+setMethod("!=", c(e2="jobjRef"), function(e1,e2) !.jequals(e1,e2))
+
+# other operators such as <,> are defined in comparison.R
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/options.R b/com.oracle.truffle.r.pkgs/rJava/R/options.R
new file mode 100644
index 0000000000000000000000000000000000000000..f26d816a53fe7656bd98111b0c3aa2863a2b2857
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/options.R
@@ -0,0 +1,11 @@
+.joptions <- function(...) {
+  l <- list(...)
+  if (length(l)==0) return(list())
+  if ("jni.cache" %in% names(l)) {
+    v <- l[["jni.cache"]]
+    if (!is.logical(v) || length(v)!=1)
+      stop("jni.cache must be a logical vector of length 1")
+    .C(RuseJNICache,v)
+    invisible(NULL)
+  }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/reflection.R b/com.oracle.truffle.r.pkgs/rJava/R/reflection.R
new file mode 100644
index 0000000000000000000000000000000000000000..c8f9ef67f1ce7911ec5562f828b1fc39a1b64c93
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/reflection.R
@@ -0,0 +1,272 @@
+### reflection functions - convenience function relying on the low-level
+### functions .jcall/.jnew and friends
+
+### reflection tools (inofficial so far, because it returns strings
+### instead of the reflection objects - it's useful for quick checks,
+### though)
+.jmethods <- function(o, name=NULL, as.obj=FALSE) {
+  cl <- if (is(o, "jobjRef")) .jcall(o, "Ljava/lang/Class;", "getClass") else if (is(o, "jclassName")) o@jobj else .jfindClass(as.character(o))
+  ms<-.jcall(cl,"[Ljava/lang/reflect/Method;","getMethods")
+  if (isTRUE(as.obj)) return(ms)
+  ss<-unlist(lapply(ms,function(x) .jcall(x,"S","toString")))
+  if (!is.null(name))
+    grep(paste("\\.",name,"\\(",sep=''),ss,value=TRUE)
+  else
+    ss
+}
+
+.jconstructors <- function(o, as.obj=FALSE) {
+  cl <- if (is(o, "jobjRef")) .jcall(o, "Ljava/lang/Class;", "getClass") else if (is(o, "jclassName")) o@jobj else .jfindClass(as.character(o))
+  cs<-.jcall(cl,"[Ljava/lang/reflect/Constructor;","getConstructors")
+  if (isTRUE(as.obj)) return(cs)
+  unlist(lapply(cs,function(x) .jcall(x,"S","toString")))
+}
+
+### this list maps R class names to Java class names for which the constructor does the necessary conversion (for use in .jrcall)
+.class.to.jclass <-    c(character= "java/lang/String",
+                         jbyte    = "java/lang/Byte",
+                         integer  = "java/lang/Integer",
+                         numeric  = "java/lang/Double",
+                         logical  = "java/lang/Boolean",
+                         jlong    = "java/lang/Long",
+                         jchar    = "java/lang/Character",
+                         jshort   = "java/lang/Short",
+                         jfloat   = "java/lang/Float")
+
+### Java classes that have a corresponding primitive type and thus a corresponding TYPE field to use with scalars
+.primitive.classes = c("java/lang/Byte", "java/lang/Integer", "java/lang/Double", "java/lang/Boolean",
+                       "java/lang/Long", "java/lang/Character", "java/lang/Short", "java/lang/Float")
+
+### creates a valid java object
+### if a is already a java object reference, all is good
+### otherwise some primitive conversion occurs
+# this is used for internal purposes only, in particular 
+# it does not dispatch arrays to jrectRef
+._java_valid_object <- function(a) {
+  if (is(a, "jobjRef")) a 
+  else if (is.null(a)) .jnull() else {
+    cm <- match(class(a)[1], names(.class.to.jclass))
+    if (!any(is.na(cm))) { 
+    	if (length(a) == 1) { 
+    		y <- .jnew(.class.to.jclass[cm], a)
+    		if (.class.to.jclass[cm] %in% .primitive.classes) attr(y, "primitive") <- TRUE
+    		y 
+    	} else .jarray(a, dispatch = FALSE)
+    } else {
+      stop("Sorry, parameter type `", cm ,"' is ambiguous or not supported.")
+    }
+  }
+}
+
+### creates a list of valid java parameters, used in both .J and .jrcall
+._java_valid_objects_list <- function( ... )
+  lapply(list(...), ._java_valid_object )
+
+
+### returns a list of Class objects
+### this is used in both .J and .jrcall
+._isPrimitiveReference <- function(x) 
+  isTRUE(attr(x, "primitive"))
+
+._java_class <- function( x ){
+  if (is.jnull(x)) { if (is(x,"jobjRef")) .jfindClass(x@jclass) else .jclassObject } else {
+    if (._isPrimitiveReference(x)) .jfield(x, "Ljava/lang/Class;", "TYPE") else .jcall(x, "Ljava/lang/Class;", "getClass")
+  }
+}
+._java_class_list <- function( objects_list )
+	lapply(objects_list, ._java_class )
+                       
+### reflected call - this high-level call uses reflection to call a method
+### it is much less efficient than .jcall but doesn't require return type
+### specification or exact matching of parameter types
+.jrcall <- function(o, method, ..., simplify=TRUE) {
+  if (!is.character(method) | length(method) != 1)
+    stop("Invalid method name - must be exactly one character string.")
+  if (inherits(o, "jobjRef") || inherits(o, "jarrayRef"))
+    cl <- .jcall(o, "Ljava/lang/Class;", "getClass")
+  else
+    cl <- .jfindClass(o)
+  if (is.null(cl))
+    stop("Cannot find class of the object.")
+  
+  # p is a list of parameters that are formed solely by valid Java objects
+  p <- ._java_valid_objects_list(...)
+  
+  # list of classes
+  pc <- ._java_class_list( p )
+  
+  # invoke the method directly from the RJavaTools class
+  # ( this throws the actual exception instead of an InvocationTargetException ) 
+  j_p  <- .jarray(p, "java/lang/Object" , dispatch = FALSE )
+  j_pc <- .jarray(pc, "java/lang/Class" , dispatch = FALSE )
+  r <- .jcall( "RJavaTools", "Ljava/lang/Object;", "invokeMethod",
+  	cl, .jcast(if(inherits(o,"jobjRef") || inherits(o, "jarrayRef")) o else cl, "java/lang/Object"), 
+  	.jnew( "java/lang/String", method), 
+  	j_p, j_pc, use.true.class = TRUE, evalString = simplify, evalArray = FALSE )
+  
+  # null is returned when the return type of the method is void
+  # TODO[romain]: not sure how to distinguish when the result is null but the 
+  #       return type is not null
+  if( is.jnull( r ) || is.null(r) ){ 
+  	return( invisible( NULL ) )
+  }
+  
+  # simplify if needed and return the object
+  if( is(r, "jarrayRef" ) && simplify ){
+  	._jarray_simplify( r )
+  } else if (simplify){
+  	  .jsimplify(r) 
+  } else  {
+  	  r
+  }
+}
+
+### reflected construction of java objects
+### This uses reflection to call a suitable constructor based 
+### on the classes of the ... it does not require exact match between 
+### the objects and the constructor parameters
+### This is to .jnew what .jrcall is to .jcall
+.J <- function(class, ...) {
+  # allow non-JNI specifiation
+  class <- gsub("\\.","/",class) 
+  
+  # p is a list of parameters that are formed solely by valid Java objects
+  p <- ._java_valid_objects_list(...)
+  
+  # list of classes
+  pc <- ._java_class_list( p )
+
+  # use RJavaTools to find create the object
+  o <- .jcall("RJavaTools", "Ljava/lang/Object;", 
+  	"newInstance", .jfindClass(class), 
+  	.jarray(p,"java/lang/Object", dispatch = FALSE ), 
+  	.jarray(pc,"java/lang/Class", dispatch = FALSE ), 
+  	evalString = FALSE, evalArray = FALSE, use.true.class = TRUE )
+  
+  o
+}
+
+## make sure Java's -2147483648 
+.iNA <- function(o, convert=TRUE) if(convert && is.na(o)) -2147483648.0 else o
+
+### simplify non-scalar reference to a scalar object if possible
+.jsimplify <- function(o, promote=FALSE) {
+  if (!inherits(o, "jobjRef") && !inherits(o, "jarrayRef"))
+    return(o)
+  cn <- .jclass(o, true=TRUE)
+  if (cn == "java.lang.Boolean") .jcall(o, "Z", "booleanValue") else
+  if (cn == "java.lang.Integer" || cn == "java.lang.Short" || cn == "java.lang.Character" || cn == "java.lang.Byte") .iNA(.jcall(o, "I", "intValue"), promote) else
+  if (cn == "java.lang.Number" || cn == "java.lang.Double" || cn == "java.lang.Long" || cn == "java.lang.Float") .jcall(o, "D", "doubleValue") else
+  if (cn == "java.lang.String") .jstrVal(.jcast(o, "java/lang/String")) else
+  o
+}
+
+#! ### get the value of a field (static class fields are not supported yet)
+#! .jrfield <- function(o, name, simplify=TRUE, true.class=TRUE) {
+#!   if (!inherits(o, "jobjRef") && !inherits(o, "jarrayRef") && !is.character(o))
+#!     stop("Object must be a Java reference or class name.")
+#!   if (is.character(o)) {
+#!     cl <- .jfindClass(o)
+#!     .jcheck(silent=TRUE)
+#!     if (is.null(cl))
+#!       stop("class not found")
+#!     o <- .jnull()
+#!   } else {
+#!     cl <- .jcall(o, "Ljava/lang/Class;", "getClass")
+#!     o <- .jcast(o, "java/lang/Object")
+#!   }
+#!   f <- .jcall(cl, "Ljava/lang/reflect/Field;", "getField", name)
+#!   r <- .jcall(f,"Ljava/lang/Object;","get",o)
+#!   if (simplify) r <- .jsimplify(r)
+#!   if (true.class && (inherits(r, "jobjRef") || inherits(r, "jarrayRef"))) {
+#!     cl <- .jcall(r, "Ljava/lang/Class;", "getClass")
+#!     cn <- .jcall(cl, "Ljava/lang/String;", "getName")
+#!     if (substr(cn,1,1) != '[')
+#!       r@jclass <- gsub("\\.","/",cn)
+#!   }
+#!   r
+#! }
+
+### list the fields of a class or object
+.jfields <- function(o, name=NULL, as.obj=FALSE) {
+  cl <- if (is(o, "jobjRef")) .jcall(o, "Ljava/lang/Class;", "getClass") else if (is(o, "jclassName")) o@jobj else .jfindClass(as.character(o))
+  f <- .jcall(cl, "[Ljava/lang/reflect/Field;", "getFields")
+  if (isTRUE(as.obj)) return(f)
+  fl <- unlist(lapply(f, function(x) .jcall(x, "S", "toString")))
+  if (!is.null(name)) grep(paste("\\.",name,"$",sep=''), fl) else fl
+}
+
+._must_be_character_of_length_one <- function(name){
+	if( !is.character(name) || length(name) != 1L ){
+		stop( "'name' must be a character vector of length one" )
+	}
+}
+### checks if the java object x has a field called name
+hasField <- function( x, name ){
+	._must_be_character_of_length_one(name)
+	.jcall("RJavaTools", "Z", "hasField", .jcast( x, "java/lang/Object" ), name)
+}
+
+hasJavaMethod <- function( x, name ){
+	._must_be_character_of_length_one(name)
+	.jcall("RJavaTools", "Z", "hasMethod", .jcast( x, "java/lang/Object" ), name)
+}
+
+hasClass <- function( x, name){
+	._must_be_character_of_length_one(name)
+	.jcall("RJavaTools", "Z", "hasClass", .jcast( x, "java/lang/Object" ), name)
+}
+
+### the following ones are needed for the static version of $
+classHasField <- function(x, name, static=FALSE) {
+	if (is(x, "jclassName")) x <- x@jobj else if (!is(x, "jobjRef")) x <- .jfindClass(as.character(x))
+	._must_be_character_of_length_one(name)
+	.jcall("RJavaTools", "Z", "classHasField", x, name, static)
+}
+
+classHasMethod <- function(x, name, static=FALSE) {
+	if (is(x, "jclassName")) x <- x@jobj else if (!is(x, "jobjRef")) x <- .jfindClass(as.character(x))
+	._must_be_character_of_length_one(name)
+	.jcall("RJavaTools", "Z", "classHasMethod", x, name, static)
+}
+
+classHasClass <- function(x, name, static=FALSE) {
+	if (is(x, "jclassName")) x <- x@jobj else if (!is(x, "jobjRef")) x <- .jfindClass(as.character(x))
+	._must_be_character_of_length_one(name)
+	.jcall("RJavaTools", "Z", "classHasClass", x, name, static)
+}
+
+### syntactic sugar to allow object$field and object$methods(...)
+### first attempts to find a field of that name and then a method
+._jobjRef_dollar <- function(x, name) {
+	if (hasField(x, name) ){
+		.jfield(x, , name)
+	} else if( hasJavaMethod( x, name ) ) {
+		function(...) .jrcall(x, name, ...)
+	} else if( hasClass(x, name) ) {
+		cl <- .jcall( x, "Ljava/lang/Class;", "getClass" )
+		inner.cl <- .jcall( "RJavaTools", "Ljava/lang/Class;", "getClass", cl, name, FALSE ) 
+		new("jclassName", name=.jcall(inner.cl, "S", "getName"), jobj=inner.cl)
+	} else if( is.character(name) && length(name) == 1L && name == "length" && isJavaArray(x) ){
+		length( x )
+	} else {
+		stop( sprintf( "no field, method or inner class called '%s' ", name ) ) 
+	}
+}
+setMethod("$", c(x="jobjRef"), ._jobjRef_dollar )
+
+### support for object$field<-...
+._jobjRef_dollargets <- function(x, name, value) {
+	if( hasField( x, name ) ){
+		.jfield(x, name) <- value
+	}
+	x
+}
+setMethod("$<-", c(x="jobjRef"), ._jobjRef_dollargets )
+
+# get a class name for an object
+.jclass <- function(o, true=TRUE) {
+  if (true) .jcall(.jcall(o, "Ljava/lang/Class;", "getClass"), "S", "getName")
+  else if( inherits( o, "jarrayRef" ) ) o@jsig else o@jclass
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/rep.R b/com.oracle.truffle.r.pkgs/rJava/R/rep.R
new file mode 100644
index 0000000000000000000000000000000000000000..b7b3f1fa4a94985052ebef4aa1a47bf223da0ebc
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/rep.R
@@ -0,0 +1,30 @@
+# :tabSize=4:indentSize=4:noTabs=false:folding=explicit:collapseFolds=1:
+
+# {{{ rep
+setGeneric("rep")
+setMethod( "rep", "jobjRef", function( x, times = 1L, ... ){
+	.jcall( "RJavaArrayTools", "[Ljava/lang/Object;", "rep", 
+		.jcast(x), as.integer(times), evalArray = FALSE )
+} )
+setMethod( "rep", "jarrayRef", function(x, times = 1L, ...){
+	.NotYetImplemented()
+} )
+setMethod( "rep", "jrectRef", function(x, times = 1L, ...){
+	.NotYetImplemented()
+} )
+# }}}
+
+# {{{ clone 
+clone <- function( x, ... ){
+	UseMethod( "clone" )
+}
+clone.default <- function( x, ... ){
+	.NotYetImplemented()
+}
+setGeneric( "clone" )
+setMethod( "clone", "jobjRef", function(x, ...){
+	.jcall( "RJavaArrayTools", "Ljava/lang/Object;", "cloneObject", .jcast( x ) ) 
+} )
+setMethod( "clone", "jarrayRef", function(x, ...){ .NotYetImplemented( ) } )
+setMethod( "clone", "jrectRef", function(x, ...){ .NotYetImplemented( ) } )
+# }}}
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/rj.R b/com.oracle.truffle.r.pkgs/rJava/R/rj.R
deleted file mode 100644
index 238d2d9a91884db9100cbf45a2f956a9cac61a68..0000000000000000000000000000000000000000
--- a/com.oracle.truffle.r.pkgs/rJava/R/rj.R
+++ /dev/null
@@ -1,392 +0,0 @@
-##
- # This material is distributed under the GNU General Public License
- # Version 2. You may review the terms of this license at
- # http://www.gnu.org/licenses/gpl-2.0.html
- #
- # Copyright (c) 2006 Simon Urbanek <simon.urbanek@r-project.org>
- # Copyright (c) 2017, Oracle and/or its affiliates
- #
- # All rights reserved.
-##
-
-#' @export
-.jnew <- function (class, ..., check = TRUE, silent = !check) {
-    class <- gsub("/", ".", as.character(class))
-    co <- new.java.class(class)
-    args <- .ellipsisToJObj(co, ...)
-    o <- .fastr.interop.try(function() { do.call(new.external, args) }, check)
-    new("jobjRef", jobj=o, jclass=class)
-}
-
-
-#' @export
-.jcall <- function (obj, returnSig = "V", method, ..., evalArray = TRUE, 
-    evalString = TRUE, check = TRUE, interface = "RcallMethod", 
-    simplify = FALSE, use.true.class = FALSE) {
-    obj <- .toJObj(obj)    
-
-    if (is.character(obj)) {
-        obj <- gsub("/", ".", as.character(obj))
-        obj <- new.java.class(obj)
-    }
-
-    args <- .ellipsisToJObj(...)
-    extMethod <- function(...) {obj[method](...)}
-    r <- .fastr.interop.try(function() { do.call(extMethod, args) }, check)
-    
-    if (is.null(r) && returnSig == "V") {
-        return(invisible(NULL))
-    }
-
-    .toS4(r)
-}
-
-#' @export
-.jfield <- function (obj, sig = NULL, name, true.class = is.null(sig), convert = TRUE) {
-    if (isS4(obj)) {
-        obj <- obj@jobj
-    }
-    if (is.character(obj)) {
-        co <- new.java.class(obj)
-        r <- co[name]
-    } else {
-        r <- obj[name]
-    }
-    .toS4(r)  
-}
-
-#' @export
-.jarray <- function (x, contents.class = NULL, dispatch = FALSE) {
-    as.java.array(x, ,TRUE)
-}
-
-#' @export
-.jevalArray <- function (x, contents.class = NULL, dispatch = FALSE) {
-    .fastr.interop.fromArray(x)
-}
-
-#' @export
-.jbyte <- function (x) {
-    storage.mode( x ) <- "integer"
-    new("jbyte", x)
-}
-
-#' @export
-.jchar <- function (x) {
-    storage.mode( x ) <- "character"
-    new("jchar", x)
-}
-
-#' @export
-.jshort <- function (x) {
-    storage.mode( x ) <- "integer"
-    new("jshort", x)
-}
-
-#' @export
-.jlong <- function (x) {
-    storage.mode( x ) <- "double"
-    new("jlong", x)
-}
-
-#' @export
-.jfloat <- function (x) {    
-    storage.mode( x ) <- "double"
-    new("jfloat", x )
-}
-
-#' @export
-J <- function (class, method, ...) {         
-    if (nargs() == 1L && missing(method)) {
-        if(inherits(class, "jclassName")) {
-            return(class)
-        } else if(is.character(class)) {
-            className <- class
-            jobj <- .jfindClass(class)
-        } else {            
-            className <- as.character(class)
-            jobj <- .jfindClass(className)
-        }
-        new("jclassName", name=className, jobj=jobj)
-    } else {
-        # .jrcall(class, method, ...)
-        .jcall(class, , method, ...)
-    }
-}
-
-#' @export
-.jpackage <- function (name, jars='*', morePaths='', nativeLibrary=FALSE, lib.loc=NULL) {
-    classes <- system.file("java", package = name, lib.loc = lib.loc)
-    if (nchar(classes)) {
-        .jaddClassPath(classes)
-        if (length(jars)) {
-            if (length(jars) == 1 && jars == "*") {
-                jars <- grep(".*\\.jar", list.files(classes, 
-                  full.names = TRUE), TRUE, value = TRUE)
-                if (length(jars)) 
-                  .jaddClassPath(jars)
-            }
-            else .jaddClassPath(paste(classes, jars, sep = .Platform$file.sep))
-        }
-    }
-    if (any(nchar(morePaths))) {
-        cl <- as.character(morePaths)
-        cl <- cl[nchar(cl) > 0]
-        .jaddClassPath(cl)
-    }
-    if (is.logical(nativeLibrary)) {
-        if (nativeLibrary) {
-            libs <- "libs"
-            if (nchar(.Platform$r_arch)) 
-                lib <- file.path("libs", .Platform$r_arch)
-            lib <- system.file(libs, paste(name, .Platform$dynlib.ext, 
-                sep = ""), package = name, lib.loc = lib.loc)
-            if (nchar(lib)) 
-                .jaddLibrary(name, lib)
-            else warning("Native library for `", name, "' could not be found.")
-        }
-    }
-    else {
-        .jaddLibrary(name, nativeLibrary)
-    }
-    invisible(TRUE)
-}
-
-#' @export
-.jaddClassPath <- function (path) {
-    java.addToClasspath(path)
-}
-
-#' @export
-.jfindClass <- function (cl, silent = FALSE) {
-    if (inherits(cl, "jclassName")) return(cl@jobj)
-    if (!is.character(cl) || length(cl)!=1) {
-        stop("invalid class name")
-    }
-
-    cl <- gsub("/", ".", as.character(cl))
-    javaClass <- new.java.class(cl)
-    cls <- new('jobjRef', jobj=javaClass, jclass='java.lang.Class', stringValue=paste0("class ", cl))
-    .jcheck(silent)
-    if (!silent && is.jnull(cls)) stop("class not found")
-    cls
-}
-
-.toS4 <- function(obj) {
-    res <- obj
-    if (is.external(obj)) {        
-        if (is.external.array(obj)) {
-            res <- as.vector(obj)
-        } else {
-            res <- new("jobjRef", jobj=obj, jclass=java.class(obj))
-        }        
-    } 
-    res
-}
-
-.ellipsisToJObj <- function(...) {
-    lapply(list(...), function(x) .toJObj(x))
-}
-
-.toJObj <- function(x) {
-    if (is(x, "jobjRef")) {
-        x@jobj
-    } else if (is(x, "jclassName")) {
-        x@jobj@jobj
-    } else if (is(x, "jbyte")) {
-        as.external.byte(x)    
-    } else if (is(x, "jchar")) {
-        as.external.char(x)    
-    } else if (is(x, "jfloat")) {
-        as.external.float(x)
-    } else if (is(x, "jlong")) {
-        as.external.long(x)
-    } else if (is(x, "jshort")) {
-        as.external.short(x)        
-    } else {
-        x
-    } 
-}
-
-#' @export
-.jgetEx <- function (clear = FALSE) {
-    interopEx <- .fastr.interop.getTryException(clear)
-    if (is.null(interopEx))
-        return(NULL)
-    new("jobjRef", jobj = interopEx, jclass = "java/lang/Throwable")
-}
-
-#' @export
-.jclear <- function () {
-     invisible(.fastr.interop.clearTryException())
-}
-
-#' @export
-.jinit <- function (classpath = NULL, parameters = getOption("java.parameters"), ..., silent = FALSE, force.init = FALSE) {
-    if (!is.null(classpath)) java.addToClasspath(classpath)
-}
-
-#' @export
-.jnull <- function (class = "java/lang/Object") {
-    new("jobjRef", jobj=NULL, jclass=class)
-}
-
-#' @export
-is.jnull <- function (x) {
-    is.null(x) || is.external.null(x) || (is(x,"jobjRef") && is.null(x@jobj))
-}
-
-#' @export
-.jaddLibrary <- function (name, path) {
-    cat(paste0("********************************************************\n",
-           "*** WARNING!!!\n",
-           "*** .jaddLibrary is not yet implemented.\n",
-           "*** Please ensure that all native libraries from:\n",
-           "*** ", path, "\n",
-           "*** are set on LD_LIBRARY_PATH or java.library.path\n",
-           "********************************************************\n"))
-}
-
-#' @export
-.jcast <- function(obj, new.class="java/lang/Object", check = FALSE, convert.array = FALSE) {
-  if (!is(obj,"jobjRef"))
-    stop("cannot cast anything but Java objects")
-  # TODO implement checks  
-  # if( check && !.jinstanceof( obj, new.class) ){
-  #     stop( sprintf( "cannot cast object to '%s'", new.class ) ) 
-  # }
-  
-  new.class <- gsub("\\.","/", as.character(new.class)) # allow non-JNI specifiation
-  # if( convert.array && !is( obj, "jarrayRef" ) && isJavaArray( obj ) ){
-  #    r <- .jcastToArray( obj, signature = new.class)
-  # } else {
-     r <- obj
-     r@jclass <- new.class
-  # }
-  r
-}
-
-#' @export
-.jstrVal <- function (obj) {
-    if (is.character(obj)) {
-        return(obj)
-    }    
-    r <- NULL
-    if (!is(obj, "jobjRef")) {
-        stop("can get value of Java objects only")
-    }
-    if(!is.null(obj@stringValue)) {
-        obj@stringValue
-    } else {
-        obj@jobj["toString"]()
-    }
-}
-
-.isJavaArray <- function(o){
-    is.external.array(o) && java.class(o) != NULL
-}
-
-#
-# S4
-#
-
-setClass("truffle.object", representation(jobj="ANY"))
-setClassUnion("TruffleObjectOrNull",members=c("truffle.object", "NULL"))
-setClassUnion("characterOrNull",members=c("character", "NULL"))
-
-#
-# jobjRef
-#
-setClass("jobjRef", representation(jobj="TruffleObjectOrNull", jclass="character", stringValue="characterOrNull"), prototype=list(jobj=NULL, jclass="java/lang/Object", stringValue=NULL))
-
-setMethod("$", c(x="jobjRef"), function(x, name) {
-    if(name %in% names(x@jobj)) {        
-        if(is.external.executable(x@jobj[name])) {
-            function(...) { .jcall(x, , name, ...) }    
-        } else {
-            .jfield(x, , name)                
-        }
-    } else if( is.character(name) && length(name) == 1L && name == "length" && is.external.array(x) ) {
-        length( x@obj )
-    } else {
-        stop(sprintf( "no field, method or inner class called '%s' ", name)) 
-    }
-})
-
-setMethod("$<-", c(x="jobjRef"), function(x, name, value) {
-    if(name %in% names(x@jobj)) {
-        if(!is.external.executable(x@jobj[name])) {
-            value <- .toJObj(value)
-            x@jobj[name] <- value
-        }
-    }
-    x
-})
-
-setMethod("show", c(object="jobjRef"), function(object) {
-    if (is.jnull(object)) {
-        show("Java-Object<null>") 
-    } else {
-        show(paste("Java-Object{", .jstrVal(object), "}", sep=''))
-    }
-    invisible(NULL)
-})
-
-#
-# jclassName
-#
-
-setClass("jclassName", representation(name="character", jobj="jobjRef"))
-setMethod("show", c(object="jclassName"), function(object) {
-    invisible(show(paste("Java-Class-Name:", object@name)))
-})
-setMethod("as.character", c(x="jclassName"), function(x, ...) x@name)
-setMethod("$", c(x="jclassName"), function(x, name) {
-    if(name == "class") {
-        x@jobj
-    } 
-    obj <- x@jobj@jobj
-    if(name %in% names(obj)) {
-        if(is.external.executable(obj[name])) {
-            function(...) { .jcall(obj, , name, ...) }    
-        } else {
-            .jfield(obj, , name)
-        }
-    } else {
-        stop("no static field, method or inner class called `", name, "' in `", x@name, "'")
-    } 
-})
-setMethod("$<-", c(x="jclassName"), function(x, name, value) {
-    value <- .toJObj(value)
-    x@jobj@jobj[name] <- value
-    x
-})
-
-# TODO makes CMD INSTALL complain
-# setGeneric("new")
-# setMethod("new", signature(Class="jclassName"), function(Class, ...) .jnew(Class, ...))
-
-setClass("jfloat", representation("array"))
-setClass("jlong", representation("array"))
-setClass("jbyte", representation("array"))
-setClass("jshort", representation("array"))
-setClass("jchar", representation("array"))
-
-#
-# noop stubs
-#
-
-#' @export
-.jsimplify <- function (x) {
-    x
-}
-
-#' @export
-.jcheck <- function(silent = FALSE) {
-    FALSE
-}
-
-#' @export
-.jthrow <- function (exception, message = NULL) {
-    # do nothing
-}
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/serialize.R b/com.oracle.truffle.r.pkgs/rJava/R/serialize.R
new file mode 100644
index 0000000000000000000000000000000000000000..6ea884296d202adaa8309540775ec1c30fe42d78
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/serialize.R
@@ -0,0 +1,29 @@
+## Java serialization/unserialization
+
+.jserialize <- function(o) {
+  if (!is(o, "jobjRef"))
+    stop("can serialize Java objects only")
+  .jcall("RJavaClassLoader","[B","toByte",.jcast(o, "java.lang.Object"))
+}
+
+.junserialize <- function(data) {
+  if (!is.raw(data))
+    stop("can de-serialize raw vectors only")
+  o <- .jcall("RJavaClassLoader","Ljava/lang/Object;","toObjectPL",.jarray(data, dispatch = FALSE))
+  if (!is.jnull(o)) {
+    cl<-try(.jclass(o), silent=TRUE)
+    if (all(class(cl) == "character"))
+      o@jclass <- gsub("\\.","/",cl)
+  }
+  o
+}
+
+.jcache <- function(o, update=TRUE) {
+  if (!is(o, "jobjRef"))
+    stop("o must be a Java object")
+  if (!is.null(update) && (!is.logical(update) || length(update) != 1))
+    stop("update must be TRUE, FALSE of NULL")
+  what <- update
+  if (isTRUE(what)) what <- .jserialize(o)
+  invisible(.Call(javaObjectCache, o@jobj, what))
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/tools.R b/com.oracle.truffle.r.pkgs/rJava/R/tools.R
new file mode 100644
index 0000000000000000000000000000000000000000..53946d5da9b8649573d3075ee4487b6f4b90e7e1
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/tools.R
@@ -0,0 +1,28 @@
+#' converts a java class name to jni notation
+tojni <- function( cl = "java.lang.Object" ){
+	gsub( "[.]", "/", cl )
+}
+
+tojniSignature <- function( cl ){
+	sig <- tojni( cl )
+	
+	if( isPrimitiveTypeName(sig) || isPrimitiveArraySignature(sig) ){
+		return( sig ) 
+	}
+	
+	n <- nchar( sig )
+	last <- substr( sig, n, n )
+	add.semi <- last != ";"
+	
+	first <- substr( sig, 1, 1 )
+	add.L <- ! first %in% c("L", "[" )
+	
+	sig <- if( !add.L && !add.semi) sig else sprintf( "%s%s%s", if( add.L ) "L" else "", sig, if( add.semi ) ";" else "" )
+	sig
+}
+
+#' converts jni notation to java notation
+tojava <- function( cl = "java/lang/Object" ){
+	gsub( "/", ".", cl )
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/windows/FirstLib.R b/com.oracle.truffle.r.pkgs/rJava/R/windows/FirstLib.R
new file mode 100755
index 0000000000000000000000000000000000000000..09694b4d709e4fc3238644b2e972024106886dda
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/windows/FirstLib.R
@@ -0,0 +1,57 @@
+.onLoad <-
+function(libname, pkgname) {
+    OPATH <- Sys.getenv("PATH")
+    javahome <- if (!is.null(getOption("java.home"))) getOption("java.home") else Sys.getenv("JAVA_HOME")
+    if(!nchar(javahome)) { ## JAVA_HOME was not set explicitly
+        find.java <- function() {
+            for (root in c("HLM", "HCU"))
+                for(key in c(
+                               "Software\\JavaSoft\\JRE",
+                               "Software\\JavaSoft\\JDK",
+                               "Software\\JavaSoft\\Java Runtime Environment",
+                               "Software\\JavaSoft\\Java Development Kit"
+                             )) {
+                  hive <- try(utils::readRegistry(key, root, 2), silent=TRUE)
+                  if (!inherits(hive, "try-error")) return(hive)
+                }
+            hive
+        }
+        hive <- find.java()
+        if (inherits(hive, "try-error"))
+            stop("JAVA_HOME cannot be determined from the Registry")
+        if (!length(hive$CurrentVersion))
+            stop("No CurrentVersion entry in Software/JavaSoft registry! Try re-installing Java and make sure R and Java have matching architectures.")
+        this <- hive[[hive$CurrentVersion]]
+        javahome <- this$JavaHome
+        paths <- dirname(this$RuntimeLib) # wrong on 64-bit
+    } else paths <- character()
+    if(is.null(javahome) || !length(javahome) || !nchar(javahome))
+        stop("JAVA_HOME is not set and could not be determined from the registry")
+    #else cat("using JAVA_HOME =", javahome, "\n")
+
+    ## we need to add Java-related library paths to PATH
+    curPath <- OPATH
+    paths <- c(paths,
+               file.path(javahome, "bin", "client"), # 32-bit
+               file.path(javahome, "bin", "server"), # 64-bit
+               file.path(javahome, "bin"), # base (now needed for MSVCRT in recent Sun Java)
+               file.path(javahome, "jre", "bin", "server"), # old 64-bit (or manual JAVA_HOME setting to JDK)
+               file.path(javahome, "jre", "bin", "client")) # old 32-bit (or manual JAVA_HOME setting to JDK)
+    cpc <- strsplit(curPath, ";", fixed=TRUE)[[1]] ## split it up so we can check presence/absence of a path
+
+    ## add paths only if they are not in already and they exist
+    for (path in unique(paths))
+        if (!path %in% cpc && file.exists(path)) curPath <- paste(path, curPath, sep=";")
+
+    ## set PATH only if it's not correct already (cannot use identical/isTRUE because of PATH name attribute)
+    if (curPath != OPATH) {
+      Sys.setenv(PATH = curPath)
+      # check the resulting PATH - if they don't match then Windows has truncated it
+      if (curPath != Sys.getenv("PATH"))
+        warning("*** WARNING: your Windows system seems to suffer from truncated PATH bug which will likely prevent rJava from loading.\n      Either reduce your PATH or read http://support.microsoft.com/kb/906469 on how to fix your system.")
+    }
+
+    library.dynam("rJava", pkgname, libname)
+    Sys.setenv(PATH = OPATH)
+    .jfirst(libname, pkgname)
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/with.R b/com.oracle.truffle.r.pkgs/rJava/R/with.R
new file mode 100644
index 0000000000000000000000000000000000000000..0111dfab16d21b79cdbbccd18048bc0f0f1018ce
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/with.R
@@ -0,0 +1,175 @@
+## This program 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, see <http://www.gnu.org/licenses/>.
+##
+## Author: Romain Francois <francoisromain@free.fr>
+
+._populate_with_fields_and_methods <- function( env, fields, methods, classes, data, only.static = FALSE ){
+	object <- if( only.static ) .jnull() else .jcast( data )
+	
+	# fields 
+	if( !is.jnull(fields) ) {
+		lapply( fields, function(x ){
+  		  n <- .jcall( x, "S", "getName" )
+  		  type <- .jcall( .jcall( x, "Ljava/lang/Class;", "getType"), "Ljava/lang/String;" , "getName" )
+  		  suffix <- switch( type, 
+  		  	"boolean" = "Boolean", 
+  		  	"byte" = "Byte", 
+  		  	"char" = "Char",
+  		  	"double" = "Double", 
+  		  	"float" = "Float", 
+  		  	"int" = "Int", 
+  		  	"long" = "Long", 
+  		  	"short" = "Short",
+  		  	"" )
+  		  target <- switch( type,
+  		  	"boolean" = "Z", 
+  		  	"byte" = "B", 
+  		  	"char" = "C",
+  		  	"double" = "D", 
+  		  	"float" = "F", 
+  		  	"int" = "I", 
+  		  	"long" = "L", 
+  		  	"short" = "S",
+  		  	"Ljava/lang/Object;" )
+  		  set_method <- sprintf( "set%s", suffix)
+  		  get_method <- sprintf( "get%s", suffix )
+  		  	
+  		  makeActiveBinding( n, function(v){
+  		    if( missing(v) ){
+  		      ## get
+  		      .jcall( x, target, get_method, object )
+  		    } else {
+  		      ## set
+  		      .jcall( x, "V", set_method , object, v )
+  		    }
+  		  }, env )
+  		} )
+  	}
+  	
+  	# methods
+  	if( !is.jnull(methods) ){
+  		done.this <- NULL
+  		lapply( methods, function(m){
+  			n <- .jcall( m, "S", "getName" )
+  			if( n %in% done.this ) return()
+  		  fallback <- tryCatch( match.fun( n ), error = function(e) NULL )
+  		  assign( n, function(...) {
+  		    tryCatch( .jrcall( if(only.static) data@name else data , n, ...), error = function(e){
+  		      if( !is.null(fallback) && inherits(fallback, "function") ){
+  		        fallback( ... )
+  		      }
+  		    } )
+  		  }, env )
+  		  done.this <<- c( done.this, n )
+  		} )
+  	}
+  	
+  	# classes
+  	if( !is.jnull( classes ) ){
+  		lapply( classes, function( cl ){
+  			name <- .jcall( cl, "S", "getSimpleName" )
+  			assign( name, new("jclassName", name=.jcall(cl, "S", "getName"), jobj=cl), env )
+  		} )
+  	}
+}
+grabDots <- function( env, ...){
+  dots <- list(...)
+  if( length( dots ) ){
+  	dots.names <- names(dots)
+  	sapply( dots.names, function( name ){
+  		if( name != "" ){
+  			assign( name, dots[[ name ]], env )
+  		}
+  	} )
+  	
+  }
+}
+
+with.jobjRef <- function( data, expr, ...){
+  env <- new.env( parent = parent.frame() )
+  clazz <- .jcall( data, "Ljava/lang/Class;", "getClass")
+  
+  fields  <- .jcall( clazz, "[Ljava/lang/reflect/Field;", "getFields" )
+  methods <- .jcall( clazz, "[Ljava/lang/reflect/Method;", "getMethods" )
+  classes <- .jcall( clazz, "[Ljava/lang/Class;" , "getClasses" )
+  ._populate_with_fields_and_methods( env, fields, methods, classes, data, only.static = FALSE )
+
+  assign( "this", data, env )
+
+  grabDots( env, ... )
+  
+  eval( substitute( expr ), env )
+}
+
+within.jobjRef <- function(data, expr, ... ){
+  call <- match.call()
+  call[[1]] <- as.name("with.jobjRef")
+  eval( call, parent.frame() )
+  data
+}
+
+with.jarrayRef <- function( data, expr, ...){
+  env <- new.env( parent = environment() )
+  clazz <- .jcall( data, "Ljava/lang/Class;", "getClass")
+  
+  fields  <- .jcall( clazz, "[Ljava/lang/reflect/Field;", "getFields" )
+  methods <- .jcall( clazz, "[Ljava/lang/reflect/Method;", "getMethods" )
+  classes <- .jcall( clazz, "[Ljava/lang/Class;" , "getClasses" )
+  ._populate_with_fields_and_methods( env, fields, methods, classes, data, only.static = FALSE )
+
+  assign( "this", data, env )
+
+  # add "length" pseudo field
+  makeActiveBinding( "length", function(v){
+  	if( missing( v ) ){
+  		._length_java_array( data )
+  	} else{
+  		stop( "cannot modify length of java array" ) 
+  	}
+  }, env )
+  
+  grabDots( env, ... )
+  
+  eval( substitute( expr ), env )
+}
+
+within.jarrayRef <- function(data, expr, ... ){
+  call <- match.call()
+  call[[1]] <- as.name("with.jarrayRef")
+  eval( call, parent.frame() )
+  data
+}
+
+with.jclassName <- function( data, expr, ... ){
+	env <- new.env( parent = environment() )
+	clazz <- data@jobj
+	
+	static_fields  <- .jcall( "RJavaTools", "[Ljava/lang/reflect/Field;",  "getStaticFields",  clazz )
+	static_methods <- .jcall( "RJavaTools", "[Ljava/lang/reflect/Method;",  "getStaticMethods",  clazz )
+	static_classes <- .jcall( clazz, "[Ljava/lang/Class;",  "getClasses" )
+	
+	._populate_with_fields_and_methods( env, static_fields, 
+		static_methods, static_classes, data, only.static = TRUE )
+	
+	grabDots( env, ... )
+	eval( substitute( expr ), env )
+}
+
+within.jclassName <- function(data, expr, ... ){
+  call <- match.call()
+  call[[1]] <- as.name("with.jclassName")
+  eval( call, parent.frame() )
+  data
+}
+
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/zzz.R b/com.oracle.truffle.r.pkgs/rJava/R/zzz.R
new file mode 100644
index 0000000000000000000000000000000000000000..eb8aba7170cb0b84b56168ba4593abc574d0f44b
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/zzz.R
@@ -0,0 +1,20 @@
+.onLoad <- function(libname, pkgname) {
+  Sys.setenv("LD_LIBRARY_PATH"=paste(Sys.getenv("LD_LIBRARY_PATH"),"@JAVA_LD@",sep=':'))
+  ## On OS X with Oracle Java we may need to work around Oracle bug:
+  ## https://bugs.openjdk.java.net/browse/JDK-7131356
+  if (length(grep("^darwin", R.version$os)) && file.exists("/usr/libexec/java_home")) {
+     jh <- Sys.getenv("JAVA_HOME")
+     if (!nzchar(jh)) jh <- system("/usr/libexec/java_home", intern=TRUE)[1L]
+     if (file.exists(file.path(jh, "jre/lib"))) jh <- file.path(jh, "jre")
+     if (file.exists(jli <- file.path(jh, "lib/jli/libjli.dylib"))) {
+       dyn.load(jli, FALSE)
+       dlp <- Sys.getenv("DYLD_LIBRARY_PATH")
+       if (nzchar(dlp)) dlp <- paste0(":", dlp)
+       if (file.exists(file.path(jh, "lib/server/libjvm.dylib")))
+         Sys.setenv(DYLD_LIBRARY_PATH=paste0(file.path(jh, "lib/server"), dlp))
+     }
+  }
+  library.dynam("rJava", pkgname, libname)
+  # pass on to the system-independent part
+  .jfirst(libname, pkgname)
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/R/zzz.R.in b/com.oracle.truffle.r.pkgs/rJava/R/zzz.R.in
new file mode 100644
index 0000000000000000000000000000000000000000..eb8aba7170cb0b84b56168ba4593abc574d0f44b
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/R/zzz.R.in
@@ -0,0 +1,20 @@
+.onLoad <- function(libname, pkgname) {
+  Sys.setenv("LD_LIBRARY_PATH"=paste(Sys.getenv("LD_LIBRARY_PATH"),"@JAVA_LD@",sep=':'))
+  ## On OS X with Oracle Java we may need to work around Oracle bug:
+  ## https://bugs.openjdk.java.net/browse/JDK-7131356
+  if (length(grep("^darwin", R.version$os)) && file.exists("/usr/libexec/java_home")) {
+     jh <- Sys.getenv("JAVA_HOME")
+     if (!nzchar(jh)) jh <- system("/usr/libexec/java_home", intern=TRUE)[1L]
+     if (file.exists(file.path(jh, "jre/lib"))) jh <- file.path(jh, "jre")
+     if (file.exists(jli <- file.path(jh, "lib/jli/libjli.dylib"))) {
+       dyn.load(jli, FALSE)
+       dlp <- Sys.getenv("DYLD_LIBRARY_PATH")
+       if (nzchar(dlp)) dlp <- paste0(":", dlp)
+       if (file.exists(file.path(jh, "lib/server/libjvm.dylib")))
+         Sys.setenv(DYLD_LIBRARY_PATH=paste0(file.path(jh, "lib/server"), dlp))
+     }
+  }
+  library.dynam("rJava", pkgname, libname)
+  # pass on to the system-independent part
+  .jfirst(libname, pkgname)
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/README.md b/com.oracle.truffle.r.pkgs/rJava/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..3bf875fb0f8d5dfda7a57b2a0e6518352ba77a52
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/README.md
@@ -0,0 +1,33 @@
+# rJava
+R/Java interface allowing the use of Java from R as well as embedding
+R into Java (via JRI)
+
+Please visit the [main rJava project page on
+RForge.net](http://rforge.net) for details.
+
+### Installation
+
+Recommended installation of the latest development version is via
+
+    install.packages("rJava",,"http://rforge.net")
+
+in R. The RForge.net repository is updated automatically on each
+commit. On OS X you may need to add `type='source'`.
+
+### Sources
+
+When checking out the sources, you *must* use
+
+    git clone --recursive https://github.com/s-u/rJava.git
+
+since rJava includes REngine as a submodule. If you want to create a
+package from the source checkout, you *must* use `sh mkdist` to do so
+since the checkout is not the acutal package.
+
+### Mailing list and bug reports
+
+Please use
+[stats-rosuda-devel](https://mailman.rz.uni-augsburg.de/mailman/listinfo/stats-rosuda-devel)
+mailing list for questions about rJava and [rJava GitHub issues
+page](https://github.com/s-u/rJava/issues) to report bugs.
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/config.status b/com.oracle.truffle.r.pkgs/rJava/config.status
new file mode 100755
index 0000000000000000000000000000000000000000..58cc7d8f6e5adc57379c453e22794efdcbefc446
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/config.status
@@ -0,0 +1,1010 @@
+#! /bin/sh
+# Generated by configure.
+# Run this file to recreate the current configuration.
+# Compiler output produced by configure, useful for debugging
+# configure, is in config.log if it exists.
+
+debug=false
+ac_cs_recheck=false
+ac_cs_silent=false
+
+SHELL=${CONFIG_SHELL-/bin/sh}
+export SHELL
+## -------------------- ##
+## M4sh Initialization. ##
+## -------------------- ##
+
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
+  emulate sh
+  NULLCMD=:
+  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in #(
+  *posix*) :
+    set -o posix ;; #(
+  *) :
+     ;;
+esac
+fi
+
+
+as_nl='
+'
+export as_nl
+# Printing a long string crashes Solaris 7 /usr/bin/printf.
+as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
+# Prefer a ksh shell builtin over an external printf program on Solaris,
+# but without wasting forks for bash or zsh.
+if test -z "$BASH_VERSION$ZSH_VERSION" \
+    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='print -r --'
+  as_echo_n='print -rn --'
+elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='printf %s\n'
+  as_echo_n='printf %s'
+else
+  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
+    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
+    as_echo_n='/usr/ucb/echo -n'
+  else
+    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
+    as_echo_n_body='eval
+      arg=$1;
+      case $arg in #(
+      *"$as_nl"*)
+	expr "X$arg" : "X\\(.*\\)$as_nl";
+	arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
+      esac;
+      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
+    '
+    export as_echo_n_body
+    as_echo_n='sh -c $as_echo_n_body as_echo'
+  fi
+  export as_echo_body
+  as_echo='sh -c $as_echo_body as_echo'
+fi
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  PATH_SEPARATOR=:
+  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
+    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
+      PATH_SEPARATOR=';'
+  }
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+IFS=" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+as_myself=
+case $0 in #((
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+  done
+IFS=$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  exit 1
+fi
+
+# Unset variables that we do not need and which cause bugs (e.g. in
+# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
+# suppresses any "Segmentation fault" message there.  '((' could
+# trigger a bug in pdksh 5.2.14.
+for as_var in BASH_ENV ENV MAIL MAILPATH
+do eval test x\${$as_var+set} = xset \
+  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+LC_ALL=C
+export LC_ALL
+LANGUAGE=C
+export LANGUAGE
+
+# CDPATH.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+
+# as_fn_error STATUS ERROR [LINENO LOG_FD]
+# ----------------------------------------
+# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
+# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
+# script with STATUS, using 1 if that was 0.
+as_fn_error ()
+{
+  as_status=$1; test $as_status -eq 0 && as_status=1
+  if test "$4"; then
+    as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
+  fi
+  $as_echo "$as_me: error: $2" >&2
+  as_fn_exit $as_status
+} # as_fn_error
+
+
+# as_fn_set_status STATUS
+# -----------------------
+# Set $? to STATUS, without forking.
+as_fn_set_status ()
+{
+  return $1
+} # as_fn_set_status
+
+# as_fn_exit STATUS
+# -----------------
+# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
+as_fn_exit ()
+{
+  set +e
+  as_fn_set_status $1
+  exit $1
+} # as_fn_exit
+
+# as_fn_unset VAR
+# ---------------
+# Portably unset VAR.
+as_fn_unset ()
+{
+  { eval $1=; unset $1;}
+}
+as_unset=as_fn_unset
+# as_fn_append VAR VALUE
+# ----------------------
+# Append the text in VALUE to the end of the definition contained in VAR. Take
+# advantage of any shell optimizations that allow amortized linear growth over
+# repeated appends, instead of the typical quadratic growth present in naive
+# implementations.
+if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
+  eval 'as_fn_append ()
+  {
+    eval $1+=\$2
+  }'
+else
+  as_fn_append ()
+  {
+    eval $1=\$$1\$2
+  }
+fi # as_fn_append
+
+# as_fn_arith ARG...
+# ------------------
+# Perform arithmetic evaluation on the ARGs, and store the result in the
+# global $as_val. Take advantage of shells that can avoid forks. The arguments
+# must be portable across $(()) and expr.
+if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
+  eval 'as_fn_arith ()
+  {
+    as_val=$(( $* ))
+  }'
+else
+  as_fn_arith ()
+  {
+    as_val=`expr "$@" || test $? -eq 1`
+  }
+fi # as_fn_arith
+
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+  as_basename=basename
+else
+  as_basename=false
+fi
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
+
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in #(((((
+-n*)
+  case `echo 'xy\c'` in
+  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
+  xy)  ECHO_C='\c';;
+  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
+       ECHO_T='	';;
+  esac;;
+*)
+  ECHO_N='-n';;
+esac
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir 2>/dev/null
+fi
+if (echo >conf$$.file) 2>/dev/null; then
+  if ln -s conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s='ln -s'
+    # ... but there are two gotchas:
+    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+    # In both cases, we have to default to `cp -pR'.
+    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+      as_ln_s='cp -pR'
+  elif ln conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s=ln
+  else
+    as_ln_s='cp -pR'
+  fi
+else
+  as_ln_s='cp -pR'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+
+# as_fn_mkdir_p
+# -------------
+# Create "$as_dir" as a directory, including parents if necessary.
+as_fn_mkdir_p ()
+{
+
+  case $as_dir in #(
+  -*) as_dir=./$as_dir;;
+  esac
+  test -d "$as_dir" || eval $as_mkdir_p || {
+    as_dirs=
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
+      *) as_qdir=$as_dir;;
+      esac
+      as_dirs="'$as_qdir' $as_dirs"
+      as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_dir" : 'X\(//\)[^/]' \| \
+	 X"$as_dir" : 'X\(//\)$' \| \
+	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_dir" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+      test -d "$as_dir" && break
+    done
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
+
+
+} # as_fn_mkdir_p
+if mkdir -p . 2>/dev/null; then
+  as_mkdir_p='mkdir -p "$as_dir"'
+else
+  test -d ./-p && rmdir ./-p
+  as_mkdir_p=false
+fi
+
+
+# as_fn_executable_p FILE
+# -----------------------
+# Test if FILE is an executable regular file.
+as_fn_executable_p ()
+{
+  test -f "$1" && test -x "$1"
+} # as_fn_executable_p
+as_test_x='test -x'
+as_executable_p=as_fn_executable_p
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+exec 6>&1
+## ----------------------------------- ##
+## Main body of $CONFIG_STATUS script. ##
+## ----------------------------------- ##
+# Save the log message, to keep $0 and so on meaningful, and to
+# report actual input values of CONFIG_FILES etc. instead of their
+# values after options handling.
+ac_log="
+This file was extended by rJava $as_me 0.8, which was
+generated by GNU Autoconf 2.69.  Invocation command line was
+
+  CONFIG_FILES    = $CONFIG_FILES
+  CONFIG_HEADERS  = $CONFIG_HEADERS
+  CONFIG_LINKS    = $CONFIG_LINKS
+  CONFIG_COMMANDS = $CONFIG_COMMANDS
+  $ $0 $@
+
+on `(hostname || uname -n) 2>/dev/null | sed 1q`
+"
+
+# Files that config.status was made for.
+config_files=" src/Makevars R/zzz.R"
+config_headers=" src/config.h"
+
+ac_cs_usage="\
+\`$as_me' instantiates files and other configuration actions
+from templates according to the current configuration.  Unless the files
+and actions are specified as TAGs, all are instantiated by default.
+
+Usage: $0 [OPTION]... [TAG]...
+
+  -h, --help       print this help, then exit
+  -V, --version    print version number and configuration settings, then exit
+      --config     print configuration, then exit
+  -q, --quiet, --silent
+                   do not print progress messages
+  -d, --debug      don't remove temporary files
+      --recheck    update $as_me by reconfiguring in the same conditions
+      --file=FILE[:TEMPLATE]
+                   instantiate the configuration file FILE
+      --header=FILE[:TEMPLATE]
+                   instantiate the configuration header FILE
+
+Configuration files:
+$config_files
+
+Configuration headers:
+$config_headers
+
+Report bugs to <Simon.Urbanek@r-project.org>."
+
+ac_cs_config=""
+ac_cs_version="\
+rJava config.status 0.8
+configured by ./configure, generated by GNU Autoconf 2.69,
+  with options \"$ac_cs_config\"
+
+Copyright (C) 2012 Free Software Foundation, Inc.
+This config.status script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it."
+
+ac_pwd='/work/src/rjava/rjava.github'
+srcdir='.'
+test -n "$AWK" || AWK=awk
+# The default lists apply if the user does not specify any file.
+ac_need_defaults=:
+while test $# != 0
+do
+  case $1 in
+  --*=?*)
+    ac_option=`expr "X$1" : 'X\([^=]*\)='`
+    ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
+    ac_shift=:
+    ;;
+  --*=)
+    ac_option=`expr "X$1" : 'X\([^=]*\)='`
+    ac_optarg=
+    ac_shift=:
+    ;;
+  *)
+    ac_option=$1
+    ac_optarg=$2
+    ac_shift=shift
+    ;;
+  esac
+
+  case $ac_option in
+  # Handling of the options.
+  -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
+    ac_cs_recheck=: ;;
+  --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
+    $as_echo "$ac_cs_version"; exit ;;
+  --config | --confi | --conf | --con | --co | --c )
+    $as_echo "$ac_cs_config"; exit ;;
+  --debug | --debu | --deb | --de | --d | -d )
+    debug=: ;;
+  --file | --fil | --fi | --f )
+    $ac_shift
+    case $ac_optarg in
+    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    '') as_fn_error $? "missing file argument" ;;
+    esac
+    as_fn_append CONFIG_FILES " '$ac_optarg'"
+    ac_need_defaults=false;;
+  --header | --heade | --head | --hea )
+    $ac_shift
+    case $ac_optarg in
+    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    esac
+    as_fn_append CONFIG_HEADERS " '$ac_optarg'"
+    ac_need_defaults=false;;
+  --he | --h)
+    # Conflict between --help and --header
+    as_fn_error $? "ambiguous option: \`$1'
+Try \`$0 --help' for more information.";;
+  --help | --hel | -h )
+    $as_echo "$ac_cs_usage"; exit ;;
+  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+  | -silent | --silent | --silen | --sile | --sil | --si | --s)
+    ac_cs_silent=: ;;
+
+  # This is an error.
+  -*) as_fn_error $? "unrecognized option: \`$1'
+Try \`$0 --help' for more information." ;;
+
+  *) as_fn_append ac_config_targets " $1"
+     ac_need_defaults=false ;;
+
+  esac
+  shift
+done
+
+ac_configure_extra_args=
+
+if $ac_cs_silent; then
+  exec 6>/dev/null
+  ac_configure_extra_args="$ac_configure_extra_args --silent"
+fi
+
+if $ac_cs_recheck; then
+  set X /bin/sh './configure'  $ac_configure_extra_args --no-create --no-recursion
+  shift
+  $as_echo "running CONFIG_SHELL=/bin/sh $*" >&6
+  CONFIG_SHELL='/bin/sh'
+  export CONFIG_SHELL
+  exec "$@"
+fi
+
+exec 5>>config.log
+{
+  echo
+  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
+## Running $as_me. ##
+_ASBOX
+  $as_echo "$ac_log"
+} >&5
+
+
+# Handling of arguments.
+for ac_config_target in $ac_config_targets
+do
+  case $ac_config_target in
+    "src/config.h") CONFIG_HEADERS="$CONFIG_HEADERS src/config.h" ;;
+    "src/Makevars") CONFIG_FILES="$CONFIG_FILES src/Makevars" ;;
+    "R/zzz.R") CONFIG_FILES="$CONFIG_FILES R/zzz.R" ;;
+
+  *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
+  esac
+done
+
+
+# If the user did not use the arguments to specify the items to instantiate,
+# then the envvar interface is used.  Set only those that are not.
+# We use the long form for the default assignment because of an extremely
+# bizarre bug on SunOS 4.1.3.
+if $ac_need_defaults; then
+  test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
+  test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers
+fi
+
+# Have a temporary directory for convenience.  Make it in the build tree
+# simply because there is no reason against having it here, and in addition,
+# creating and moving files from /tmp can sometimes cause problems.
+# Hook for its removal unless debugging.
+# Note that there is a small window in which the directory will not be cleaned:
+# after its creation but before its name has been assigned to `$tmp'.
+$debug ||
+{
+  tmp= ac_tmp=
+  trap 'exit_status=$?
+  : "${ac_tmp:=$tmp}"
+  { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status
+' 0
+  trap 'as_fn_exit 1' 1 2 13 15
+}
+# Create a (secure) tmp directory for tmp files.
+
+{
+  tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
+  test -d "$tmp"
+}  ||
+{
+  tmp=./conf$$-$RANDOM
+  (umask 077 && mkdir "$tmp")
+} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5
+ac_tmp=$tmp
+
+# Set up the scripts for CONFIG_FILES section.
+# No need to generate them if there are no CONFIG_FILES.
+# This happens for instance with `./config.status config.h'.
+if test -n "$CONFIG_FILES"; then
+
+
+ac_cr=`echo X | tr X '\015'`
+# On cygwin, bash can eat \r inside `` if the user requested igncr.
+# But we know of no other shell where ac_cr would be empty at this
+# point, so we can use a bashism as a fallback.
+if test "x$ac_cr" = x; then
+  eval ac_cr=\$\'\\r\'
+fi
+ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' </dev/null 2>/dev/null`
+if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then
+  ac_cs_awk_cr='\\r'
+else
+  ac_cs_awk_cr=$ac_cr
+fi
+
+echo 'BEGIN {' >"$ac_tmp/subs1.awk" &&
+cat >>"$ac_tmp/subs1.awk" <<\_ACAWK &&
+S["LTLIBOBJS"]=""
+S["LIBOBJS"]=""
+S["subdirs"]=""
+S["JAVAH"]="/Library/Java/JavaVirtualMachines/labsjdk1.8.0_121-jvmci-0.29//bin/javah"
+S["JAVAC"]="/Library/Java/JavaVirtualMachines/labsjdk1.8.0_121-jvmci-0.29//bin/javac"
+S["JAVA"]="/Library/Java/JavaVirtualMachines/labsjdk1.8.0_121-jvmci-0.29//jre/bin/java"
+S["JAVA_HOME"]="/Library/Java/JavaVirtualMachines/jdk1.8.0_122.jdk/Contents/Home/"
+S["JAVA_CPPFLAGS"]="-I/Library/Java/JavaVirtualMachines/labsjdk1.8.0_121-jvmci-0.29//include -I/Library/Java/JavaVirtualMachines/labsjdk1.8.0_121-jvmci-0.29//include/da"\
+"rwin"
+S["JAVA_LIBS"]="-L/Library/Java/JavaVirtualMachines/labsjdk1.8.0_121-jvmci-0.29/jre/lib/server -ljvm"
+S["WANT_JRI_FALSE"]=""
+S["WANT_JRI_TRUE"]="#"
+S["EGREP"]="/usr/bin/grep -E"
+S["GREP"]="/usr/bin/grep"
+S["CPP"]="gcc -E"
+S["OBJEXT"]="o"
+S["EXEEXT"]=""
+S["ac_ct_CC"]="gcc"
+S["CPPFLAGS"]=""
+S["LDFLAGS"]=""
+S["CFLAGS"]="-g -O0 -Wall -pedantic -std=gnu99 -mtune=native -pipe -ggdb -I/Library/Java/JavaVirtualMachines/labsjdk1.8.0_121-jvmci-0.29//include -I/Library/Java"\
+"/JavaVirtualMachines/labsjdk1.8.0_121-jvmci-0.29//include/darwin"
+S["CC"]="gcc"
+S["R_HOME"]="/work/src/graalvm/fastr/com.oracle.truffle.r.native/gnur/R-3.4.0"
+S["target_alias"]=""
+S["host_alias"]=""
+S["build_alias"]=""
+S["LIBS"]=" -L/Library/Java/JavaVirtualMachines/labsjdk1.8.0_121-jvmci-0.29/jre/lib/server -ljvm"
+S["ECHO_T"]=""
+S["ECHO_N"]=""
+S["ECHO_C"]="\\c"
+S["DEFS"]="-DHAVE_CONFIG_H"
+S["mandir"]="${datarootdir}/man"
+S["localedir"]="${datarootdir}/locale"
+S["libdir"]="${exec_prefix}/lib"
+S["psdir"]="${docdir}"
+S["pdfdir"]="${docdir}"
+S["dvidir"]="${docdir}"
+S["htmldir"]="${docdir}"
+S["infodir"]="${datarootdir}/info"
+S["docdir"]="${datarootdir}/doc/${PACKAGE_TARNAME}"
+S["oldincludedir"]="/usr/include"
+S["includedir"]="${prefix}/include"
+S["localstatedir"]="${prefix}/var"
+S["sharedstatedir"]="${prefix}/com"
+S["sysconfdir"]="${prefix}/etc"
+S["datadir"]="${datarootdir}"
+S["datarootdir"]="${prefix}/share"
+S["libexecdir"]="${exec_prefix}/libexec"
+S["sbindir"]="${exec_prefix}/sbin"
+S["bindir"]="${exec_prefix}/bin"
+S["program_transform_name"]="s,x,x,"
+S["prefix"]="/usr/local"
+S["exec_prefix"]="${prefix}"
+S["PACKAGE_URL"]=""
+S["PACKAGE_BUGREPORT"]="Simon.Urbanek@r-project.org"
+S["PACKAGE_STRING"]="rJava 0.8"
+S["PACKAGE_VERSION"]="0.8"
+S["PACKAGE_TARNAME"]="rjava"
+S["PACKAGE_NAME"]="rJava"
+S["PATH_SEPARATOR"]=":"
+S["SHELL"]="/bin/sh"
+_ACAWK
+cat >>"$ac_tmp/subs1.awk" <<_ACAWK &&
+  for (key in S) S_is_set[key] = 1
+  FS = ""
+
+}
+{
+  line = $ 0
+  nfields = split(line, field, "@")
+  substed = 0
+  len = length(field[1])
+  for (i = 2; i < nfields; i++) {
+    key = field[i]
+    keylen = length(key)
+    if (S_is_set[key]) {
+      value = S[key]
+      line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3)
+      len += length(value) + length(field[++i])
+      substed = 1
+    } else
+      len += 1 + keylen
+  }
+
+  print line
+}
+
+_ACAWK
+if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then
+  sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g"
+else
+  cat
+fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \
+  || as_fn_error $? "could not setup config files machinery" "$LINENO" 5
+fi # test -n "$CONFIG_FILES"
+
+# Set up the scripts for CONFIG_HEADERS section.
+# No need to generate them if there are no CONFIG_HEADERS.
+# This happens for instance with `./config.status Makefile'.
+if test -n "$CONFIG_HEADERS"; then
+cat >"$ac_tmp/defines.awk" <<\_ACAWK ||
+BEGIN {
+D["PACKAGE_NAME"]=" \"rJava\""
+D["PACKAGE_TARNAME"]=" \"rjava\""
+D["PACKAGE_VERSION"]=" \"0.8\""
+D["PACKAGE_STRING"]=" \"rJava 0.8\""
+D["PACKAGE_BUGREPORT"]=" \"Simon.Urbanek@r-project.org\""
+D["PACKAGE_URL"]=" \"\""
+D["STDC_HEADERS"]=" 1"
+D["HAVE_SYS_WAIT_H"]=" 1"
+D["HAVE_SYS_TYPES_H"]=" 1"
+D["HAVE_SYS_STAT_H"]=" 1"
+D["HAVE_STDLIB_H"]=" 1"
+D["HAVE_STRING_H"]=" 1"
+D["HAVE_MEMORY_H"]=" 1"
+D["HAVE_STRINGS_H"]=" 1"
+D["HAVE_INTTYPES_H"]=" 1"
+D["HAVE_STDINT_H"]=" 1"
+D["HAVE_UNISTD_H"]=" 1"
+D["HAVE_STRING_H"]=" 1"
+D["HAVE_SYS_TIME_H"]=" 1"
+D["HAVE_UNISTD_H"]=" 1"
+D["TIME_WITH_SYS_TIME"]=" 1"
+D["HAVE_STATIC_INLINE"]=" 1"
+D["HAVE_DECL_SIGSETJMP"]=" 1"
+D["HAVE_DECL_SIGLONGJMP"]=" 1"
+D["HAVE_POSIX_SETJMP"]=" 1"
+D["USE_HEADLESS_INIT"]=" 1"
+  for (key in D) D_is_set[key] = 1
+  FS = ""
+}
+/^[\t ]*#[\t ]*(define|undef)[\t ]+[_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ][_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]*([\t (]|$)/ {
+  line = $ 0
+  split(line, arg, " ")
+  if (arg[1] == "#") {
+    defundef = arg[2]
+    mac1 = arg[3]
+  } else {
+    defundef = substr(arg[1], 2)
+    mac1 = arg[2]
+  }
+  split(mac1, mac2, "(") #)
+  macro = mac2[1]
+  prefix = substr(line, 1, index(line, defundef) - 1)
+  if (D_is_set[macro]) {
+    # Preserve the white space surrounding the "#".
+    print prefix "define", macro P[macro] D[macro]
+    next
+  } else {
+    # Replace #undef with comments.  This is necessary, for example,
+    # in the case of _POSIX_SOURCE, which is predefined and required
+    # on some systems where configure will not decide to define it.
+    if (defundef == "undef") {
+      print "/*", prefix defundef, macro, "*/"
+      next
+    }
+  }
+}
+{ print }
+_ACAWK
+  as_fn_error $? "could not setup config headers machinery" "$LINENO" 5
+fi # test -n "$CONFIG_HEADERS"
+
+
+eval set X "  :F $CONFIG_FILES  :H $CONFIG_HEADERS    "
+shift
+for ac_tag
+do
+  case $ac_tag in
+  :[FHLC]) ac_mode=$ac_tag; continue;;
+  esac
+  case $ac_mode$ac_tag in
+  :[FHL]*:*);;
+  :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;;
+  :[FH]-) ac_tag=-:-;;
+  :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
+  esac
+  ac_save_IFS=$IFS
+  IFS=:
+  set x $ac_tag
+  IFS=$ac_save_IFS
+  shift
+  ac_file=$1
+  shift
+
+  case $ac_mode in
+  :L) ac_source=$1;;
+  :[FH])
+    ac_file_inputs=
+    for ac_f
+    do
+      case $ac_f in
+      -) ac_f="$ac_tmp/stdin";;
+      *) # Look for the file first in the build tree, then in the source tree
+	 # (if the path is not absolute).  The absolute path cannot be DOS-style,
+	 # because $ac_f cannot contain `:'.
+	 test -f "$ac_f" ||
+	   case $ac_f in
+	   [\\/$]*) false;;
+	   *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
+	   esac ||
+	   as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;;
+      esac
+      case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac
+      as_fn_append ac_file_inputs " '$ac_f'"
+    done
+
+    # Let's still pretend it is `configure' which instantiates (i.e., don't
+    # use $as_me), people would be surprised to read:
+    #    /* config.h.  Generated by config.status.  */
+    configure_input='Generated from '`
+	  $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g'
+	`' by configure.'
+    if test x"$ac_file" != x-; then
+      configure_input="$ac_file.  $configure_input"
+      { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5
+$as_echo "$as_me: creating $ac_file" >&6;}
+    fi
+    # Neutralize special characters interpreted by sed in replacement strings.
+    case $configure_input in #(
+    *\&* | *\|* | *\\* )
+       ac_sed_conf_input=`$as_echo "$configure_input" |
+       sed 's/[\\\\&|]/\\\\&/g'`;; #(
+    *) ac_sed_conf_input=$configure_input;;
+    esac
+
+    case $ac_tag in
+    *:-:* | *:-) cat >"$ac_tmp/stdin" \
+      || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;;
+    esac
+    ;;
+  esac
+
+  ac_dir=`$as_dirname -- "$ac_file" ||
+$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$ac_file" : 'X\(//\)[^/]' \| \
+	 X"$ac_file" : 'X\(//\)$' \| \
+	 X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$ac_file" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+  as_dir="$ac_dir"; as_fn_mkdir_p
+  ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+
+  case $ac_mode in
+  :F)
+  #
+  # CONFIG_FILE
+  #
+
+# If the template does not know about datarootdir, expand it.
+# FIXME: This hack should be removed a few years after 2.60.
+ac_datarootdir_hack=; ac_datarootdir_seen=
+ac_sed_dataroot='
+/datarootdir/ {
+  p
+  q
+}
+/@datadir@/p
+/@docdir@/p
+/@infodir@/p
+/@localedir@/p
+/@mandir@/p'
+case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in
+*datarootdir*) ac_datarootdir_seen=yes;;
+*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
+$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
+  ac_datarootdir_hack='
+  s&@datadir@&${datarootdir}&g
+  s&@docdir@&${datarootdir}/doc/${PACKAGE_TARNAME}&g
+  s&@infodir@&${datarootdir}/info&g
+  s&@localedir@&${datarootdir}/locale&g
+  s&@mandir@&${datarootdir}/man&g
+  s&\${datarootdir}&${prefix}/share&g' ;;
+esac
+ac_sed_extra="/^[	 ]*VPATH[	 ]*=[	 ]*/{
+h
+s///
+s/^/:/
+s/[	 ]*$/:/
+s/:\$(srcdir):/:/g
+s/:\${srcdir}:/:/g
+s/:@srcdir@:/:/g
+s/^:*//
+s/:*$//
+x
+s/\(=[	 ]*\).*/\1/
+G
+s/\n//
+s/^[^=]*=[	 ]*$//
+}
+
+:t
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
+s|@configure_input@|$ac_sed_conf_input|;t t
+s&@top_builddir@&$ac_top_builddir_sub&;t t
+s&@top_build_prefix@&$ac_top_build_prefix&;t t
+s&@srcdir@&$ac_srcdir&;t t
+s&@abs_srcdir@&$ac_abs_srcdir&;t t
+s&@top_srcdir@&$ac_top_srcdir&;t t
+s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
+s&@builddir@&$ac_builddir&;t t
+s&@abs_builddir@&$ac_abs_builddir&;t t
+s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
+$ac_datarootdir_hack
+"
+eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \
+  >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5
+
+test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
+  { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } &&
+  { ac_out=`sed -n '/^[	 ]*datarootdir[	 ]*:*=/p' \
+      "$ac_tmp/out"`; test -z "$ac_out"; } &&
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined" >&5
+$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined" >&2;}
+
+  rm -f "$ac_tmp/stdin"
+  case $ac_file in
+  -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";;
+  *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";;
+  esac \
+  || as_fn_error $? "could not create $ac_file" "$LINENO" 5
+ ;;
+  :H)
+  #
+  # CONFIG_HEADER
+  #
+  if test x"$ac_file" != x-; then
+    {
+      $as_echo "/* $configure_input  */" \
+      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs"
+    } >"$ac_tmp/config.h" \
+      || as_fn_error $? "could not create $ac_file" "$LINENO" 5
+    if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5
+$as_echo "$as_me: $ac_file is unchanged" >&6;}
+    else
+      rm -f "$ac_file"
+      mv "$ac_tmp/config.h" "$ac_file" \
+	|| as_fn_error $? "could not create $ac_file" "$LINENO" 5
+    fi
+  else
+    $as_echo "/* $configure_input  */" \
+      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \
+      || as_fn_error $? "could not create -" "$LINENO" 5
+  fi
+ ;;
+
+
+  esac
+
+done # for ac_tag
+
+
+as_fn_exit 0
diff --git a/com.oracle.truffle.r.pkgs/rJava/configure b/com.oracle.truffle.r.pkgs/rJava/configure
new file mode 100755
index 0000000000000000000000000000000000000000..b3b95f136ef2a6b360e9b369f66030b4a916bd83
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/configure
@@ -0,0 +1,5426 @@
+#! /bin/sh
+# Guess values for system-dependent variables and create Makefiles.
+# Generated by GNU Autoconf 2.69 for rJava 0.8.
+#
+# Report bugs to <Simon.Urbanek@r-project.org>.
+#
+#
+# Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
+#
+#
+# This configure script is free software; the Free Software Foundation
+# gives unlimited permission to copy, distribute and modify it.
+## -------------------- ##
+## M4sh Initialization. ##
+## -------------------- ##
+
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
+  emulate sh
+  NULLCMD=:
+  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in #(
+  *posix*) :
+    set -o posix ;; #(
+  *) :
+     ;;
+esac
+fi
+
+
+as_nl='
+'
+export as_nl
+# Printing a long string crashes Solaris 7 /usr/bin/printf.
+as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
+# Prefer a ksh shell builtin over an external printf program on Solaris,
+# but without wasting forks for bash or zsh.
+if test -z "$BASH_VERSION$ZSH_VERSION" \
+    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='print -r --'
+  as_echo_n='print -rn --'
+elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='printf %s\n'
+  as_echo_n='printf %s'
+else
+  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
+    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
+    as_echo_n='/usr/ucb/echo -n'
+  else
+    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
+    as_echo_n_body='eval
+      arg=$1;
+      case $arg in #(
+      *"$as_nl"*)
+	expr "X$arg" : "X\\(.*\\)$as_nl";
+	arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
+      esac;
+      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
+    '
+    export as_echo_n_body
+    as_echo_n='sh -c $as_echo_n_body as_echo'
+  fi
+  export as_echo_body
+  as_echo='sh -c $as_echo_body as_echo'
+fi
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  PATH_SEPARATOR=:
+  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
+    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
+      PATH_SEPARATOR=';'
+  }
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+IFS=" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+as_myself=
+case $0 in #((
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+  done
+IFS=$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  exit 1
+fi
+
+# Unset variables that we do not need and which cause bugs (e.g. in
+# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
+# suppresses any "Segmentation fault" message there.  '((' could
+# trigger a bug in pdksh 5.2.14.
+for as_var in BASH_ENV ENV MAIL MAILPATH
+do eval test x\${$as_var+set} = xset \
+  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+LC_ALL=C
+export LC_ALL
+LANGUAGE=C
+export LANGUAGE
+
+# CDPATH.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+# Use a proper internal environment variable to ensure we don't fall
+  # into an infinite loop, continuously re-executing ourselves.
+  if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then
+    _as_can_reexec=no; export _as_can_reexec;
+    # We cannot yet assume a decent shell, so we have to provide a
+# neutralization value for shells without unset; and this also
+# works around shells that cannot unset nonexistent variables.
+# Preserve -v and -x to the replacement shell.
+BASH_ENV=/dev/null
+ENV=/dev/null
+(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
+case $- in # ((((
+  *v*x* | *x*v* ) as_opts=-vx ;;
+  *v* ) as_opts=-v ;;
+  *x* ) as_opts=-x ;;
+  * ) as_opts= ;;
+esac
+exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
+# Admittedly, this is quite paranoid, since all the known shells bail
+# out after a failed `exec'.
+$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
+as_fn_exit 255
+  fi
+  # We don't want this to propagate to other subprocesses.
+          { _as_can_reexec=; unset _as_can_reexec;}
+if test "x$CONFIG_SHELL" = x; then
+  as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :
+  emulate sh
+  NULLCMD=:
+  # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '\${1+\"\$@\"}'='\"\$@\"'
+  setopt NO_GLOB_SUBST
+else
+  case \`(set -o) 2>/dev/null\` in #(
+  *posix*) :
+    set -o posix ;; #(
+  *) :
+     ;;
+esac
+fi
+"
+  as_required="as_fn_return () { (exit \$1); }
+as_fn_success () { as_fn_return 0; }
+as_fn_failure () { as_fn_return 1; }
+as_fn_ret_success () { return 0; }
+as_fn_ret_failure () { return 1; }
+
+exitcode=0
+as_fn_success || { exitcode=1; echo as_fn_success failed.; }
+as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; }
+as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; }
+as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; }
+if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then :
+
+else
+  exitcode=1; echo positional parameters were not saved.
+fi
+test x\$exitcode = x0 || exit 1
+test -x / || exit 1"
+  as_suggested="  as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO
+  as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO
+  eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" &&
+  test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1
+test \$(( 1 + 1 )) = 2 || exit 1"
+  if (eval "$as_required") 2>/dev/null; then :
+  as_have_required=yes
+else
+  as_have_required=no
+fi
+  if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then :
+
+else
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+as_found=false
+for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  as_found=:
+  case $as_dir in #(
+	 /*)
+	   for as_base in sh bash ksh sh5; do
+	     # Try only shells that exist, to save several forks.
+	     as_shell=$as_dir/$as_base
+	     if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
+		    { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then :
+  CONFIG_SHELL=$as_shell as_have_required=yes
+		   if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then :
+  break 2
+fi
+fi
+	   done;;
+       esac
+  as_found=false
+done
+$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } &&
+	      { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then :
+  CONFIG_SHELL=$SHELL as_have_required=yes
+fi; }
+IFS=$as_save_IFS
+
+
+      if test "x$CONFIG_SHELL" != x; then :
+  export CONFIG_SHELL
+             # We cannot yet assume a decent shell, so we have to provide a
+# neutralization value for shells without unset; and this also
+# works around shells that cannot unset nonexistent variables.
+# Preserve -v and -x to the replacement shell.
+BASH_ENV=/dev/null
+ENV=/dev/null
+(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
+case $- in # ((((
+  *v*x* | *x*v* ) as_opts=-vx ;;
+  *v* ) as_opts=-v ;;
+  *x* ) as_opts=-x ;;
+  * ) as_opts= ;;
+esac
+exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
+# Admittedly, this is quite paranoid, since all the known shells bail
+# out after a failed `exec'.
+$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
+exit 255
+fi
+
+    if test x$as_have_required = xno; then :
+  $as_echo "$0: This script requires a shell more modern than all"
+  $as_echo "$0: the shells that I found on your system."
+  if test x${ZSH_VERSION+set} = xset ; then
+    $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should"
+    $as_echo "$0: be upgraded to zsh 4.3.4 or later."
+  else
+    $as_echo "$0: Please tell bug-autoconf@gnu.org and
+$0: Simon.Urbanek@r-project.org about your system,
+$0: including any error possibly output before this
+$0: message. Then install a modern shell, or manually run
+$0: the script under such a shell if you do have one."
+  fi
+  exit 1
+fi
+fi
+fi
+SHELL=${CONFIG_SHELL-/bin/sh}
+export SHELL
+# Unset more variables known to interfere with behavior of common tools.
+CLICOLOR_FORCE= GREP_OPTIONS=
+unset CLICOLOR_FORCE GREP_OPTIONS
+
+## --------------------- ##
+## M4sh Shell Functions. ##
+## --------------------- ##
+# as_fn_unset VAR
+# ---------------
+# Portably unset VAR.
+as_fn_unset ()
+{
+  { eval $1=; unset $1;}
+}
+as_unset=as_fn_unset
+
+# as_fn_set_status STATUS
+# -----------------------
+# Set $? to STATUS, without forking.
+as_fn_set_status ()
+{
+  return $1
+} # as_fn_set_status
+
+# as_fn_exit STATUS
+# -----------------
+# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
+as_fn_exit ()
+{
+  set +e
+  as_fn_set_status $1
+  exit $1
+} # as_fn_exit
+
+# as_fn_mkdir_p
+# -------------
+# Create "$as_dir" as a directory, including parents if necessary.
+as_fn_mkdir_p ()
+{
+
+  case $as_dir in #(
+  -*) as_dir=./$as_dir;;
+  esac
+  test -d "$as_dir" || eval $as_mkdir_p || {
+    as_dirs=
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
+      *) as_qdir=$as_dir;;
+      esac
+      as_dirs="'$as_qdir' $as_dirs"
+      as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_dir" : 'X\(//\)[^/]' \| \
+	 X"$as_dir" : 'X\(//\)$' \| \
+	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_dir" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+      test -d "$as_dir" && break
+    done
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
+
+
+} # as_fn_mkdir_p
+
+# as_fn_executable_p FILE
+# -----------------------
+# Test if FILE is an executable regular file.
+as_fn_executable_p ()
+{
+  test -f "$1" && test -x "$1"
+} # as_fn_executable_p
+# as_fn_append VAR VALUE
+# ----------------------
+# Append the text in VALUE to the end of the definition contained in VAR. Take
+# advantage of any shell optimizations that allow amortized linear growth over
+# repeated appends, instead of the typical quadratic growth present in naive
+# implementations.
+if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
+  eval 'as_fn_append ()
+  {
+    eval $1+=\$2
+  }'
+else
+  as_fn_append ()
+  {
+    eval $1=\$$1\$2
+  }
+fi # as_fn_append
+
+# as_fn_arith ARG...
+# ------------------
+# Perform arithmetic evaluation on the ARGs, and store the result in the
+# global $as_val. Take advantage of shells that can avoid forks. The arguments
+# must be portable across $(()) and expr.
+if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
+  eval 'as_fn_arith ()
+  {
+    as_val=$(( $* ))
+  }'
+else
+  as_fn_arith ()
+  {
+    as_val=`expr "$@" || test $? -eq 1`
+  }
+fi # as_fn_arith
+
+
+# as_fn_error STATUS ERROR [LINENO LOG_FD]
+# ----------------------------------------
+# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
+# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
+# script with STATUS, using 1 if that was 0.
+as_fn_error ()
+{
+  as_status=$1; test $as_status -eq 0 && as_status=1
+  if test "$4"; then
+    as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
+  fi
+  $as_echo "$as_me: error: $2" >&2
+  as_fn_exit $as_status
+} # as_fn_error
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+  as_basename=basename
+else
+  as_basename=false
+fi
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
+
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+
+  as_lineno_1=$LINENO as_lineno_1a=$LINENO
+  as_lineno_2=$LINENO as_lineno_2a=$LINENO
+  eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" &&
+  test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || {
+  # Blame Lee E. McMahon (1931-1989) for sed's syntax.  :-)
+  sed -n '
+    p
+    /[$]LINENO/=
+  ' <$as_myself |
+    sed '
+      s/[$]LINENO.*/&-/
+      t lineno
+      b
+      :lineno
+      N
+      :loop
+      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
+      t loop
+      s/-\n.*//
+    ' >$as_me.lineno &&
+  chmod +x "$as_me.lineno" ||
+    { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; }
+
+  # If we had to re-execute with $CONFIG_SHELL, we're ensured to have
+  # already done that, so ensure we don't try to do so again and fall
+  # in an infinite loop.  This has already happened in practice.
+  _as_can_reexec=no; export _as_can_reexec
+  # Don't try to exec as it changes $[0], causing all sort of problems
+  # (the dirname of $[0] is not the place where we might find the
+  # original and so on.  Autoconf is especially sensitive to this).
+  . "./$as_me.lineno"
+  # Exit status is that of the last command.
+  exit
+}
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in #(((((
+-n*)
+  case `echo 'xy\c'` in
+  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
+  xy)  ECHO_C='\c';;
+  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
+       ECHO_T='	';;
+  esac;;
+*)
+  ECHO_N='-n';;
+esac
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir 2>/dev/null
+fi
+if (echo >conf$$.file) 2>/dev/null; then
+  if ln -s conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s='ln -s'
+    # ... but there are two gotchas:
+    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+    # In both cases, we have to default to `cp -pR'.
+    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+      as_ln_s='cp -pR'
+  elif ln conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s=ln
+  else
+    as_ln_s='cp -pR'
+  fi
+else
+  as_ln_s='cp -pR'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+if mkdir -p . 2>/dev/null; then
+  as_mkdir_p='mkdir -p "$as_dir"'
+else
+  test -d ./-p && rmdir ./-p
+  as_mkdir_p=false
+fi
+
+as_test_x='test -x'
+as_executable_p=as_fn_executable_p
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+test -n "$DJDIR" || exec 7<&0 </dev/null
+exec 6>&1
+
+# Name of the host.
+# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status,
+# so uname gets run too.
+ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`
+
+#
+# Initializations.
+#
+ac_default_prefix=/usr/local
+ac_clean_files=
+ac_config_libobj_dir=.
+LIBOBJS=
+cross_compiling=no
+subdirs=
+MFLAGS=
+MAKEFLAGS=
+
+# Identity of this package.
+PACKAGE_NAME='rJava'
+PACKAGE_TARNAME='rjava'
+PACKAGE_VERSION='0.8'
+PACKAGE_STRING='rJava 0.8'
+PACKAGE_BUGREPORT='Simon.Urbanek@r-project.org'
+PACKAGE_URL=''
+
+ac_unique_file="src/rJava.c"
+# Factoring default headers for most tests.
+ac_includes_default="\
+#include <stdio.h>
+#ifdef HAVE_SYS_TYPES_H
+# include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_STAT_H
+# include <sys/stat.h>
+#endif
+#ifdef STDC_HEADERS
+# include <stdlib.h>
+# include <stddef.h>
+#else
+# ifdef HAVE_STDLIB_H
+#  include <stdlib.h>
+# endif
+#endif
+#ifdef HAVE_STRING_H
+# if !defined STDC_HEADERS && defined HAVE_MEMORY_H
+#  include <memory.h>
+# endif
+# include <string.h>
+#endif
+#ifdef HAVE_STRINGS_H
+# include <strings.h>
+#endif
+#ifdef HAVE_INTTYPES_H
+# include <inttypes.h>
+#endif
+#ifdef HAVE_STDINT_H
+# include <stdint.h>
+#endif
+#ifdef HAVE_UNISTD_H
+# include <unistd.h>
+#endif"
+
+enable_option_checking=no
+ac_subst_vars='LTLIBOBJS
+LIBOBJS
+subdirs
+JAVAH
+JAVAC
+JAVA
+JAVA_HOME
+JAVA_CPPFLAGS
+JAVA_LIBS
+WANT_JRI_FALSE
+WANT_JRI_TRUE
+EGREP
+GREP
+CPP
+OBJEXT
+EXEEXT
+ac_ct_CC
+CPPFLAGS
+LDFLAGS
+CFLAGS
+CC
+R_HOME
+target_alias
+host_alias
+build_alias
+LIBS
+ECHO_T
+ECHO_N
+ECHO_C
+DEFS
+mandir
+localedir
+libdir
+psdir
+pdfdir
+dvidir
+htmldir
+infodir
+docdir
+oldincludedir
+includedir
+localstatedir
+sharedstatedir
+sysconfdir
+datadir
+datarootdir
+libexecdir
+sbindir
+bindir
+program_transform_name
+prefix
+exec_prefix
+PACKAGE_URL
+PACKAGE_BUGREPORT
+PACKAGE_STRING
+PACKAGE_VERSION
+PACKAGE_TARNAME
+PACKAGE_NAME
+PATH_SEPARATOR
+SHELL'
+ac_subst_files=''
+ac_user_opts='
+enable_option_checking
+enable_threads
+enable_jni_cache
+enable_jri
+enable_headless
+enable_Xrs
+enable_debug
+enable_mem_profile
+enable_callbacks
+'
+      ac_precious_vars='build_alias
+host_alias
+target_alias
+CC
+CFLAGS
+LDFLAGS
+LIBS
+CPPFLAGS
+CPP'
+ac_subdirs_all='jri'
+
+# Initialize some variables set by options.
+ac_init_help=
+ac_init_version=false
+ac_unrecognized_opts=
+ac_unrecognized_sep=
+# The variables have the same names as the options, with
+# dashes changed to underlines.
+cache_file=/dev/null
+exec_prefix=NONE
+no_create=
+no_recursion=
+prefix=NONE
+program_prefix=NONE
+program_suffix=NONE
+program_transform_name=s,x,x,
+silent=
+site=
+srcdir=
+verbose=
+x_includes=NONE
+x_libraries=NONE
+
+# Installation directory options.
+# These are left unexpanded so users can "make install exec_prefix=/foo"
+# and all the variables that are supposed to be based on exec_prefix
+# by default will actually change.
+# Use braces instead of parens because sh, perl, etc. also accept them.
+# (The list follows the same order as the GNU Coding Standards.)
+bindir='${exec_prefix}/bin'
+sbindir='${exec_prefix}/sbin'
+libexecdir='${exec_prefix}/libexec'
+datarootdir='${prefix}/share'
+datadir='${datarootdir}'
+sysconfdir='${prefix}/etc'
+sharedstatedir='${prefix}/com'
+localstatedir='${prefix}/var'
+includedir='${prefix}/include'
+oldincludedir='/usr/include'
+docdir='${datarootdir}/doc/${PACKAGE_TARNAME}'
+infodir='${datarootdir}/info'
+htmldir='${docdir}'
+dvidir='${docdir}'
+pdfdir='${docdir}'
+psdir='${docdir}'
+libdir='${exec_prefix}/lib'
+localedir='${datarootdir}/locale'
+mandir='${datarootdir}/man'
+
+ac_prev=
+ac_dashdash=
+for ac_option
+do
+  # If the previous option needs an argument, assign it.
+  if test -n "$ac_prev"; then
+    eval $ac_prev=\$ac_option
+    ac_prev=
+    continue
+  fi
+
+  case $ac_option in
+  *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;;
+  *=)   ac_optarg= ;;
+  *)    ac_optarg=yes ;;
+  esac
+
+  # Accept the important Cygnus configure options, so we can diagnose typos.
+
+  case $ac_dashdash$ac_option in
+  --)
+    ac_dashdash=yes ;;
+
+  -bindir | --bindir | --bindi | --bind | --bin | --bi)
+    ac_prev=bindir ;;
+  -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
+    bindir=$ac_optarg ;;
+
+  -build | --build | --buil | --bui | --bu)
+    ac_prev=build_alias ;;
+  -build=* | --build=* | --buil=* | --bui=* | --bu=*)
+    build_alias=$ac_optarg ;;
+
+  -cache-file | --cache-file | --cache-fil | --cache-fi \
+  | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
+    ac_prev=cache_file ;;
+  -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
+  | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
+    cache_file=$ac_optarg ;;
+
+  --config-cache | -C)
+    cache_file=config.cache ;;
+
+  -datadir | --datadir | --datadi | --datad)
+    ac_prev=datadir ;;
+  -datadir=* | --datadir=* | --datadi=* | --datad=*)
+    datadir=$ac_optarg ;;
+
+  -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \
+  | --dataroo | --dataro | --datar)
+    ac_prev=datarootdir ;;
+  -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \
+  | --dataroot=* | --dataroo=* | --dataro=* | --datar=*)
+    datarootdir=$ac_optarg ;;
+
+  -disable-* | --disable-*)
+    ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error $? "invalid feature name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"enable_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval enable_$ac_useropt=no ;;
+
+  -docdir | --docdir | --docdi | --doc | --do)
+    ac_prev=docdir ;;
+  -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*)
+    docdir=$ac_optarg ;;
+
+  -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv)
+    ac_prev=dvidir ;;
+  -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*)
+    dvidir=$ac_optarg ;;
+
+  -enable-* | --enable-*)
+    ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error $? "invalid feature name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"enable_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval enable_$ac_useropt=\$ac_optarg ;;
+
+  -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
+  | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
+  | --exec | --exe | --ex)
+    ac_prev=exec_prefix ;;
+  -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
+  | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
+  | --exec=* | --exe=* | --ex=*)
+    exec_prefix=$ac_optarg ;;
+
+  -gas | --gas | --ga | --g)
+    # Obsolete; use --with-gas.
+    with_gas=yes ;;
+
+  -help | --help | --hel | --he | -h)
+    ac_init_help=long ;;
+  -help=r* | --help=r* | --hel=r* | --he=r* | -hr*)
+    ac_init_help=recursive ;;
+  -help=s* | --help=s* | --hel=s* | --he=s* | -hs*)
+    ac_init_help=short ;;
+
+  -host | --host | --hos | --ho)
+    ac_prev=host_alias ;;
+  -host=* | --host=* | --hos=* | --ho=*)
+    host_alias=$ac_optarg ;;
+
+  -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht)
+    ac_prev=htmldir ;;
+  -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \
+  | --ht=*)
+    htmldir=$ac_optarg ;;
+
+  -includedir | --includedir | --includedi | --included | --include \
+  | --includ | --inclu | --incl | --inc)
+    ac_prev=includedir ;;
+  -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \
+  | --includ=* | --inclu=* | --incl=* | --inc=*)
+    includedir=$ac_optarg ;;
+
+  -infodir | --infodir | --infodi | --infod | --info | --inf)
+    ac_prev=infodir ;;
+  -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
+    infodir=$ac_optarg ;;
+
+  -libdir | --libdir | --libdi | --libd)
+    ac_prev=libdir ;;
+  -libdir=* | --libdir=* | --libdi=* | --libd=*)
+    libdir=$ac_optarg ;;
+
+  -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \
+  | --libexe | --libex | --libe)
+    ac_prev=libexecdir ;;
+  -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \
+  | --libexe=* | --libex=* | --libe=*)
+    libexecdir=$ac_optarg ;;
+
+  -localedir | --localedir | --localedi | --localed | --locale)
+    ac_prev=localedir ;;
+  -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*)
+    localedir=$ac_optarg ;;
+
+  -localstatedir | --localstatedir | --localstatedi | --localstated \
+  | --localstate | --localstat | --localsta | --localst | --locals)
+    ac_prev=localstatedir ;;
+  -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
+  | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*)
+    localstatedir=$ac_optarg ;;
+
+  -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
+    ac_prev=mandir ;;
+  -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
+    mandir=$ac_optarg ;;
+
+  -nfp | --nfp | --nf)
+    # Obsolete; use --without-fp.
+    with_fp=no ;;
+
+  -no-create | --no-create | --no-creat | --no-crea | --no-cre \
+  | --no-cr | --no-c | -n)
+    no_create=yes ;;
+
+  -no-recursion | --no-recursion | --no-recursio | --no-recursi \
+  | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)
+    no_recursion=yes ;;
+
+  -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \
+  | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \
+  | --oldin | --oldi | --old | --ol | --o)
+    ac_prev=oldincludedir ;;
+  -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
+  | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
+  | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
+    oldincludedir=$ac_optarg ;;
+
+  -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
+    ac_prev=prefix ;;
+  -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
+    prefix=$ac_optarg ;;
+
+  -program-prefix | --program-prefix | --program-prefi | --program-pref \
+  | --program-pre | --program-pr | --program-p)
+    ac_prev=program_prefix ;;
+  -program-prefix=* | --program-prefix=* | --program-prefi=* \
+  | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)
+    program_prefix=$ac_optarg ;;
+
+  -program-suffix | --program-suffix | --program-suffi | --program-suff \
+  | --program-suf | --program-su | --program-s)
+    ac_prev=program_suffix ;;
+  -program-suffix=* | --program-suffix=* | --program-suffi=* \
+  | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)
+    program_suffix=$ac_optarg ;;
+
+  -program-transform-name | --program-transform-name \
+  | --program-transform-nam | --program-transform-na \
+  | --program-transform-n | --program-transform- \
+  | --program-transform | --program-transfor \
+  | --program-transfo | --program-transf \
+  | --program-trans | --program-tran \
+  | --progr-tra | --program-tr | --program-t)
+    ac_prev=program_transform_name ;;
+  -program-transform-name=* | --program-transform-name=* \
+  | --program-transform-nam=* | --program-transform-na=* \
+  | --program-transform-n=* | --program-transform-=* \
+  | --program-transform=* | --program-transfor=* \
+  | --program-transfo=* | --program-transf=* \
+  | --program-trans=* | --program-tran=* \
+  | --progr-tra=* | --program-tr=* | --program-t=*)
+    program_transform_name=$ac_optarg ;;
+
+  -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd)
+    ac_prev=pdfdir ;;
+  -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*)
+    pdfdir=$ac_optarg ;;
+
+  -psdir | --psdir | --psdi | --psd | --ps)
+    ac_prev=psdir ;;
+  -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*)
+    psdir=$ac_optarg ;;
+
+  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+  | -silent | --silent | --silen | --sile | --sil)
+    silent=yes ;;
+
+  -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
+    ac_prev=sbindir ;;
+  -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
+  | --sbi=* | --sb=*)
+    sbindir=$ac_optarg ;;
+
+  -sharedstatedir | --sharedstatedir | --sharedstatedi \
+  | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
+  | --sharedst | --shareds | --shared | --share | --shar \
+  | --sha | --sh)
+    ac_prev=sharedstatedir ;;
+  -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \
+  | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
+  | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
+  | --sha=* | --sh=*)
+    sharedstatedir=$ac_optarg ;;
+
+  -site | --site | --sit)
+    ac_prev=site ;;
+  -site=* | --site=* | --sit=*)
+    site=$ac_optarg ;;
+
+  -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
+    ac_prev=srcdir ;;
+  -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
+    srcdir=$ac_optarg ;;
+
+  -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \
+  | --syscon | --sysco | --sysc | --sys | --sy)
+    ac_prev=sysconfdir ;;
+  -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \
+  | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)
+    sysconfdir=$ac_optarg ;;
+
+  -target | --target | --targe | --targ | --tar | --ta | --t)
+    ac_prev=target_alias ;;
+  -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
+    target_alias=$ac_optarg ;;
+
+  -v | -verbose | --verbose | --verbos | --verbo | --verb)
+    verbose=yes ;;
+
+  -version | --version | --versio | --versi | --vers | -V)
+    ac_init_version=: ;;
+
+  -with-* | --with-*)
+    ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error $? "invalid package name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"with_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval with_$ac_useropt=\$ac_optarg ;;
+
+  -without-* | --without-*)
+    ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error $? "invalid package name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"with_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval with_$ac_useropt=no ;;
+
+  --x)
+    # Obsolete; use --with-x.
+    with_x=yes ;;
+
+  -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \
+  | --x-incl | --x-inc | --x-in | --x-i)
+    ac_prev=x_includes ;;
+  -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \
+  | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)
+    x_includes=$ac_optarg ;;
+
+  -x-libraries | --x-libraries | --x-librarie | --x-librari \
+  | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)
+    ac_prev=x_libraries ;;
+  -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \
+  | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
+    x_libraries=$ac_optarg ;;
+
+  -*) as_fn_error $? "unrecognized option: \`$ac_option'
+Try \`$0 --help' for more information"
+    ;;
+
+  *=*)
+    ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='`
+    # Reject names that are not valid shell variable names.
+    case $ac_envvar in #(
+      '' | [0-9]* | *[!_$as_cr_alnum]* )
+      as_fn_error $? "invalid variable name: \`$ac_envvar'" ;;
+    esac
+    eval $ac_envvar=\$ac_optarg
+    export $ac_envvar ;;
+
+  *)
+    # FIXME: should be removed in autoconf 3.0.
+    $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2
+    expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2
+    : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}"
+    ;;
+
+  esac
+done
+
+if test -n "$ac_prev"; then
+  ac_option=--`echo $ac_prev | sed 's/_/-/g'`
+  as_fn_error $? "missing argument to $ac_option"
+fi
+
+if test -n "$ac_unrecognized_opts"; then
+  case $enable_option_checking in
+    no) ;;
+    fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;;
+    *)     $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;;
+  esac
+fi
+
+# Check all directory arguments for consistency.
+for ac_var in	exec_prefix prefix bindir sbindir libexecdir datarootdir \
+		datadir sysconfdir sharedstatedir localstatedir includedir \
+		oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
+		libdir localedir mandir
+do
+  eval ac_val=\$$ac_var
+  # Remove trailing slashes.
+  case $ac_val in
+    */ )
+      ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'`
+      eval $ac_var=\$ac_val;;
+  esac
+  # Be sure to have absolute directory names.
+  case $ac_val in
+    [\\/$]* | ?:[\\/]* )  continue;;
+    NONE | '' ) case $ac_var in *prefix ) continue;; esac;;
+  esac
+  as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val"
+done
+
+# There might be people who depend on the old broken behavior: `$host'
+# used to hold the argument of --host etc.
+# FIXME: To remove some day.
+build=$build_alias
+host=$host_alias
+target=$target_alias
+
+# FIXME: To remove some day.
+if test "x$host_alias" != x; then
+  if test "x$build_alias" = x; then
+    cross_compiling=maybe
+  elif test "x$build_alias" != "x$host_alias"; then
+    cross_compiling=yes
+  fi
+fi
+
+ac_tool_prefix=
+test -n "$host_alias" && ac_tool_prefix=$host_alias-
+
+test "$silent" = yes && exec 6>/dev/null
+
+
+ac_pwd=`pwd` && test -n "$ac_pwd" &&
+ac_ls_di=`ls -di .` &&
+ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` ||
+  as_fn_error $? "working directory cannot be determined"
+test "X$ac_ls_di" = "X$ac_pwd_ls_di" ||
+  as_fn_error $? "pwd does not report name of working directory"
+
+
+# Find the source files, if location was not specified.
+if test -z "$srcdir"; then
+  ac_srcdir_defaulted=yes
+  # Try the directory containing this script, then the parent directory.
+  ac_confdir=`$as_dirname -- "$as_myself" ||
+$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_myself" : 'X\(//\)[^/]' \| \
+	 X"$as_myself" : 'X\(//\)$' \| \
+	 X"$as_myself" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_myself" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+  srcdir=$ac_confdir
+  if test ! -r "$srcdir/$ac_unique_file"; then
+    srcdir=..
+  fi
+else
+  ac_srcdir_defaulted=no
+fi
+if test ! -r "$srcdir/$ac_unique_file"; then
+  test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .."
+  as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir"
+fi
+ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work"
+ac_abs_confdir=`(
+	cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg"
+	pwd)`
+# When building in place, set srcdir=.
+if test "$ac_abs_confdir" = "$ac_pwd"; then
+  srcdir=.
+fi
+# Remove unnecessary trailing slashes from srcdir.
+# Double slashes in file names in object file debugging info
+# mess up M-x gdb in Emacs.
+case $srcdir in
+*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;;
+esac
+for ac_var in $ac_precious_vars; do
+  eval ac_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_env_${ac_var}_value=\$${ac_var}
+  eval ac_cv_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_cv_env_${ac_var}_value=\$${ac_var}
+done
+
+#
+# Report the --help message.
+#
+if test "$ac_init_help" = "long"; then
+  # Omit some internal or obsolete options to make the list less imposing.
+  # This message is too long to be a string in the A/UX 3.1 sh.
+  cat <<_ACEOF
+\`configure' configures rJava 0.8 to adapt to many kinds of systems.
+
+Usage: $0 [OPTION]... [VAR=VALUE]...
+
+To assign environment variables (e.g., CC, CFLAGS...), specify them as
+VAR=VALUE.  See below for descriptions of some of the useful variables.
+
+Defaults for the options are specified in brackets.
+
+Configuration:
+  -h, --help              display this help and exit
+      --help=short        display options specific to this package
+      --help=recursive    display the short help of all the included packages
+  -V, --version           display version information and exit
+  -q, --quiet, --silent   do not print \`checking ...' messages
+      --cache-file=FILE   cache test results in FILE [disabled]
+  -C, --config-cache      alias for \`--cache-file=config.cache'
+  -n, --no-create         do not create output files
+      --srcdir=DIR        find the sources in DIR [configure dir or \`..']
+
+Installation directories:
+  --prefix=PREFIX         install architecture-independent files in PREFIX
+                          [$ac_default_prefix]
+  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
+                          [PREFIX]
+
+By default, \`make install' will install all the files in
+\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc.  You can specify
+an installation prefix other than \`$ac_default_prefix' using \`--prefix',
+for instance \`--prefix=\$HOME'.
+
+For better control, use the options below.
+
+Fine tuning of the installation directories:
+  --bindir=DIR            user executables [EPREFIX/bin]
+  --sbindir=DIR           system admin executables [EPREFIX/sbin]
+  --libexecdir=DIR        program executables [EPREFIX/libexec]
+  --sysconfdir=DIR        read-only single-machine data [PREFIX/etc]
+  --sharedstatedir=DIR    modifiable architecture-independent data [PREFIX/com]
+  --localstatedir=DIR     modifiable single-machine data [PREFIX/var]
+  --libdir=DIR            object code libraries [EPREFIX/lib]
+  --includedir=DIR        C header files [PREFIX/include]
+  --oldincludedir=DIR     C header files for non-gcc [/usr/include]
+  --datarootdir=DIR       read-only arch.-independent data root [PREFIX/share]
+  --datadir=DIR           read-only architecture-independent data [DATAROOTDIR]
+  --infodir=DIR           info documentation [DATAROOTDIR/info]
+  --localedir=DIR         locale-dependent data [DATAROOTDIR/locale]
+  --mandir=DIR            man documentation [DATAROOTDIR/man]
+  --docdir=DIR            documentation root [DATAROOTDIR/doc/rjava]
+  --htmldir=DIR           html documentation [DOCDIR]
+  --dvidir=DIR            dvi documentation [DOCDIR]
+  --pdfdir=DIR            pdf documentation [DOCDIR]
+  --psdir=DIR             ps documentation [DOCDIR]
+_ACEOF
+
+  cat <<\_ACEOF
+_ACEOF
+fi
+
+if test -n "$ac_init_help"; then
+  case $ac_init_help in
+     short | recursive ) echo "Configuration of rJava 0.8:";;
+   esac
+  cat <<\_ACEOF
+
+Optional Features:
+  --disable-option-checking  ignore unrecognized --enable/--with options
+  --disable-FEATURE       do not include FEATURE (same as --enable-FEATURE=no)
+  --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
+  --enable-threads        enable the use of threads, i.e. Java is run on a
+                          separate thread. This is necessary for some
+                          implementations of AWT. This feature is highly
+                          experimental, becasue of synchronization issues, so
+                          use with care. [no]
+  --enable-jni-cache      enable support for caching of the JNI environment.
+                          With this option turned on, the JNI state is stored
+                          locally and re-used for subsequent calls. This will
+                          work *only* if no threads are used, because each
+                          thread has a separate JNI state. Enabling this
+                          option can give some performance boost for
+                          applications that call JNI very often. If used in a
+                          threaded environment, it is bound to crash, so use
+                          with care. [no]
+  --enable-jri            enable Java to R interface (JRI), which allows Java
+                          programs to embed R. [auto]
+  --enable-headless       enable initialization in headless mode. [auto]
+  --enable-Xrs            use -Xrs in Java initialization. [auto]
+  --enable-debug          enable debug flags and output. [no]
+  --enable-mem-profile    enable memory profiling. [debug]
+  --enable-callbacks      enable the support for callbacks from Java into R.
+                          This requires JRI and is currently
+                          experimental/incomplete. [no]
+
+Some influential environment variables:
+  CC          C compiler command
+  CFLAGS      C compiler flags
+  LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries in a
+              nonstandard directory <lib dir>
+  LIBS        libraries to pass to the linker, e.g. -l<library>
+  CPPFLAGS    (Objective) C/C++ preprocessor flags, e.g. -I<include dir> if
+              you have headers in a nonstandard directory <include dir>
+  CPP         C preprocessor
+
+Use these variables to override the choices made by `configure' or to help
+it to find libraries and programs with nonstandard names/locations.
+
+Report bugs to <Simon.Urbanek@r-project.org>.
+_ACEOF
+ac_status=$?
+fi
+
+if test "$ac_init_help" = "recursive"; then
+  # If there are subdirs, report their specific --help.
+  for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
+    test -d "$ac_dir" ||
+      { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } ||
+      continue
+    ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+    cd "$ac_dir" || { ac_status=$?; continue; }
+    # Check for guested configure.
+    if test -f "$ac_srcdir/configure.gnu"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure.gnu" --help=recursive
+    elif test -f "$ac_srcdir/configure"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure" --help=recursive
+    else
+      $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
+    fi || ac_status=$?
+    cd "$ac_pwd" || { ac_status=$?; break; }
+  done
+fi
+
+test -n "$ac_init_help" && exit $ac_status
+if $ac_init_version; then
+  cat <<\_ACEOF
+rJava configure 0.8
+generated by GNU Autoconf 2.69
+
+Copyright (C) 2012 Free Software Foundation, Inc.
+This configure script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it.
+_ACEOF
+  exit
+fi
+
+## ------------------------ ##
+## Autoconf initialization. ##
+## ------------------------ ##
+
+# ac_fn_c_try_compile LINENO
+# --------------------------
+# Try to compile conftest.$ac_ext, and return whether this succeeded.
+ac_fn_c_try_compile ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  rm -f conftest.$ac_objext
+  if { { ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compile") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_retval=1
+fi
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_compile
+
+# ac_fn_c_try_cpp LINENO
+# ----------------------
+# Try to preprocess conftest.$ac_ext, and return whether this succeeded.
+ac_fn_c_try_cpp ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  if { { ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } > conftest.i && {
+	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       }; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+    ac_retval=1
+fi
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_cpp
+
+# ac_fn_c_try_run LINENO
+# ----------------------
+# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes
+# that executables *can* be run.
+ac_fn_c_try_run ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  if { { ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && { ac_try='./conftest$ac_exeext'
+  { { case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_try") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; }; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: program exited with status $ac_status" >&5
+       $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+       ac_retval=$ac_status
+fi
+  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_run
+
+# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES
+# -------------------------------------------------------
+# Tests whether HEADER exists, giving a warning if it cannot be compiled using
+# the include files in INCLUDES and setting the cache variable VAR
+# accordingly.
+ac_fn_c_check_header_mongrel ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  if eval \${$3+:} false; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+$as_echo_n "checking for $2... " >&6; }
+if eval \${$3+:} false; then :
+  $as_echo_n "(cached) " >&6
+fi
+eval ac_res=\$$3
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+else
+  # Is the header compilable?
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5
+$as_echo_n "checking $2 usability... " >&6; }
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+$4
+#include <$2>
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_header_compiler=yes
+else
+  ac_header_compiler=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5
+$as_echo "$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5
+$as_echo_n "checking $2 presence... " >&6; }
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <$2>
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+  ac_header_preproc=yes
+else
+  ac_header_preproc=no
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5
+$as_echo "$ac_header_preproc" >&6; }
+
+# So?  What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #((
+  yes:no: )
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5
+$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
+$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
+    ;;
+  no:yes:* )
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5
+$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2:     check for missing prerequisite headers?" >&5
+$as_echo "$as_me: WARNING: $2:     check for missing prerequisite headers?" >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5
+$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2:     section \"Present But Cannot Be Compiled\"" >&5
+$as_echo "$as_me: WARNING: $2:     section \"Present But Cannot Be Compiled\"" >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
+$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
+( $as_echo "## ------------------------------------------ ##
+## Report this to Simon.Urbanek@r-project.org ##
+## ------------------------------------------ ##"
+     ) | sed "s/^/$as_me: WARNING:     /" >&2
+    ;;
+esac
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+$as_echo_n "checking for $2... " >&6; }
+if eval \${$3+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  eval "$3=\$ac_header_compiler"
+fi
+eval ac_res=\$$3
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+fi
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+
+} # ac_fn_c_check_header_mongrel
+
+# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES
+# -------------------------------------------------------
+# Tests whether HEADER exists and can be compiled using the include files in
+# INCLUDES, setting the cache variable VAR accordingly.
+ac_fn_c_check_header_compile ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+$as_echo_n "checking for $2... " >&6; }
+if eval \${$3+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+$4
+#include <$2>
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  eval "$3=yes"
+else
+  eval "$3=no"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+eval ac_res=\$$3
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+
+} # ac_fn_c_check_header_compile
+
+# ac_fn_c_check_decl LINENO SYMBOL VAR INCLUDES
+# ---------------------------------------------
+# Tests whether SYMBOL is declared in INCLUDES, setting cache variable VAR
+# accordingly.
+ac_fn_c_check_decl ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  as_decl_name=`echo $2|sed 's/ *(.*//'`
+  as_decl_use=`echo $2|sed -e 's/(/((/' -e 's/)/) 0&/' -e 's/,/) 0& (/g'`
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $as_decl_name is declared" >&5
+$as_echo_n "checking whether $as_decl_name is declared... " >&6; }
+if eval \${$3+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+$4
+int
+main ()
+{
+#ifndef $as_decl_name
+#ifdef __cplusplus
+  (void) $as_decl_use;
+#else
+  (void) $as_decl_name;
+#endif
+#endif
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  eval "$3=yes"
+else
+  eval "$3=no"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+eval ac_res=\$$3
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+
+} # ac_fn_c_check_decl
+
+# ac_fn_c_try_link LINENO
+# -----------------------
+# Try to link conftest.$ac_ext, and return whether this succeeded.
+ac_fn_c_try_link ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  rm -f conftest.$ac_objext conftest$ac_exeext
+  if { { ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest$ac_exeext && {
+	 test "$cross_compiling" = yes ||
+	 test -x conftest$ac_exeext
+       }; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_retval=1
+fi
+  # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information
+  # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would
+  # interfere with the next link command; also delete a directory that is
+  # left behind by Apple's compiler.  We do this before executing the actions.
+  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_link
+cat >config.log <<_ACEOF
+This file contains any messages produced by compilers while
+running configure, to aid debugging if configure makes a mistake.
+
+It was created by rJava $as_me 0.8, which was
+generated by GNU Autoconf 2.69.  Invocation command line was
+
+  $ $0 $@
+
+_ACEOF
+exec 5>>config.log
+{
+cat <<_ASUNAME
+## --------- ##
+## Platform. ##
+## --------- ##
+
+hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`
+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 || echo unknown`
+/bin/uname -X     = `(/bin/uname -X) 2>/dev/null     || echo unknown`
+
+/bin/arch              = `(/bin/arch) 2>/dev/null              || echo unknown`
+/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null       || echo unknown`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
+/usr/bin/hostinfo      = `(/usr/bin/hostinfo) 2>/dev/null      || echo unknown`
+/bin/machine           = `(/bin/machine) 2>/dev/null           || echo unknown`
+/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null       || echo unknown`
+/bin/universe          = `(/bin/universe) 2>/dev/null          || echo unknown`
+
+_ASUNAME
+
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    $as_echo "PATH: $as_dir"
+  done
+IFS=$as_save_IFS
+
+} >&5
+
+cat >&5 <<_ACEOF
+
+
+## ----------- ##
+## Core tests. ##
+## ----------- ##
+
+_ACEOF
+
+
+# Keep a trace of the command line.
+# Strip out --no-create and --no-recursion so they do not pile up.
+# Strip out --silent because we don't want to record it for future runs.
+# Also quote any args containing shell meta-characters.
+# Make two passes to allow for proper duplicate-argument suppression.
+ac_configure_args=
+ac_configure_args0=
+ac_configure_args1=
+ac_must_keep_next=false
+for ac_pass in 1 2
+do
+  for ac_arg
+  do
+    case $ac_arg in
+    -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;;
+    -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+    | -silent | --silent | --silen | --sile | --sil)
+      continue ;;
+    *\'*)
+      ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    esac
+    case $ac_pass in
+    1) as_fn_append ac_configure_args0 " '$ac_arg'" ;;
+    2)
+      as_fn_append ac_configure_args1 " '$ac_arg'"
+      if test $ac_must_keep_next = true; then
+	ac_must_keep_next=false # Got value, back to normal.
+      else
+	case $ac_arg in
+	  *=* | --config-cache | -C | -disable-* | --disable-* \
+	  | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \
+	  | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \
+	  | -with-* | --with-* | -without-* | --without-* | --x)
+	    case "$ac_configure_args0 " in
+	      "$ac_configure_args1"*" '$ac_arg' "* ) continue ;;
+	    esac
+	    ;;
+	  -* ) ac_must_keep_next=true ;;
+	esac
+      fi
+      as_fn_append ac_configure_args " '$ac_arg'"
+      ;;
+    esac
+  done
+done
+{ ac_configure_args0=; unset ac_configure_args0;}
+{ ac_configure_args1=; unset ac_configure_args1;}
+
+# When interrupted or exit'd, cleanup temporary files, and complete
+# config.log.  We remove comments because anyway the quotes in there
+# would cause problems or look ugly.
+# WARNING: Use '\'' to represent an apostrophe within the trap.
+# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug.
+trap 'exit_status=$?
+  # Save into config.log some information that might help in debugging.
+  {
+    echo
+
+    $as_echo "## ---------------- ##
+## Cache variables. ##
+## ---------------- ##"
+    echo
+    # The following way of writing the cache mishandles newlines in values,
+(
+  for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
+$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
+      *) { eval $ac_var=; unset $ac_var;} ;;
+      esac ;;
+    esac
+  done
+  (set) 2>&1 |
+    case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
+      sed -n \
+	"s/'\''/'\''\\\\'\'''\''/g;
+	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p"
+      ;; #(
+    *)
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+      ;;
+    esac |
+    sort
+)
+    echo
+
+    $as_echo "## ----------------- ##
+## Output variables. ##
+## ----------------- ##"
+    echo
+    for ac_var in $ac_subst_vars
+    do
+      eval ac_val=\$$ac_var
+      case $ac_val in
+      *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+      esac
+      $as_echo "$ac_var='\''$ac_val'\''"
+    done | sort
+    echo
+
+    if test -n "$ac_subst_files"; then
+      $as_echo "## ------------------- ##
+## File substitutions. ##
+## ------------------- ##"
+      echo
+      for ac_var in $ac_subst_files
+      do
+	eval ac_val=\$$ac_var
+	case $ac_val in
+	*\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+	esac
+	$as_echo "$ac_var='\''$ac_val'\''"
+      done | sort
+      echo
+    fi
+
+    if test -s confdefs.h; then
+      $as_echo "## ----------- ##
+## confdefs.h. ##
+## ----------- ##"
+      echo
+      cat confdefs.h
+      echo
+    fi
+    test "$ac_signal" != 0 &&
+      $as_echo "$as_me: caught signal $ac_signal"
+    $as_echo "$as_me: exit $exit_status"
+  } >&5
+  rm -f core *.core core.conftest.* &&
+    rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
+    exit $exit_status
+' 0
+for ac_signal in 1 2 13 15; do
+  trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal
+done
+ac_signal=0
+
+# confdefs.h avoids OS command line length limits that DEFS can exceed.
+rm -f -r conftest* confdefs.h
+
+$as_echo "/* confdefs.h */" > confdefs.h
+
+# Predefined preprocessor variables.
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_NAME "$PACKAGE_NAME"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_TARNAME "$PACKAGE_TARNAME"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_VERSION "$PACKAGE_VERSION"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_STRING "$PACKAGE_STRING"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_URL "$PACKAGE_URL"
+_ACEOF
+
+
+# Let the site file select an alternate cache file if it wants to.
+# Prefer an explicitly selected file to automatically selected ones.
+ac_site_file1=NONE
+ac_site_file2=NONE
+if test -n "$CONFIG_SITE"; then
+  # We do not want a PATH search for config.site.
+  case $CONFIG_SITE in #((
+    -*)  ac_site_file1=./$CONFIG_SITE;;
+    */*) ac_site_file1=$CONFIG_SITE;;
+    *)   ac_site_file1=./$CONFIG_SITE;;
+  esac
+elif test "x$prefix" != xNONE; then
+  ac_site_file1=$prefix/share/config.site
+  ac_site_file2=$prefix/etc/config.site
+else
+  ac_site_file1=$ac_default_prefix/share/config.site
+  ac_site_file2=$ac_default_prefix/etc/config.site
+fi
+for ac_site_file in "$ac_site_file1" "$ac_site_file2"
+do
+  test "x$ac_site_file" = xNONE && continue
+  if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5
+$as_echo "$as_me: loading site script $ac_site_file" >&6;}
+    sed 's/^/| /' "$ac_site_file" >&5
+    . "$ac_site_file" \
+      || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "failed to load site script $ac_site_file
+See \`config.log' for more details" "$LINENO" 5; }
+  fi
+done
+
+if test -r "$cache_file"; then
+  # Some versions of bash will fail to source /dev/null (special files
+  # actually), so we avoid doing that.  DJGPP emulates it as a regular file.
+  if test /dev/null != "$cache_file" && test -f "$cache_file"; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5
+$as_echo "$as_me: loading cache $cache_file" >&6;}
+    case $cache_file in
+      [\\/]* | ?:[\\/]* ) . "$cache_file";;
+      *)                      . "./$cache_file";;
+    esac
+  fi
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5
+$as_echo "$as_me: creating cache $cache_file" >&6;}
+  >$cache_file
+fi
+
+# Check that the precious variables saved in the cache have kept the same
+# value.
+ac_cache_corrupted=false
+for ac_var in $ac_precious_vars; do
+  eval ac_old_set=\$ac_cv_env_${ac_var}_set
+  eval ac_new_set=\$ac_env_${ac_var}_set
+  eval ac_old_val=\$ac_cv_env_${ac_var}_value
+  eval ac_new_val=\$ac_env_${ac_var}_value
+  case $ac_old_set,$ac_new_set in
+    set,)
+      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
+$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
+      ac_cache_corrupted=: ;;
+    ,set)
+      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5
+$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
+      ac_cache_corrupted=: ;;
+    ,);;
+    *)
+      if test "x$ac_old_val" != "x$ac_new_val"; then
+	# differences in whitespace do not lead to failure.
+	ac_old_val_w=`echo x $ac_old_val`
+	ac_new_val_w=`echo x $ac_new_val`
+	if test "$ac_old_val_w" != "$ac_new_val_w"; then
+	  { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5
+$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
+	  ac_cache_corrupted=:
+	else
+	  { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5
+$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;}
+	  eval $ac_var=\$ac_old_val
+	fi
+	{ $as_echo "$as_me:${as_lineno-$LINENO}:   former value:  \`$ac_old_val'" >&5
+$as_echo "$as_me:   former value:  \`$ac_old_val'" >&2;}
+	{ $as_echo "$as_me:${as_lineno-$LINENO}:   current value: \`$ac_new_val'" >&5
+$as_echo "$as_me:   current value: \`$ac_new_val'" >&2;}
+      fi;;
+  esac
+  # Pass precious variables to config.status.
+  if test "$ac_new_set" = set; then
+    case $ac_new_val in
+    *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
+    *) ac_arg=$ac_var=$ac_new_val ;;
+    esac
+    case " $ac_configure_args " in
+      *" '$ac_arg' "*) ;; # Avoid dups.  Use of quotes ensures accuracy.
+      *) as_fn_append ac_configure_args " '$ac_arg'" ;;
+    esac
+  fi
+done
+if $ac_cache_corrupted; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+  { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5
+$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;}
+  as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5
+fi
+## -------------------- ##
+## Main body of script. ##
+## -------------------- ##
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+
+ac_config_headers="$ac_config_headers src/config.h"
+
+
+# find R home and set CC/CFLAGS
+: ${R_HOME=`R RHOME`}
+if test -z "${R_HOME}"; then
+  echo "could not determine R_HOME"
+  exit 1
+fi
+RBIN="${R_HOME}/bin/R"
+CC=`"${RBIN}" CMD config CC`;
+CFLAGS=`"${RBIN}" CMD config CFLAGS`
+LIBS="${PKG_LIBS}"
+
+
+RLD=`"${RBIN}" CMD config --ldflags 2>/dev/null`
+has_R_shlib=no
+if test -n "$RLD"; then
+   has_R_shlib=yes
+fi
+
+## enable threads, i.e. Java is running is a separate thread
+# Check whether --enable-threads was given.
+if test "${enable_threads+set}" = set; then :
+  enableval=$enable_threads; want_threads="${enableval}"
+else
+  want_threads=no
+fi
+
+
+## enable JNI-cache
+# Check whether --enable-jni-cache was given.
+if test "${enable_jni_cache+set}" = set; then :
+  enableval=$enable_jni_cache; want_jni_cache="${enableval}"
+else
+  want_jni_cache=no
+fi
+
+
+## enable JRI
+# Check whether --enable-jri was given.
+if test "${enable_jri+set}" = set; then :
+  enableval=$enable_jri; want_jri="${enableval}"
+else
+  want_jri=auto
+fi
+
+
+## enable headless
+# Check whether --enable-headless was given.
+if test "${enable_headless+set}" = set; then :
+  enableval=$enable_headless; want_headless="${enableval}"
+else
+  want_headless=auto
+fi
+
+
+## enable -Xrs support
+# Check whether --enable-Xrs was given.
+if test "${enable_Xrs+set}" = set; then :
+  enableval=$enable_Xrs; want_xrs="${enableval}"
+else
+  want_xrs=auto
+fi
+
+
+## enable debug flags
+# Check whether --enable-debug was given.
+if test "${enable_debug+set}" = set; then :
+  enableval=$enable_debug; want_debug="${enableval}"
+else
+  want_debug=no
+fi
+
+
+## enable memory profiling
+# Check whether --enable-mem-profile was given.
+if test "${enable_mem_profile+set}" = set; then :
+  enableval=$enable_mem_profile; want_memprof="${enableval}"
+else
+  want_memprof=debug
+fi
+
+
+## enable callbacks (experimental)
+# Check whether --enable-callbacks was given.
+if test "${enable_callbacks+set}" = set; then :
+  enableval=$enable_callbacks; want_callbacks="${enableval}"
+else
+  want_callbacks=no
+fi
+
+
+
+# Checks for programs.
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args.
+set dummy ${ac_tool_prefix}gcc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_CC="${ac_tool_prefix}gcc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_CC"; then
+  ac_ct_CC=$CC
+  # Extract the first word of "gcc", so it can be a program name with args.
+set dummy gcc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_CC"; then
+  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_ac_ct_CC="gcc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+$as_echo "$ac_ct_CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
+else
+  CC="$ac_cv_prog_CC"
+fi
+
+if test -z "$CC"; then
+          if test -n "$ac_tool_prefix"; then
+    # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
+set dummy ${ac_tool_prefix}cc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_CC="${ac_tool_prefix}cc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  fi
+fi
+if test -z "$CC"; then
+  # Extract the first word of "cc", so it can be a program name with args.
+set dummy cc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+  ac_prog_rejected=no
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
+       ac_prog_rejected=yes
+       continue
+     fi
+    ac_cv_prog_CC="cc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+if test $ac_prog_rejected = yes; then
+  # We found a bogon in the path, so make sure we never use it.
+  set dummy $ac_cv_prog_CC
+  shift
+  if test $# != 0; then
+    # We chose a different compiler from the bogus one.
+    # However, it has the same basename, so the bogon will be chosen
+    # first if we set CC to just the basename; use the full file name.
+    shift
+    ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@"
+  fi
+fi
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$CC"; then
+  if test -n "$ac_tool_prefix"; then
+  for ac_prog in cl.exe
+  do
+    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+    test -n "$CC" && break
+  done
+fi
+if test -z "$CC"; then
+  ac_ct_CC=$CC
+  for ac_prog in cl.exe
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_CC"; then
+  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_ac_ct_CC="$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+$as_echo "$ac_ct_CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$ac_ct_CC" && break
+done
+
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
+fi
+
+fi
+
+
+test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "no acceptable C compiler found in \$PATH
+See \`config.log' for more details" "$LINENO" 5; }
+
+# Provide some information about the compiler.
+$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
+set X $ac_compile
+ac_compiler=$2
+for ac_option in --version -v -V -qversion; do
+  { { ac_try="$ac_compiler $ac_option >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compiler $ac_option >&5") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    sed '10a\
+... rest of stderr output deleted ...
+         10q' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+  fi
+  rm -f conftest.er1 conftest.err
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+done
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+ac_clean_files_save=$ac_clean_files
+ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out"
+# Try to create an executable without -o first, disregard a.out.
+# It will help us diagnose broken compilers, and finding out an intuition
+# of exeext.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5
+$as_echo_n "checking whether the C compiler works... " >&6; }
+ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
+
+# The possible output files:
+ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*"
+
+ac_rmfiles=
+for ac_file in $ac_files
+do
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
+    * ) ac_rmfiles="$ac_rmfiles $ac_file";;
+  esac
+done
+rm -f $ac_rmfiles
+
+if { { ac_try="$ac_link_default"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link_default") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then :
+  # Autoconf-2.13 could set the ac_cv_exeext variable to `no'.
+# So ignore a value of `no', otherwise this would lead to `EXEEXT = no'
+# in a Makefile.  We should not override ac_cv_exeext if it was cached,
+# so that the user can short-circuit this test for compilers unknown to
+# Autoconf.
+for ac_file in $ac_files ''
+do
+  test -f "$ac_file" || continue
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj )
+	;;
+    [ab].out )
+	# We found the default executable, but exeext='' is most
+	# certainly right.
+	break;;
+    *.* )
+	if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no;
+	then :; else
+	   ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+	fi
+	# We set ac_cv_exeext here because the later test for it is not
+	# safe: cross compilers may not add the suffix if given an `-o'
+	# argument, so we may need to know it at that point already.
+	# Even if this section looks crufty: it has the advantage of
+	# actually working.
+	break;;
+    * )
+	break;;
+  esac
+done
+test "$ac_cv_exeext" = no && ac_cv_exeext=
+
+else
+  ac_file=''
+fi
+if test -z "$ac_file"; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+$as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error 77 "C compiler cannot create executables
+See \`config.log' for more details" "$LINENO" 5; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5
+$as_echo_n "checking for C compiler default output file name... " >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5
+$as_echo "$ac_file" >&6; }
+ac_exeext=$ac_cv_exeext
+
+rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out
+ac_clean_files=$ac_clean_files_save
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5
+$as_echo_n "checking for suffix of executables... " >&6; }
+if { { ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then :
+  # If both `conftest.exe' and `conftest' are `present' (well, observable)
+# catch `conftest.exe'.  For instance with Cygwin, `ls conftest' will
+# work properly (i.e., refer to `conftest.exe'), while it won't with
+# `rm'.
+for ac_file in conftest.exe conftest conftest.*; do
+  test -f "$ac_file" || continue
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
+    *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+	  break;;
+    * ) break;;
+  esac
+done
+else
+  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "cannot compute suffix of executables: cannot compile and link
+See \`config.log' for more details" "$LINENO" 5; }
+fi
+rm -f conftest conftest$ac_cv_exeext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5
+$as_echo "$ac_cv_exeext" >&6; }
+
+rm -f conftest.$ac_ext
+EXEEXT=$ac_cv_exeext
+ac_exeext=$EXEEXT
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdio.h>
+int
+main ()
+{
+FILE *f = fopen ("conftest.out", "w");
+ return ferror (f) || fclose (f) != 0;
+
+  ;
+  return 0;
+}
+_ACEOF
+ac_clean_files="$ac_clean_files conftest.out"
+# Check that the compiler produces executables we can run.  If not, either
+# the compiler is broken, or we cross compile.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5
+$as_echo_n "checking whether we are cross compiling... " >&6; }
+if test "$cross_compiling" != yes; then
+  { { ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+  if { ac_try='./conftest$ac_cv_exeext'
+  { { case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_try") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; }; then
+    cross_compiling=no
+  else
+    if test "$cross_compiling" = maybe; then
+	cross_compiling=yes
+    else
+	{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "cannot run C compiled programs.
+If you meant to cross compile, use \`--host'.
+See \`config.log' for more details" "$LINENO" 5; }
+    fi
+  fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5
+$as_echo "$cross_compiling" >&6; }
+
+rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out
+ac_clean_files=$ac_clean_files_save
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5
+$as_echo_n "checking for suffix of object files... " >&6; }
+if ${ac_cv_objext+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.o conftest.obj
+if { { ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compile") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then :
+  for ac_file in conftest.o conftest.obj conftest.*; do
+  test -f "$ac_file" || continue;
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;;
+    *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'`
+       break;;
+  esac
+done
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "cannot compute suffix of object files: cannot compile
+See \`config.log' for more details" "$LINENO" 5; }
+fi
+rm -f conftest.$ac_cv_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5
+$as_echo "$ac_cv_objext" >&6; }
+OBJEXT=$ac_cv_objext
+ac_objext=$OBJEXT
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5
+$as_echo_n "checking whether we are using the GNU C compiler... " >&6; }
+if ${ac_cv_c_compiler_gnu+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+#ifndef __GNUC__
+       choke me
+#endif
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_compiler_gnu=yes
+else
+  ac_compiler_gnu=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_cv_c_compiler_gnu=$ac_compiler_gnu
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5
+$as_echo "$ac_cv_c_compiler_gnu" >&6; }
+if test $ac_compiler_gnu = yes; then
+  GCC=yes
+else
+  GCC=
+fi
+ac_test_CFLAGS=${CFLAGS+set}
+ac_save_CFLAGS=$CFLAGS
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
+$as_echo_n "checking whether $CC accepts -g... " >&6; }
+if ${ac_cv_prog_cc_g+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_save_c_werror_flag=$ac_c_werror_flag
+   ac_c_werror_flag=yes
+   ac_cv_prog_cc_g=no
+   CFLAGS="-g"
+   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_g=yes
+else
+  CFLAGS=""
+      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+
+else
+  ac_c_werror_flag=$ac_save_c_werror_flag
+	 CFLAGS="-g"
+	 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_g=yes
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+   ac_c_werror_flag=$ac_save_c_werror_flag
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5
+$as_echo "$ac_cv_prog_cc_g" >&6; }
+if test "$ac_test_CFLAGS" = set; then
+  CFLAGS=$ac_save_CFLAGS
+elif test $ac_cv_prog_cc_g = yes; then
+  if test "$GCC" = yes; then
+    CFLAGS="-g -O2"
+  else
+    CFLAGS="-g"
+  fi
+else
+  if test "$GCC" = yes; then
+    CFLAGS="-O2"
+  else
+    CFLAGS=
+  fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5
+$as_echo_n "checking for $CC option to accept ISO C89... " >&6; }
+if ${ac_cv_prog_cc_c89+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_cv_prog_cc_c89=no
+ac_save_CC=$CC
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdarg.h>
+#include <stdio.h>
+struct stat;
+/* Most of the following tests are stolen from RCS 5.7's src/conf.sh.  */
+struct buf { int x; };
+FILE * (*rcsopen) (struct buf *, struct stat *, int);
+static char *e (p, i)
+     char **p;
+     int i;
+{
+  return p[i];
+}
+static char *f (char * (*g) (char **, int), char **p, ...)
+{
+  char *s;
+  va_list v;
+  va_start (v,p);
+  s = g (p, va_arg (v,int));
+  va_end (v);
+  return s;
+}
+
+/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default.  It has
+   function prototypes and stuff, but not '\xHH' hex character constants.
+   These don't provoke an error unfortunately, instead are silently treated
+   as 'x'.  The following induces an error, until -std is added to get
+   proper ANSI mode.  Curiously '\x00'!='x' always comes out true, for an
+   array size at least.  It's necessary to write '\x00'==0 to get something
+   that's true only with -std.  */
+int osf4_cc_array ['\x00' == 0 ? 1 : -1];
+
+/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
+   inside strings and character constants.  */
+#define FOO(x) 'x'
+int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1];
+
+int test (int i, double x);
+struct s1 {int (*f) (int a);};
+struct s2 {int (*f) (double a);};
+int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int);
+int argc;
+char **argv;
+int
+main ()
+{
+return f (e, argv, 0) != argv[0]  ||  f (e, argv, 1) != argv[1];
+  ;
+  return 0;
+}
+_ACEOF
+for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \
+	-Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
+do
+  CC="$ac_save_CC $ac_arg"
+  if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_c89=$ac_arg
+fi
+rm -f core conftest.err conftest.$ac_objext
+  test "x$ac_cv_prog_cc_c89" != "xno" && break
+done
+rm -f conftest.$ac_ext
+CC=$ac_save_CC
+
+fi
+# AC_CACHE_VAL
+case "x$ac_cv_prog_cc_c89" in
+  x)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
+$as_echo "none needed" >&6; } ;;
+  xno)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
+$as_echo "unsupported" >&6; } ;;
+  *)
+    CC="$CC $ac_cv_prog_cc_c89"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5
+$as_echo "$ac_cv_prog_cc_c89" >&6; } ;;
+esac
+if test "x$ac_cv_prog_cc_c89" != xno; then :
+
+fi
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+# Checks for libraries.
+
+# Checks for header files.
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5
+$as_echo_n "checking how to run the C preprocessor... " >&6; }
+# On Suns, sometimes $CPP names a directory.
+if test -n "$CPP" && test -d "$CPP"; then
+  CPP=
+fi
+if test -z "$CPP"; then
+  if ${ac_cv_prog_CPP+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+      # Double quotes because CPP needs to be expanded
+    for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
+    do
+      ac_preproc_ok=false
+for ac_c_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
+  # On the NeXT, cc -E runs the code through the compiler's parser,
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+
+else
+  # Broken: fails on valid input.
+continue
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <ac_nonexistent.h>
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+  # Broken: success on invalid input.
+continue
+else
+  # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.i conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then :
+  break
+fi
+
+    done
+    ac_cv_prog_CPP=$CPP
+
+fi
+  CPP=$ac_cv_prog_CPP
+else
+  ac_cv_prog_CPP=$CPP
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5
+$as_echo "$CPP" >&6; }
+ac_preproc_ok=false
+for ac_c_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
+  # On the NeXT, cc -E runs the code through the compiler's parser,
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+
+else
+  # Broken: fails on valid input.
+continue
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <ac_nonexistent.h>
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+  # Broken: success on invalid input.
+continue
+else
+  # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.i conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then :
+
+else
+  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "C preprocessor \"$CPP\" fails sanity check
+See \`config.log' for more details" "$LINENO" 5; }
+fi
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5
+$as_echo_n "checking for grep that handles long lines and -e... " >&6; }
+if ${ac_cv_path_GREP+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -z "$GREP"; then
+  ac_path_GREP_found=false
+  # Loop through the user's path and test for each of PROGNAME-LIST
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_prog in grep ggrep; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext"
+      as_fn_executable_p "$ac_path_GREP" || continue
+# Check for GNU ac_path_GREP and select it if it is found.
+  # Check for GNU $ac_path_GREP
+case `"$ac_path_GREP" --version 2>&1` in
+*GNU*)
+  ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;;
+*)
+  ac_count=0
+  $as_echo_n 0123456789 >"conftest.in"
+  while :
+  do
+    cat "conftest.in" "conftest.in" >"conftest.tmp"
+    mv "conftest.tmp" "conftest.in"
+    cp "conftest.in" "conftest.nl"
+    $as_echo 'GREP' >> "conftest.nl"
+    "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break
+    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+    as_fn_arith $ac_count + 1 && ac_count=$as_val
+    if test $ac_count -gt ${ac_path_GREP_max-0}; then
+      # Best one so far, save it but keep looking for a better one
+      ac_cv_path_GREP="$ac_path_GREP"
+      ac_path_GREP_max=$ac_count
+    fi
+    # 10*(2^10) chars as input seems more than enough
+    test $ac_count -gt 10 && break
+  done
+  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+esac
+
+      $ac_path_GREP_found && break 3
+    done
+  done
+  done
+IFS=$as_save_IFS
+  if test -z "$ac_cv_path_GREP"; then
+    as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
+  fi
+else
+  ac_cv_path_GREP=$GREP
+fi
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5
+$as_echo "$ac_cv_path_GREP" >&6; }
+ GREP="$ac_cv_path_GREP"
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5
+$as_echo_n "checking for egrep... " >&6; }
+if ${ac_cv_path_EGREP+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if echo a | $GREP -E '(a|b)' >/dev/null 2>&1
+   then ac_cv_path_EGREP="$GREP -E"
+   else
+     if test -z "$EGREP"; then
+  ac_path_EGREP_found=false
+  # Loop through the user's path and test for each of PROGNAME-LIST
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_prog in egrep; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext"
+      as_fn_executable_p "$ac_path_EGREP" || continue
+# Check for GNU ac_path_EGREP and select it if it is found.
+  # Check for GNU $ac_path_EGREP
+case `"$ac_path_EGREP" --version 2>&1` in
+*GNU*)
+  ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;;
+*)
+  ac_count=0
+  $as_echo_n 0123456789 >"conftest.in"
+  while :
+  do
+    cat "conftest.in" "conftest.in" >"conftest.tmp"
+    mv "conftest.tmp" "conftest.in"
+    cp "conftest.in" "conftest.nl"
+    $as_echo 'EGREP' >> "conftest.nl"
+    "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break
+    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+    as_fn_arith $ac_count + 1 && ac_count=$as_val
+    if test $ac_count -gt ${ac_path_EGREP_max-0}; then
+      # Best one so far, save it but keep looking for a better one
+      ac_cv_path_EGREP="$ac_path_EGREP"
+      ac_path_EGREP_max=$ac_count
+    fi
+    # 10*(2^10) chars as input seems more than enough
+    test $ac_count -gt 10 && break
+  done
+  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+esac
+
+      $ac_path_EGREP_found && break 3
+    done
+  done
+  done
+IFS=$as_save_IFS
+  if test -z "$ac_cv_path_EGREP"; then
+    as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
+  fi
+else
+  ac_cv_path_EGREP=$EGREP
+fi
+
+   fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5
+$as_echo "$ac_cv_path_EGREP" >&6; }
+ EGREP="$ac_cv_path_EGREP"
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
+$as_echo_n "checking for ANSI C header files... " >&6; }
+if ${ac_cv_header_stdc+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <float.h>
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_header_stdc=yes
+else
+  ac_cv_header_stdc=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+if test $ac_cv_header_stdc = yes; then
+  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <string.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "memchr" >/dev/null 2>&1; then :
+
+else
+  ac_cv_header_stdc=no
+fi
+rm -f conftest*
+
+fi
+
+if test $ac_cv_header_stdc = yes; then
+  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdlib.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "free" >/dev/null 2>&1; then :
+
+else
+  ac_cv_header_stdc=no
+fi
+rm -f conftest*
+
+fi
+
+if test $ac_cv_header_stdc = yes; then
+  # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
+  if test "$cross_compiling" = yes; then :
+  :
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <ctype.h>
+#include <stdlib.h>
+#if ((' ' & 0x0FF) == 0x020)
+# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
+# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
+#else
+# define ISLOWER(c) \
+		   (('a' <= (c) && (c) <= 'i') \
+		     || ('j' <= (c) && (c) <= 'r') \
+		     || ('s' <= (c) && (c) <= 'z'))
+# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
+#endif
+
+#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
+int
+main ()
+{
+  int i;
+  for (i = 0; i < 256; i++)
+    if (XOR (islower (i), ISLOWER (i))
+	|| toupper (i) != TOUPPER (i))
+      return 2;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_run "$LINENO"; then :
+
+else
+  ac_cv_header_stdc=no
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5
+$as_echo "$ac_cv_header_stdc" >&6; }
+if test $ac_cv_header_stdc = yes; then
+
+$as_echo "#define STDC_HEADERS 1" >>confdefs.h
+
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sys/wait.h that is POSIX.1 compatible" >&5
+$as_echo_n "checking for sys/wait.h that is POSIX.1 compatible... " >&6; }
+if ${ac_cv_header_sys_wait_h+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <sys/types.h>
+#include <sys/wait.h>
+#ifndef WEXITSTATUS
+# define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
+#endif
+#ifndef WIFEXITED
+# define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
+#endif
+
+int
+main ()
+{
+  int s;
+  wait (&s);
+  s = WIFEXITED (s) ? WEXITSTATUS (s) : 1;
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_header_sys_wait_h=yes
+else
+  ac_cv_header_sys_wait_h=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_sys_wait_h" >&5
+$as_echo "$ac_cv_header_sys_wait_h" >&6; }
+if test $ac_cv_header_sys_wait_h = yes; then
+
+$as_echo "#define HAVE_SYS_WAIT_H 1" >>confdefs.h
+
+fi
+
+# On IRIX 5.3, sys/types and inttypes.h are conflicting.
+for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \
+		  inttypes.h stdint.h unistd.h
+do :
+  as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default
+"
+if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+for ac_header in string.h sys/time.h unistd.h
+do :
+  as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default"
+if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+# Checks for typedefs, structures, and compiler characteristics.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for an ANSI C-conforming const" >&5
+$as_echo_n "checking for an ANSI C-conforming const... " >&6; }
+if ${ac_cv_c_const+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+#ifndef __cplusplus
+  /* Ultrix mips cc rejects this sort of thing.  */
+  typedef int charset[2];
+  const charset cs = { 0, 0 };
+  /* SunOS 4.1.1 cc rejects this.  */
+  char const *const *pcpcc;
+  char **ppc;
+  /* NEC SVR4.0.2 mips cc rejects this.  */
+  struct point {int x, y;};
+  static struct point const zero = {0,0};
+  /* AIX XL C 1.02.0.0 rejects this.
+     It does not let you subtract one const X* pointer from another in
+     an arm of an if-expression whose if-part is not a constant
+     expression */
+  const char *g = "string";
+  pcpcc = &g + (g ? g-g : 0);
+  /* HPUX 7.0 cc rejects these. */
+  ++pcpcc;
+  ppc = (char**) pcpcc;
+  pcpcc = (char const *const *) ppc;
+  { /* SCO 3.2v4 cc rejects this sort of thing.  */
+    char tx;
+    char *t = &tx;
+    char const *s = 0 ? (char *) 0 : (char const *) 0;
+
+    *t++ = 0;
+    if (s) return 0;
+  }
+  { /* Someone thinks the Sun supposedly-ANSI compiler will reject this.  */
+    int x[] = {25, 17};
+    const int *foo = &x[0];
+    ++foo;
+  }
+  { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */
+    typedef const int *iptr;
+    iptr p = 0;
+    ++p;
+  }
+  { /* AIX XL C 1.02.0.0 rejects this sort of thing, saying
+       "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */
+    struct s { int j; const int *ap[3]; } bx;
+    struct s *b = &bx; b->j = 5;
+  }
+  { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */
+    const int foo = 10;
+    if (!foo) return 0;
+  }
+  return !cs[0] && !zero.x;
+#endif
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_c_const=yes
+else
+  ac_cv_c_const=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_const" >&5
+$as_echo "$ac_cv_c_const" >&6; }
+if test $ac_cv_c_const = no; then
+
+$as_echo "#define const /**/" >>confdefs.h
+
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether time.h and sys/time.h may both be included" >&5
+$as_echo_n "checking whether time.h and sys/time.h may both be included... " >&6; }
+if ${ac_cv_header_time+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <sys/types.h>
+#include <sys/time.h>
+#include <time.h>
+
+int
+main ()
+{
+if ((struct tm *) 0)
+return 0;
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_header_time=yes
+else
+  ac_cv_header_time=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_time" >&5
+$as_echo "$ac_cv_header_time" >&6; }
+if test $ac_cv_header_time = yes; then
+
+$as_echo "#define TIME_WITH_SYS_TIME 1" >>confdefs.h
+
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${CC} supports static inline..." >&5
+$as_echo "$as_me: checking whether ${CC} supports static inline..." >&6;}
+can_inline=no
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+static inline int foo(int a, int b);
+static f = 1;
+static inline int foo(int a, int b) { return a+b; }
+int main(void) {
+    return foo(f,-1);
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  can_inline=yes
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: ${can_inline}" >&5
+$as_echo "${can_inline}" >&6; }
+if test "${can_inline}" = yes; then
+
+$as_echo "#define HAVE_STATIC_INLINE 1" >>confdefs.h
+
+fi
+
+### from R m4/R.m4 - needed to hack R 2.9.x
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether setjmp.h is POSIX.1 compatible" >&5
+$as_echo_n "checking whether setjmp.h is POSIX.1 compatible... " >&6; }
+if ${r_cv_header_setjmp_posix+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <setjmp.h>
+int
+main ()
+{
+sigjmp_buf b;
+sigsetjmp(b, 0);
+siglongjmp(b, 1);
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  r_cv_header_setjmp_posix=yes
+else
+  r_cv_header_setjmp_posix=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $r_cv_header_setjmp_posix" >&5
+$as_echo "$r_cv_header_setjmp_posix" >&6; }
+ac_fn_c_check_decl "$LINENO" "sigsetjmp" "ac_cv_have_decl_sigsetjmp" "#include <setjmp.h>
+"
+if test "x$ac_cv_have_decl_sigsetjmp" = xyes; then :
+  ac_have_decl=1
+else
+  ac_have_decl=0
+fi
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_SIGSETJMP $ac_have_decl
+_ACEOF
+ac_fn_c_check_decl "$LINENO" "siglongjmp" "ac_cv_have_decl_siglongjmp" "#include <setjmp.h>
+"
+if test "x$ac_cv_have_decl_siglongjmp" = xyes; then :
+  ac_have_decl=1
+else
+  ac_have_decl=0
+fi
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_SIGLONGJMP $ac_have_decl
+_ACEOF
+
+if test "$ac_cv_have_decl_sigsetjmp" = no; then
+  r_cv_header_setjmp_posix=no
+fi
+if test "$ac_cv_have_decl_siglongjmp" = no; then
+  r_cv_header_setjmp_posix=no
+fi
+if test "${r_cv_header_setjmp_posix}" = yes; then
+
+$as_echo "#define HAVE_POSIX_SETJMP 1" >>confdefs.h
+
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking Java support in R" >&5
+$as_echo_n "checking Java support in R... " >&6; }
+R_JAVA_HOME=`"${RBIN}" CMD config JAVA_HOME`
+: ${JAVA_HOME="${R_JAVA_HOME}"}
+if test -z "${JAVA_HOME}"; then
+   as_fn_error $? "absent
+R was configured without Java support. Please run
+R CMD javareconf
+as root to add Java support to R.
+
+If you do not have root privileges, run
+R CMD javareconf -e
+to set all Java-related variables and then install rJava." "$LINENO" 5
+fi
+
+: ${JAR=`"${RBIN}" CMD config JAR|sed 's/ERROR:.*//'`}
+: ${JAVA=`"${RBIN}" CMD config JAVA|sed 's/ERROR:.*//'`}
+: ${JAVAC=`"${RBIN}" CMD config JAVAC|sed 's/ERROR:.*//'`}
+: ${JAVAH=`"${RBIN}" CMD config JAVAH|sed 's/ERROR:.*//'`}
+: ${JAVA_CPPFLAGS=`"${RBIN}" CMD config JAVA_CPPFLAGS|sed 's/ERROR:.*//'`}
+: ${JAVA_LIBS=`"${RBIN}" CMD config JAVA_LIBS|sed 's/ERROR:.*//'`}
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: present:
+interpreter : '${JAVA}'
+archiver    : '${JAR}'
+compiler    : '${JAVAC}'
+header prep.: '${JAVAH}'
+cpp flags   : '${JAVA_CPPFLAGS}'
+java libs   : '${JAVA_LIBS}'" >&5
+$as_echo "present:
+interpreter : '${JAVA}'
+archiver    : '${JAR}'
+compiler    : '${JAVAC}'
+header prep.: '${JAVAH}'
+cpp flags   : '${JAVA_CPPFLAGS}'
+java libs   : '${JAVA_LIBS}'" >&6; }
+
+java_error='One or more Java configuration variables are not set.'
+if test -z "${JAVA}"; then
+   java_error='Java interpreter is missing or not registered in R'
+fi
+if test -z "${JAVAC}"; then
+   java_error='Java Development Kit (JDK) is missing or not registered in R'
+fi
+
+have_all_flags=no
+if test -n "${JAVA}" && test -n "${JAVAC}" && test -n "${JAVAH}" && \
+   test -n "${JAVA_CPPFLAGS}" && test -n "${JAVA_LIBS}" && test -n "${JAR}"; then
+  have_all_flags=yes;
+fi
+if test "${have_all_flags}" = no; then
+  as_fn_error $? "${java_error}
+Make sure R is configured with full Java support (including JDK). Run
+R CMD javareconf
+as root to add Java support to R.
+
+If you don't have root privileges, run
+R CMD javareconf -e
+to set all Java-related variables and then install rJava.
+" "$LINENO" 5
+fi
+
+if test `echo foo | sed -e 's:foo:bar:'` = bar; then
+   JAVA_CPPFLAGS0=`echo ${JAVA_CPPFLAGS} | sed -e 's:$(JAVA_HOME):'${JAVA_HOME}':g'`
+   JAVA_LIBS0=`echo ${JAVA_LIBS} | sed -e 's:$(JAVA_HOME):'${JAVA_HOME}':g'`
+   JAVA_LD_LIBRARY_PATH0=`echo ${JAVA_LD_LIBRARY_PATH} | sed -e 's:$(JAVA_HOME):'${JAVA_HOME}':g'`
+else
+   { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: sed is not working properly - the configuration may fail" >&5
+$as_echo "$as_me: WARNING: sed is not working properly - the configuration may fail" >&2;}
+   JAVA_CPPFLAGS0="${JAVA_CPPFLAGS}"
+   JAVA_LIBS0="${JAVA_LIBS}"
+   JAVA_LD_LIBRARY_PATH0="${JAVA_LD_LIBRARY_PATH}"
+fi
+
+OSNAME=`uname -s 2>/dev/null`
+
+LIBS="${LIBS} ${JAVA_LIBS0}"
+CFLAGS="${CFLAGS} ${JAVA_CPPFLAGS0}"
+LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${JAVA_LD_LIBRARY_PATH0}"
+if test "x$OSNAME" = xDarwin; then
+  ## we need to pull that out of R in case re-export fails (which is does on 10.11)
+  DYLD_FALLBACK_LIBRARY_PATH=`"${RBIN}" --slave --vanilla -e 'cat(Sys.getenv("DYLD_FALLBACK_LIBRARY_PATH"))'`
+  export DYLD_FALLBACK_LIBRARY_PATH
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether Java run-time works" >&5
+$as_echo_n "checking whether Java run-time works... " >&6; }
+if "$JAVA" -classpath . getsp; then
+   { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+else
+   { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+   as_fn_error $? "Java interpreter '$JAVA' does not work" "$LINENO" 5
+fi
+
+has_xrs="$want_xrs"
+if test x"$has_xrs" = xauto; then
+   { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -Xrs is supported" >&5
+$as_echo_n "checking whether -Xrs is supported... " >&6; }
+   if "$JAVA" -Xrs -classpath . getsp; then
+      has_xrs=yes
+   else
+      has_xrs=no
+   fi
+   { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${has_xrs}" >&5
+$as_echo "${has_xrs}" >&6; }
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -Xrs will be used" >&5
+$as_echo_n "checking whether -Xrs will be used... " >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: ${has_xrs}" >&5
+$as_echo "${has_xrs}" >&6; }
+if test "$has_xrs" = xyes; then
+
+$as_echo "#define HAVE_XRS 1" >>confdefs.h
+
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether JNI programs can be compiled" >&5
+$as_echo_n "checking whether JNI programs can be compiled... " >&6; }
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+#include <jni.h>
+int main(void) {
+    jobject o;
+    JNI_CreateJavaVM(0, 0, 0);
+    return 0;
+}
+
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+else
+  as_fn_error $? "Cannot compile a simple JNI program. See config.log for details.
+
+Make sure you have Java Development Kit installed and correctly registered in R.
+If in doubt, re-run \"R CMD javareconf\" as root.
+" "$LINENO" 5
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking JNI data types" >&5
+$as_echo_n "checking JNI data types... " >&6; }
+if test "$cross_compiling" = yes; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: don't know (cross-compiling)" >&5
+$as_echo "don't know (cross-compiling)" >&6; }
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+#include <jni.h>
+int main(void) {
+  return (sizeof(int)==sizeof(jint) && sizeof(long)==sizeof(long) && sizeof(jbyte)==sizeof(char) && sizeof(jshort)==sizeof(short) && sizeof(jfloat)==sizeof(float) && sizeof(jdouble)==sizeof(double))?0:1;
+}
+
+_ACEOF
+if ac_fn_c_try_run "$LINENO"; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5
+$as_echo "ok" >&6; }
+else
+  as_fn_error $? "One or more JNI types differ from the corresponding native type. You may need to use non-standard compiler flags or a different compiler in order to fix this." "$LINENO" 5
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+
+if test "${want_jri}" = auto; then
+   { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether JRI should be compiled (autodetect)" >&5
+$as_echo_n "checking whether JRI should be compiled (autodetect)... " >&6; }
+   { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${has_R_shlib}" >&5
+$as_echo "${has_R_shlib}" >&6; }
+   want_jri=${has_R_shlib}
+fi
+ if test "x${want_jri}" = xyes; then
+  WANT_JRI_TRUE=
+  WANT_JRI_FALSE='#'
+else
+  WANT_JRI_TRUE='#'
+  WANT_JRI_FALSE=
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether debugging output should be enabled" >&5
+$as_echo_n "checking whether debugging output should be enabled... " >&6; }
+if test "${want_debug}" = yes; then
+  JAVA_CPPFLAGS="-g -DRJ_DEBUG ${JAVA_CPPFLAGS}"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether memory profiling is desired" >&5
+$as_echo_n "checking whether memory profiling is desired... " >&6; }
+if test "${want_memprof}" = debug; then
+   want_memprof="${want_debug}"
+fi
+if test "${want_memprof}" = yes; then
+
+$as_echo "#define MEMPROF 1" >>confdefs.h
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+
+
+
+
+
+
+use_threads=no
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether threads support is requested" >&5
+$as_echo_n "checking whether threads support is requested... " >&6; }
+if test "${want_threads}" = yes; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether threads can be enabled" >&5
+$as_echo_n "checking whether threads can be enabled... " >&6; }
+  # check whether we can add THREADS support
+  # we don't want to run full AC_CANONICAL_HOST, all we care about is OS X
+  if test "x$OSNAME" = xDarwin; then
+    use_threads=yes
+
+$as_echo "#define THREADS 1" >>confdefs.h
+
+  fi
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${use_threads}" >&5
+$as_echo "${use_threads}" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+## enable callbacks if desired
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether callbacks support is requested" >&5
+$as_echo_n "checking whether callbacks support is requested... " >&6; }
+if test "${want_callbacks}" = yes; then
+   { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+   if test "${want_jri}" != yes; then
+      as_fn_error $? "Callbacks support can be only enabled if JRI is enabled as well." "$LINENO" 5
+   fi
+
+$as_echo "#define ENABLE_JRICB 1" >>confdefs.h
+
+else
+   { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether JNI cache support is requested" >&5
+$as_echo_n "checking whether JNI cache support is requested... " >&6; }
+if test "${want_jni_cache}" = yes; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+  if test "${use_threads}" = yes; then
+    as_fn_error $? "Threads and JNI cache cannot be used at the same time, because JNI cache is by definition not thread-safe. Please disable either option." "$LINENO" 5
+  fi
+
+$as_echo "#define JNI_CACHE 1" >>confdefs.h
+
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether headless init is enabled" >&5
+$as_echo_n "checking whether headless init is enabled... " >&6; }
+if test "${want_headless}" = auto; then
+  want_headless=no
+  ## only Darwin defaults to headless
+  if test "x$OSNAME" = xDarwin; then
+    want_headless=yes
+  fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: ${want_headless}" >&5
+$as_echo "${want_headless}" >&6; }
+if test "${want_headless}" = yes; then
+
+$as_echo "#define USE_HEADLESS_INIT 1" >>confdefs.h
+
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether JRI is requested" >&5
+$as_echo_n "checking whether JRI is requested... " >&6; }
+if test "${want_jri}" = yes; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+  export R_HOME
+  export JAVA_HOME JAVA_CPPFLAGS JAVA_LIBS JAVA_LD_LIBRARY_PATH JAVA JAVAC JAVAH JAR
+  CONFIGURED=1
+  export CONFIGURED
+  ac_aux_dir=
+for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do
+  if test -f "$ac_dir/install-sh"; then
+    ac_aux_dir=$ac_dir
+    ac_install_sh="$ac_aux_dir/install-sh -c"
+    break
+  elif test -f "$ac_dir/install.sh"; then
+    ac_aux_dir=$ac_dir
+    ac_install_sh="$ac_aux_dir/install.sh -c"
+    break
+  elif test -f "$ac_dir/shtool"; then
+    ac_aux_dir=$ac_dir
+    ac_install_sh="$ac_aux_dir/shtool install -c"
+    break
+  fi
+done
+if test -z "$ac_aux_dir"; then
+  as_fn_error $? "cannot find install-sh, install.sh, or shtool in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" "$LINENO" 5
+fi
+
+# These three variables are undocumented and unsupported,
+# and are intended to be withdrawn in a future Autoconf release.
+# They can cause serious problems if a builder's source tree is in a directory
+# whose full name contains unusual characters.
+ac_config_guess="$SHELL $ac_aux_dir/config.guess"  # Please don't use this var.
+ac_config_sub="$SHELL $ac_aux_dir/config.sub"  # Please don't use this var.
+ac_configure="$SHELL $ac_aux_dir/configure"  # Please don't use this var.
+
+
+
+
+subdirs="$subdirs jri"
+
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+ac_config_files="$ac_config_files src/Makevars"
+
+ac_config_files="$ac_config_files R/zzz.R"
+
+cat >confcache <<\_ACEOF
+# This file is a shell script that caches the results of configure
+# tests run on this system so they can be shared between configure
+# scripts and configure runs, see configure's option --config-cache.
+# It is not useful on other systems.  If it contains results you don't
+# want to keep, you may remove or edit it.
+#
+# config.status only pays attention to the cache file if you give it
+# the --recheck option to rerun configure.
+#
+# `ac_cv_env_foo' variables (set or unset) will be overridden when
+# loading this file, other *unset* `ac_cv_foo' will be assigned the
+# following values.
+
+_ACEOF
+
+# The following way of writing the cache mishandles newlines in values,
+# but we know of no workaround that is simple, portable, and efficient.
+# So, we kill variables containing newlines.
+# Ultrix sh set writes to stderr and can't be redirected directly,
+# and sets the high bit in the cache file unless we assign to the vars.
+(
+  for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
+$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
+      *) { eval $ac_var=; unset $ac_var;} ;;
+      esac ;;
+    esac
+  done
+
+  (set) 2>&1 |
+    case $as_nl`(ac_space=' '; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
+      # `set' does not quote correctly, so add quotes: double-quote
+      # substitution turns \\\\ into \\, and sed turns \\ into \.
+      sed -n \
+	"s/'/'\\\\''/g;
+	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
+      ;; #(
+    *)
+      # `set' quotes correctly as required by POSIX, so do not add quotes.
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+      ;;
+    esac |
+    sort
+) |
+  sed '
+     /^ac_cv_env_/b end
+     t clear
+     :clear
+     s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
+     t end
+     s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
+     :end' >>confcache
+if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
+  if test -w "$cache_file"; then
+    if test "x$cache_file" != "x/dev/null"; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5
+$as_echo "$as_me: updating cache $cache_file" >&6;}
+      if test ! -f "$cache_file" || test -h "$cache_file"; then
+	cat confcache >"$cache_file"
+      else
+        case $cache_file in #(
+        */* | ?:*)
+	  mv -f confcache "$cache_file"$$ &&
+	  mv -f "$cache_file"$$ "$cache_file" ;; #(
+        *)
+	  mv -f confcache "$cache_file" ;;
+	esac
+      fi
+    fi
+  else
+    { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5
+$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;}
+  fi
+fi
+rm -f confcache
+
+test "x$prefix" = xNONE && prefix=$ac_default_prefix
+# Let make expand exec_prefix.
+test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
+
+DEFS=-DHAVE_CONFIG_H
+
+ac_libobjs=
+ac_ltlibobjs=
+U=
+for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
+  # 1. Remove the extension, and $U if already installed.
+  ac_script='s/\$U\././;s/\.o$//;s/\.obj$//'
+  ac_i=`$as_echo "$ac_i" | sed "$ac_script"`
+  # 2. Prepend LIBOBJDIR.  When used with automake>=1.10 LIBOBJDIR
+  #    will be set to the directory where LIBOBJS objects are built.
+  as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext"
+  as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo'
+done
+LIBOBJS=$ac_libobjs
+
+LTLIBOBJS=$ac_ltlibobjs
+
+
+if test -z "${WANT_JRI_TRUE}" && test -z "${WANT_JRI_FALSE}"; then
+  as_fn_error $? "conditional \"WANT_JRI\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
+fi
+
+: "${CONFIG_STATUS=./config.status}"
+ac_write_fail=0
+ac_clean_files_save=$ac_clean_files
+ac_clean_files="$ac_clean_files $CONFIG_STATUS"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5
+$as_echo "$as_me: creating $CONFIG_STATUS" >&6;}
+as_write_fail=0
+cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1
+#! $SHELL
+# Generated by $as_me.
+# Run this file to recreate the current configuration.
+# Compiler output produced by configure, useful for debugging
+# configure, is in config.log if it exists.
+
+debug=false
+ac_cs_recheck=false
+ac_cs_silent=false
+
+SHELL=\${CONFIG_SHELL-$SHELL}
+export SHELL
+_ASEOF
+cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1
+## -------------------- ##
+## M4sh Initialization. ##
+## -------------------- ##
+
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
+  emulate sh
+  NULLCMD=:
+  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in #(
+  *posix*) :
+    set -o posix ;; #(
+  *) :
+     ;;
+esac
+fi
+
+
+as_nl='
+'
+export as_nl
+# Printing a long string crashes Solaris 7 /usr/bin/printf.
+as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
+# Prefer a ksh shell builtin over an external printf program on Solaris,
+# but without wasting forks for bash or zsh.
+if test -z "$BASH_VERSION$ZSH_VERSION" \
+    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='print -r --'
+  as_echo_n='print -rn --'
+elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='printf %s\n'
+  as_echo_n='printf %s'
+else
+  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
+    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
+    as_echo_n='/usr/ucb/echo -n'
+  else
+    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
+    as_echo_n_body='eval
+      arg=$1;
+      case $arg in #(
+      *"$as_nl"*)
+	expr "X$arg" : "X\\(.*\\)$as_nl";
+	arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
+      esac;
+      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
+    '
+    export as_echo_n_body
+    as_echo_n='sh -c $as_echo_n_body as_echo'
+  fi
+  export as_echo_body
+  as_echo='sh -c $as_echo_body as_echo'
+fi
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  PATH_SEPARATOR=:
+  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
+    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
+      PATH_SEPARATOR=';'
+  }
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+IFS=" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+as_myself=
+case $0 in #((
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+  done
+IFS=$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  exit 1
+fi
+
+# Unset variables that we do not need and which cause bugs (e.g. in
+# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
+# suppresses any "Segmentation fault" message there.  '((' could
+# trigger a bug in pdksh 5.2.14.
+for as_var in BASH_ENV ENV MAIL MAILPATH
+do eval test x\${$as_var+set} = xset \
+  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+LC_ALL=C
+export LC_ALL
+LANGUAGE=C
+export LANGUAGE
+
+# CDPATH.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+
+# as_fn_error STATUS ERROR [LINENO LOG_FD]
+# ----------------------------------------
+# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
+# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
+# script with STATUS, using 1 if that was 0.
+as_fn_error ()
+{
+  as_status=$1; test $as_status -eq 0 && as_status=1
+  if test "$4"; then
+    as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
+  fi
+  $as_echo "$as_me: error: $2" >&2
+  as_fn_exit $as_status
+} # as_fn_error
+
+
+# as_fn_set_status STATUS
+# -----------------------
+# Set $? to STATUS, without forking.
+as_fn_set_status ()
+{
+  return $1
+} # as_fn_set_status
+
+# as_fn_exit STATUS
+# -----------------
+# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
+as_fn_exit ()
+{
+  set +e
+  as_fn_set_status $1
+  exit $1
+} # as_fn_exit
+
+# as_fn_unset VAR
+# ---------------
+# Portably unset VAR.
+as_fn_unset ()
+{
+  { eval $1=; unset $1;}
+}
+as_unset=as_fn_unset
+# as_fn_append VAR VALUE
+# ----------------------
+# Append the text in VALUE to the end of the definition contained in VAR. Take
+# advantage of any shell optimizations that allow amortized linear growth over
+# repeated appends, instead of the typical quadratic growth present in naive
+# implementations.
+if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
+  eval 'as_fn_append ()
+  {
+    eval $1+=\$2
+  }'
+else
+  as_fn_append ()
+  {
+    eval $1=\$$1\$2
+  }
+fi # as_fn_append
+
+# as_fn_arith ARG...
+# ------------------
+# Perform arithmetic evaluation on the ARGs, and store the result in the
+# global $as_val. Take advantage of shells that can avoid forks. The arguments
+# must be portable across $(()) and expr.
+if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
+  eval 'as_fn_arith ()
+  {
+    as_val=$(( $* ))
+  }'
+else
+  as_fn_arith ()
+  {
+    as_val=`expr "$@" || test $? -eq 1`
+  }
+fi # as_fn_arith
+
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+  as_basename=basename
+else
+  as_basename=false
+fi
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
+
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in #(((((
+-n*)
+  case `echo 'xy\c'` in
+  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
+  xy)  ECHO_C='\c';;
+  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
+       ECHO_T='	';;
+  esac;;
+*)
+  ECHO_N='-n';;
+esac
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir 2>/dev/null
+fi
+if (echo >conf$$.file) 2>/dev/null; then
+  if ln -s conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s='ln -s'
+    # ... but there are two gotchas:
+    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+    # In both cases, we have to default to `cp -pR'.
+    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+      as_ln_s='cp -pR'
+  elif ln conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s=ln
+  else
+    as_ln_s='cp -pR'
+  fi
+else
+  as_ln_s='cp -pR'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+
+# as_fn_mkdir_p
+# -------------
+# Create "$as_dir" as a directory, including parents if necessary.
+as_fn_mkdir_p ()
+{
+
+  case $as_dir in #(
+  -*) as_dir=./$as_dir;;
+  esac
+  test -d "$as_dir" || eval $as_mkdir_p || {
+    as_dirs=
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
+      *) as_qdir=$as_dir;;
+      esac
+      as_dirs="'$as_qdir' $as_dirs"
+      as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_dir" : 'X\(//\)[^/]' \| \
+	 X"$as_dir" : 'X\(//\)$' \| \
+	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_dir" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+      test -d "$as_dir" && break
+    done
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
+
+
+} # as_fn_mkdir_p
+if mkdir -p . 2>/dev/null; then
+  as_mkdir_p='mkdir -p "$as_dir"'
+else
+  test -d ./-p && rmdir ./-p
+  as_mkdir_p=false
+fi
+
+
+# as_fn_executable_p FILE
+# -----------------------
+# Test if FILE is an executable regular file.
+as_fn_executable_p ()
+{
+  test -f "$1" && test -x "$1"
+} # as_fn_executable_p
+as_test_x='test -x'
+as_executable_p=as_fn_executable_p
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+exec 6>&1
+## ----------------------------------- ##
+## Main body of $CONFIG_STATUS script. ##
+## ----------------------------------- ##
+_ASEOF
+test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+# Save the log message, to keep $0 and so on meaningful, and to
+# report actual input values of CONFIG_FILES etc. instead of their
+# values after options handling.
+ac_log="
+This file was extended by rJava $as_me 0.8, which was
+generated by GNU Autoconf 2.69.  Invocation command line was
+
+  CONFIG_FILES    = $CONFIG_FILES
+  CONFIG_HEADERS  = $CONFIG_HEADERS
+  CONFIG_LINKS    = $CONFIG_LINKS
+  CONFIG_COMMANDS = $CONFIG_COMMANDS
+  $ $0 $@
+
+on `(hostname || uname -n) 2>/dev/null | sed 1q`
+"
+
+_ACEOF
+
+case $ac_config_files in *"
+"*) set x $ac_config_files; shift; ac_config_files=$*;;
+esac
+
+case $ac_config_headers in *"
+"*) set x $ac_config_headers; shift; ac_config_headers=$*;;
+esac
+
+
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+# Files that config.status was made for.
+config_files="$ac_config_files"
+config_headers="$ac_config_headers"
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+ac_cs_usage="\
+\`$as_me' instantiates files and other configuration actions
+from templates according to the current configuration.  Unless the files
+and actions are specified as TAGs, all are instantiated by default.
+
+Usage: $0 [OPTION]... [TAG]...
+
+  -h, --help       print this help, then exit
+  -V, --version    print version number and configuration settings, then exit
+      --config     print configuration, then exit
+  -q, --quiet, --silent
+                   do not print progress messages
+  -d, --debug      don't remove temporary files
+      --recheck    update $as_me by reconfiguring in the same conditions
+      --file=FILE[:TEMPLATE]
+                   instantiate the configuration file FILE
+      --header=FILE[:TEMPLATE]
+                   instantiate the configuration header FILE
+
+Configuration files:
+$config_files
+
+Configuration headers:
+$config_headers
+
+Report bugs to <Simon.Urbanek@r-project.org>."
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
+ac_cs_version="\\
+rJava config.status 0.8
+configured by $0, generated by GNU Autoconf 2.69,
+  with options \\"\$ac_cs_config\\"
+
+Copyright (C) 2012 Free Software Foundation, Inc.
+This config.status script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it."
+
+ac_pwd='$ac_pwd'
+srcdir='$srcdir'
+test -n "\$AWK" || AWK=awk
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+# The default lists apply if the user does not specify any file.
+ac_need_defaults=:
+while test $# != 0
+do
+  case $1 in
+  --*=?*)
+    ac_option=`expr "X$1" : 'X\([^=]*\)='`
+    ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
+    ac_shift=:
+    ;;
+  --*=)
+    ac_option=`expr "X$1" : 'X\([^=]*\)='`
+    ac_optarg=
+    ac_shift=:
+    ;;
+  *)
+    ac_option=$1
+    ac_optarg=$2
+    ac_shift=shift
+    ;;
+  esac
+
+  case $ac_option in
+  # Handling of the options.
+  -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
+    ac_cs_recheck=: ;;
+  --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
+    $as_echo "$ac_cs_version"; exit ;;
+  --config | --confi | --conf | --con | --co | --c )
+    $as_echo "$ac_cs_config"; exit ;;
+  --debug | --debu | --deb | --de | --d | -d )
+    debug=: ;;
+  --file | --fil | --fi | --f )
+    $ac_shift
+    case $ac_optarg in
+    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    '') as_fn_error $? "missing file argument" ;;
+    esac
+    as_fn_append CONFIG_FILES " '$ac_optarg'"
+    ac_need_defaults=false;;
+  --header | --heade | --head | --hea )
+    $ac_shift
+    case $ac_optarg in
+    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    esac
+    as_fn_append CONFIG_HEADERS " '$ac_optarg'"
+    ac_need_defaults=false;;
+  --he | --h)
+    # Conflict between --help and --header
+    as_fn_error $? "ambiguous option: \`$1'
+Try \`$0 --help' for more information.";;
+  --help | --hel | -h )
+    $as_echo "$ac_cs_usage"; exit ;;
+  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+  | -silent | --silent | --silen | --sile | --sil | --si | --s)
+    ac_cs_silent=: ;;
+
+  # This is an error.
+  -*) as_fn_error $? "unrecognized option: \`$1'
+Try \`$0 --help' for more information." ;;
+
+  *) as_fn_append ac_config_targets " $1"
+     ac_need_defaults=false ;;
+
+  esac
+  shift
+done
+
+ac_configure_extra_args=
+
+if $ac_cs_silent; then
+  exec 6>/dev/null
+  ac_configure_extra_args="$ac_configure_extra_args --silent"
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+if \$ac_cs_recheck; then
+  set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
+  shift
+  \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6
+  CONFIG_SHELL='$SHELL'
+  export CONFIG_SHELL
+  exec "\$@"
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+exec 5>>config.log
+{
+  echo
+  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
+## Running $as_me. ##
+_ASBOX
+  $as_echo "$ac_log"
+} >&5
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+
+# Handling of arguments.
+for ac_config_target in $ac_config_targets
+do
+  case $ac_config_target in
+    "src/config.h") CONFIG_HEADERS="$CONFIG_HEADERS src/config.h" ;;
+    "src/Makevars") CONFIG_FILES="$CONFIG_FILES src/Makevars" ;;
+    "R/zzz.R") CONFIG_FILES="$CONFIG_FILES R/zzz.R" ;;
+
+  *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
+  esac
+done
+
+
+# If the user did not use the arguments to specify the items to instantiate,
+# then the envvar interface is used.  Set only those that are not.
+# We use the long form for the default assignment because of an extremely
+# bizarre bug on SunOS 4.1.3.
+if $ac_need_defaults; then
+  test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
+  test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers
+fi
+
+# Have a temporary directory for convenience.  Make it in the build tree
+# simply because there is no reason against having it here, and in addition,
+# creating and moving files from /tmp can sometimes cause problems.
+# Hook for its removal unless debugging.
+# Note that there is a small window in which the directory will not be cleaned:
+# after its creation but before its name has been assigned to `$tmp'.
+$debug ||
+{
+  tmp= ac_tmp=
+  trap 'exit_status=$?
+  : "${ac_tmp:=$tmp}"
+  { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status
+' 0
+  trap 'as_fn_exit 1' 1 2 13 15
+}
+# Create a (secure) tmp directory for tmp files.
+
+{
+  tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
+  test -d "$tmp"
+}  ||
+{
+  tmp=./conf$$-$RANDOM
+  (umask 077 && mkdir "$tmp")
+} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5
+ac_tmp=$tmp
+
+# Set up the scripts for CONFIG_FILES section.
+# No need to generate them if there are no CONFIG_FILES.
+# This happens for instance with `./config.status config.h'.
+if test -n "$CONFIG_FILES"; then
+
+
+ac_cr=`echo X | tr X '\015'`
+# On cygwin, bash can eat \r inside `` if the user requested igncr.
+# But we know of no other shell where ac_cr would be empty at this
+# point, so we can use a bashism as a fallback.
+if test "x$ac_cr" = x; then
+  eval ac_cr=\$\'\\r\'
+fi
+ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' </dev/null 2>/dev/null`
+if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then
+  ac_cs_awk_cr='\\r'
+else
+  ac_cs_awk_cr=$ac_cr
+fi
+
+echo 'BEGIN {' >"$ac_tmp/subs1.awk" &&
+_ACEOF
+
+
+{
+  echo "cat >conf$$subs.awk <<_ACEOF" &&
+  echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' &&
+  echo "_ACEOF"
+} >conf$$subs.sh ||
+  as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
+ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'`
+ac_delim='%!_!# '
+for ac_last_try in false false false false false :; do
+  . ./conf$$subs.sh ||
+    as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
+
+  ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X`
+  if test $ac_delim_n = $ac_delim_num; then
+    break
+  elif $ac_last_try; then
+    as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
+  else
+    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
+  fi
+done
+rm -f conf$$subs.sh
+
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK &&
+_ACEOF
+sed -n '
+h
+s/^/S["/; s/!.*/"]=/
+p
+g
+s/^[^!]*!//
+:repl
+t repl
+s/'"$ac_delim"'$//
+t delim
+:nl
+h
+s/\(.\{148\}\)..*/\1/
+t more1
+s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/
+p
+n
+b repl
+:more1
+s/["\\]/\\&/g; s/^/"/; s/$/"\\/
+p
+g
+s/.\{148\}//
+t nl
+:delim
+h
+s/\(.\{148\}\)..*/\1/
+t more2
+s/["\\]/\\&/g; s/^/"/; s/$/"/
+p
+b
+:more2
+s/["\\]/\\&/g; s/^/"/; s/$/"\\/
+p
+g
+s/.\{148\}//
+t delim
+' <conf$$subs.awk | sed '
+/^[^""]/{
+  N
+  s/\n//
+}
+' >>$CONFIG_STATUS || ac_write_fail=1
+rm -f conf$$subs.awk
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+_ACAWK
+cat >>"\$ac_tmp/subs1.awk" <<_ACAWK &&
+  for (key in S) S_is_set[key] = 1
+  FS = ""
+
+}
+{
+  line = $ 0
+  nfields = split(line, field, "@")
+  substed = 0
+  len = length(field[1])
+  for (i = 2; i < nfields; i++) {
+    key = field[i]
+    keylen = length(key)
+    if (S_is_set[key]) {
+      value = S[key]
+      line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3)
+      len += length(value) + length(field[++i])
+      substed = 1
+    } else
+      len += 1 + keylen
+  }
+
+  print line
+}
+
+_ACAWK
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then
+  sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g"
+else
+  cat
+fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \
+  || as_fn_error $? "could not setup config files machinery" "$LINENO" 5
+_ACEOF
+
+# VPATH may cause trouble with some makes, so we remove sole $(srcdir),
+# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and
+# trailing colons and then remove the whole line if VPATH becomes empty
+# (actually we leave an empty line to preserve line numbers).
+if test "x$srcdir" = x.; then
+  ac_vpsub='/^[	 ]*VPATH[	 ]*=[	 ]*/{
+h
+s///
+s/^/:/
+s/[	 ]*$/:/
+s/:\$(srcdir):/:/g
+s/:\${srcdir}:/:/g
+s/:@srcdir@:/:/g
+s/^:*//
+s/:*$//
+x
+s/\(=[	 ]*\).*/\1/
+G
+s/\n//
+s/^[^=]*=[	 ]*$//
+}'
+fi
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+fi # test -n "$CONFIG_FILES"
+
+# Set up the scripts for CONFIG_HEADERS section.
+# No need to generate them if there are no CONFIG_HEADERS.
+# This happens for instance with `./config.status Makefile'.
+if test -n "$CONFIG_HEADERS"; then
+cat >"$ac_tmp/defines.awk" <<\_ACAWK ||
+BEGIN {
+_ACEOF
+
+# Transform confdefs.h into an awk script `defines.awk', embedded as
+# here-document in config.status, that substitutes the proper values into
+# config.h.in to produce config.h.
+
+# Create a delimiter string that does not exist in confdefs.h, to ease
+# handling of long lines.
+ac_delim='%!_!# '
+for ac_last_try in false false :; do
+  ac_tt=`sed -n "/$ac_delim/p" confdefs.h`
+  if test -z "$ac_tt"; then
+    break
+  elif $ac_last_try; then
+    as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5
+  else
+    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
+  fi
+done
+
+# For the awk script, D is an array of macro values keyed by name,
+# likewise P contains macro parameters if any.  Preserve backslash
+# newline sequences.
+
+ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]*
+sed -n '
+s/.\{148\}/&'"$ac_delim"'/g
+t rset
+:rset
+s/^[	 ]*#[	 ]*define[	 ][	 ]*/ /
+t def
+d
+:def
+s/\\$//
+t bsnl
+s/["\\]/\\&/g
+s/^ \('"$ac_word_re"'\)\(([^()]*)\)[	 ]*\(.*\)/P["\1"]="\2"\
+D["\1"]=" \3"/p
+s/^ \('"$ac_word_re"'\)[	 ]*\(.*\)/D["\1"]=" \2"/p
+d
+:bsnl
+s/["\\]/\\&/g
+s/^ \('"$ac_word_re"'\)\(([^()]*)\)[	 ]*\(.*\)/P["\1"]="\2"\
+D["\1"]=" \3\\\\\\n"\\/p
+t cont
+s/^ \('"$ac_word_re"'\)[	 ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p
+t cont
+d
+:cont
+n
+s/.\{148\}/&'"$ac_delim"'/g
+t clear
+:clear
+s/\\$//
+t bsnlc
+s/["\\]/\\&/g; s/^/"/; s/$/"/p
+d
+:bsnlc
+s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p
+b cont
+' <confdefs.h | sed '
+s/'"$ac_delim"'/"\\\
+"/g' >>$CONFIG_STATUS || ac_write_fail=1
+
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+  for (key in D) D_is_set[key] = 1
+  FS = ""
+}
+/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ {
+  line = \$ 0
+  split(line, arg, " ")
+  if (arg[1] == "#") {
+    defundef = arg[2]
+    mac1 = arg[3]
+  } else {
+    defundef = substr(arg[1], 2)
+    mac1 = arg[2]
+  }
+  split(mac1, mac2, "(") #)
+  macro = mac2[1]
+  prefix = substr(line, 1, index(line, defundef) - 1)
+  if (D_is_set[macro]) {
+    # Preserve the white space surrounding the "#".
+    print prefix "define", macro P[macro] D[macro]
+    next
+  } else {
+    # Replace #undef with comments.  This is necessary, for example,
+    # in the case of _POSIX_SOURCE, which is predefined and required
+    # on some systems where configure will not decide to define it.
+    if (defundef == "undef") {
+      print "/*", prefix defundef, macro, "*/"
+      next
+    }
+  }
+}
+{ print }
+_ACAWK
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+  as_fn_error $? "could not setup config headers machinery" "$LINENO" 5
+fi # test -n "$CONFIG_HEADERS"
+
+
+eval set X "  :F $CONFIG_FILES  :H $CONFIG_HEADERS    "
+shift
+for ac_tag
+do
+  case $ac_tag in
+  :[FHLC]) ac_mode=$ac_tag; continue;;
+  esac
+  case $ac_mode$ac_tag in
+  :[FHL]*:*);;
+  :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;;
+  :[FH]-) ac_tag=-:-;;
+  :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
+  esac
+  ac_save_IFS=$IFS
+  IFS=:
+  set x $ac_tag
+  IFS=$ac_save_IFS
+  shift
+  ac_file=$1
+  shift
+
+  case $ac_mode in
+  :L) ac_source=$1;;
+  :[FH])
+    ac_file_inputs=
+    for ac_f
+    do
+      case $ac_f in
+      -) ac_f="$ac_tmp/stdin";;
+      *) # Look for the file first in the build tree, then in the source tree
+	 # (if the path is not absolute).  The absolute path cannot be DOS-style,
+	 # because $ac_f cannot contain `:'.
+	 test -f "$ac_f" ||
+	   case $ac_f in
+	   [\\/$]*) false;;
+	   *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
+	   esac ||
+	   as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;;
+      esac
+      case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac
+      as_fn_append ac_file_inputs " '$ac_f'"
+    done
+
+    # Let's still pretend it is `configure' which instantiates (i.e., don't
+    # use $as_me), people would be surprised to read:
+    #    /* config.h.  Generated by config.status.  */
+    configure_input='Generated from '`
+	  $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g'
+	`' by configure.'
+    if test x"$ac_file" != x-; then
+      configure_input="$ac_file.  $configure_input"
+      { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5
+$as_echo "$as_me: creating $ac_file" >&6;}
+    fi
+    # Neutralize special characters interpreted by sed in replacement strings.
+    case $configure_input in #(
+    *\&* | *\|* | *\\* )
+       ac_sed_conf_input=`$as_echo "$configure_input" |
+       sed 's/[\\\\&|]/\\\\&/g'`;; #(
+    *) ac_sed_conf_input=$configure_input;;
+    esac
+
+    case $ac_tag in
+    *:-:* | *:-) cat >"$ac_tmp/stdin" \
+      || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;;
+    esac
+    ;;
+  esac
+
+  ac_dir=`$as_dirname -- "$ac_file" ||
+$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$ac_file" : 'X\(//\)[^/]' \| \
+	 X"$ac_file" : 'X\(//\)$' \| \
+	 X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$ac_file" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+  as_dir="$ac_dir"; as_fn_mkdir_p
+  ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+
+  case $ac_mode in
+  :F)
+  #
+  # CONFIG_FILE
+  #
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+# If the template does not know about datarootdir, expand it.
+# FIXME: This hack should be removed a few years after 2.60.
+ac_datarootdir_hack=; ac_datarootdir_seen=
+ac_sed_dataroot='
+/datarootdir/ {
+  p
+  q
+}
+/@datadir@/p
+/@docdir@/p
+/@infodir@/p
+/@localedir@/p
+/@mandir@/p'
+case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in
+*datarootdir*) ac_datarootdir_seen=yes;;
+*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
+$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+  ac_datarootdir_hack='
+  s&@datadir@&$datadir&g
+  s&@docdir@&$docdir&g
+  s&@infodir@&$infodir&g
+  s&@localedir@&$localedir&g
+  s&@mandir@&$mandir&g
+  s&\\\${datarootdir}&$datarootdir&g' ;;
+esac
+_ACEOF
+
+# Neutralize VPATH when `$srcdir' = `.'.
+# Shell code in configure.ac might set extrasub.
+# FIXME: do we really want to maintain this feature?
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+ac_sed_extra="$ac_vpsub
+$extrasub
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+:t
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
+s|@configure_input@|$ac_sed_conf_input|;t t
+s&@top_builddir@&$ac_top_builddir_sub&;t t
+s&@top_build_prefix@&$ac_top_build_prefix&;t t
+s&@srcdir@&$ac_srcdir&;t t
+s&@abs_srcdir@&$ac_abs_srcdir&;t t
+s&@top_srcdir@&$ac_top_srcdir&;t t
+s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
+s&@builddir@&$ac_builddir&;t t
+s&@abs_builddir@&$ac_abs_builddir&;t t
+s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
+$ac_datarootdir_hack
+"
+eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \
+  >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5
+
+test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
+  { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } &&
+  { ac_out=`sed -n '/^[	 ]*datarootdir[	 ]*:*=/p' \
+      "$ac_tmp/out"`; test -z "$ac_out"; } &&
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined" >&5
+$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined" >&2;}
+
+  rm -f "$ac_tmp/stdin"
+  case $ac_file in
+  -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";;
+  *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";;
+  esac \
+  || as_fn_error $? "could not create $ac_file" "$LINENO" 5
+ ;;
+  :H)
+  #
+  # CONFIG_HEADER
+  #
+  if test x"$ac_file" != x-; then
+    {
+      $as_echo "/* $configure_input  */" \
+      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs"
+    } >"$ac_tmp/config.h" \
+      || as_fn_error $? "could not create $ac_file" "$LINENO" 5
+    if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5
+$as_echo "$as_me: $ac_file is unchanged" >&6;}
+    else
+      rm -f "$ac_file"
+      mv "$ac_tmp/config.h" "$ac_file" \
+	|| as_fn_error $? "could not create $ac_file" "$LINENO" 5
+    fi
+  else
+    $as_echo "/* $configure_input  */" \
+      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \
+      || as_fn_error $? "could not create -" "$LINENO" 5
+  fi
+ ;;
+
+
+  esac
+
+done # for ac_tag
+
+
+as_fn_exit 0
+_ACEOF
+ac_clean_files=$ac_clean_files_save
+
+test $ac_write_fail = 0 ||
+  as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5
+
+
+# configure is writing to config.log, and then calls config.status.
+# config.status does its own redirection, appending to config.log.
+# Unfortunately, on DOS this fails, as config.log is still kept open
+# by configure, so config.status won't be able to write to it; its
+# output is simply discarded.  So we exec the FD to /dev/null,
+# effectively closing config.log, so it can be properly (re)opened and
+# appended to by config.status.  When coming back to configure, we
+# need to make the FD available again.
+if test "$no_create" != yes; then
+  ac_cs_success=:
+  ac_config_status_args=
+  test "$silent" = yes &&
+    ac_config_status_args="$ac_config_status_args --quiet"
+  exec 5>/dev/null
+  $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false
+  exec 5>>config.log
+  # Use ||, not &&, to avoid exiting from the if with $? = 1, which
+  # would make configure fail if this is the last instruction.
+  $ac_cs_success || as_fn_exit 1
+fi
+
+#
+# CONFIG_SUBDIRS section.
+#
+if test "$no_recursion" != yes; then
+
+  # Remove --cache-file, --srcdir, and --disable-option-checking arguments
+  # so they do not pile up.
+  ac_sub_configure_args=
+  ac_prev=
+  eval "set x $ac_configure_args"
+  shift
+  for ac_arg
+  do
+    if test -n "$ac_prev"; then
+      ac_prev=
+      continue
+    fi
+    case $ac_arg in
+    -cache-file | --cache-file | --cache-fil | --cache-fi \
+    | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
+      ac_prev=cache_file ;;
+    -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
+    | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* \
+    | --c=*)
+      ;;
+    --config-cache | -C)
+      ;;
+    -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
+      ac_prev=srcdir ;;
+    -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
+      ;;
+    -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
+      ac_prev=prefix ;;
+    -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
+      ;;
+    --disable-option-checking)
+      ;;
+    *)
+      case $ac_arg in
+      *\'*) ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+      esac
+      as_fn_append ac_sub_configure_args " '$ac_arg'" ;;
+    esac
+  done
+
+  # Always prepend --prefix to ensure using the same prefix
+  # in subdir configurations.
+  ac_arg="--prefix=$prefix"
+  case $ac_arg in
+  *\'*) ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+  esac
+  ac_sub_configure_args="'$ac_arg' $ac_sub_configure_args"
+
+  # Pass --silent
+  if test "$silent" = yes; then
+    ac_sub_configure_args="--silent $ac_sub_configure_args"
+  fi
+
+  # Always prepend --disable-option-checking to silence warnings, since
+  # different subdirs can have different --enable and --with options.
+  ac_sub_configure_args="--disable-option-checking $ac_sub_configure_args"
+
+  ac_popdir=`pwd`
+  for ac_dir in : $subdirs; do test "x$ac_dir" = x: && continue
+
+    # Do not complain, so a configure script can configure whichever
+    # parts of a large source tree are present.
+    test -d "$srcdir/$ac_dir" || continue
+
+    ac_msg="=== configuring in $ac_dir (`pwd`/$ac_dir)"
+    $as_echo "$as_me:${as_lineno-$LINENO}: $ac_msg" >&5
+    $as_echo "$ac_msg" >&6
+    as_dir="$ac_dir"; as_fn_mkdir_p
+    ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+
+    cd "$ac_dir"
+
+    # Check for guested configure; otherwise get Cygnus style configure.
+    if test -f "$ac_srcdir/configure.gnu"; then
+      ac_sub_configure=$ac_srcdir/configure.gnu
+    elif test -f "$ac_srcdir/configure"; then
+      ac_sub_configure=$ac_srcdir/configure
+    elif test -f "$ac_srcdir/configure.in"; then
+      # This should be Cygnus configure.
+      ac_sub_configure=$ac_aux_dir/configure
+    else
+      { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: no configuration information is in $ac_dir" >&5
+$as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2;}
+      ac_sub_configure=
+    fi
+
+    # The recursion is here.
+    if test -n "$ac_sub_configure"; then
+      # Make the cache file name correct relative to the subdirectory.
+      case $cache_file in
+      [\\/]* | ?:[\\/]* ) ac_sub_cache_file=$cache_file ;;
+      *) # Relative name.
+	ac_sub_cache_file=$ac_top_build_prefix$cache_file ;;
+      esac
+
+      { $as_echo "$as_me:${as_lineno-$LINENO}: running $SHELL $ac_sub_configure $ac_sub_configure_args --cache-file=$ac_sub_cache_file --srcdir=$ac_srcdir" >&5
+$as_echo "$as_me: running $SHELL $ac_sub_configure $ac_sub_configure_args --cache-file=$ac_sub_cache_file --srcdir=$ac_srcdir" >&6;}
+      # The eval makes quoting arguments work.
+      eval "\$SHELL \"\$ac_sub_configure\" $ac_sub_configure_args \
+	   --cache-file=\"\$ac_sub_cache_file\" --srcdir=\"\$ac_srcdir\"" ||
+	as_fn_error $? "$ac_sub_configure failed for $ac_dir" "$LINENO" 5
+    fi
+
+    cd "$ac_popdir"
+  done
+fi
+if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5
+$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;}
+fi
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/configure.ac b/com.oracle.truffle.r.pkgs/rJava/configure.ac
new file mode 100644
index 0000000000000000000000000000000000000000..d7dfb89a2bcc0b10b25e51ff559a74507fb79b2b
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/configure.ac
@@ -0,0 +1,368 @@
+# Process this file with autoconf to produce a configure script.
+AC_INIT(rJava, 0.8, Simon.Urbanek@r-project.org)
+AC_CONFIG_SRCDIR([src/rJava.c])
+AC_CONFIG_HEADER([src/config.h])
+
+# find R home and set CC/CFLAGS
+: ${R_HOME=`R RHOME`}
+if test -z "${R_HOME}"; then
+  echo "could not determine R_HOME"
+  exit 1
+fi
+RBIN="${R_HOME}/bin/R"
+CC=`"${RBIN}" CMD config CC`;
+CFLAGS=`"${RBIN}" CMD config CFLAGS`
+LIBS="${PKG_LIBS}"
+AC_SUBST(R_HOME)
+
+RLD=`"${RBIN}" CMD config --ldflags 2>/dev/null`
+has_R_shlib=no
+if test -n "$RLD"; then
+   has_R_shlib=yes
+fi
+
+## enable threads, i.e. Java is running is a separate thread
+AC_ARG_ENABLE([threads],
+[AC_HELP_STRING([--enable-threads],
+		[enable the use of threads, i.e. Java is run on a separate thread.
+		This is necessary for some implementations of AWT. This feature
+		is highly experimental, becasue of synchronization issues, so
+		use with care. @<:@no@:>@])],
+[want_threads="${enableval}"],
+[want_threads=no])
+
+## enable JNI-cache
+AC_ARG_ENABLE([jni-cache],
+[AC_HELP_STRING([--enable-jni-cache],
+	        [enable support for caching of the JNI environment. With this
+		 option turned on, the JNI state is stored locally and re-used
+		 for subsequent calls. This will work *only* if no threads are
+		 used, because each thread has a separate JNI state. Enabling
+		 this option can give some performance boost for applications
+		 that call JNI very often. If used in a threaded environment,
+		 it is bound to crash, so use with care. @<:@no@:>@])],
+[want_jni_cache="${enableval}"],
+[want_jni_cache=no])
+
+## enable JRI
+AC_ARG_ENABLE([jri],
+[AC_HELP_STRING([--enable-jri],
+		[enable Java to R interface (JRI), which allows Java programs
+		to embed R. @<:@auto@:>@])],
+[want_jri="${enableval}"],
+[want_jri=auto])
+
+## enable headless
+AC_ARG_ENABLE([headless],
+[AC_HELP_STRING([--enable-headless],
+		[enable initialization in headless mode. @<:@auto@:>@])],
+[want_headless="${enableval}"],
+[want_headless=auto])
+
+## enable -Xrs support
+AC_ARG_ENABLE([Xrs],
+[AC_HELP_STRING([--enable-Xrs],
+		[use -Xrs in Java initialization. @<:@auto@:>@])],
+[want_xrs="${enableval}"],
+[want_xrs=auto])
+
+## enable debug flags
+AC_ARG_ENABLE([debug],
+[AC_HELP_STRING([--enable-debug],
+		[enable debug flags and output. @<:@no@:>@])],
+[want_debug="${enableval}"],
+[want_debug=no])
+
+## enable memory profiling
+AC_ARG_ENABLE([mem-profile],
+[AC_HELP_STRING([--enable-mem-profile],
+		[enable memory profiling. @<:@debug@:>@])],
+[want_memprof="${enableval}"],
+[want_memprof=debug])
+
+## enable callbacks (experimental)
+AC_ARG_ENABLE([callbacks],
+[AC_HELP_STRING([--enable-callbacks],
+		[enable the support for callbacks from Java into R. This requires JRI and is currently experimental/incomplete. @<:@no@:>@])],
+[want_callbacks="${enableval}"],
+[want_callbacks=no])
+
+
+# Checks for programs.
+AC_PROG_CC
+
+# Checks for libraries.
+
+# Checks for header files.
+AC_HEADER_STDC
+AC_HEADER_SYS_WAIT
+AC_CHECK_HEADERS([string.h sys/time.h unistd.h])
+
+# Checks for typedefs, structures, and compiler characteristics.
+AC_C_CONST
+AC_HEADER_TIME
+
+AC_CHECKING([whether ${CC} supports static inline])
+can_inline=no
+AC_COMPILE_IFELSE([AC_LANG_SOURCE([
+static inline int foo(int a, int b);
+static f = 1;
+static inline int foo(int a, int b) { return a+b; }
+int main(void) {
+    return foo(f,-1);
+}])],can_inline=yes)
+AC_MSG_RESULT(${can_inline})
+if test "${can_inline}" = yes; then
+  AC_DEFINE(HAVE_STATIC_INLINE, 1, [Define to 1 when static inline works])
+fi
+
+### from R m4/R.m4 - needed to hack R 2.9.x
+AC_CACHE_CHECK([whether setjmp.h is POSIX.1 compatible],
+               [r_cv_header_setjmp_posix],
+[AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
+[[#include <setjmp.h>]],
+[[sigjmp_buf b;
+sigsetjmp(b, 0);
+siglongjmp(b, 1);]])],
+                   [r_cv_header_setjmp_posix=yes],
+                   [r_cv_header_setjmp_posix=no])])
+AC_CHECK_DECLS([sigsetjmp, siglongjmp], , , [#include <setjmp.h>])
+if test "$ac_cv_have_decl_sigsetjmp" = no; then
+  r_cv_header_setjmp_posix=no
+fi
+if test "$ac_cv_have_decl_siglongjmp" = no; then
+  r_cv_header_setjmp_posix=no
+fi
+if test "${r_cv_header_setjmp_posix}" = yes; then
+  AC_DEFINE(HAVE_POSIX_SETJMP, 1,
+            [Define if you have POSIX.1 compatible sigsetjmp/siglongjmp.])
+fi
+
+AC_MSG_CHECKING([Java support in R])
+R_JAVA_HOME=`"${RBIN}" CMD config JAVA_HOME`
+: ${JAVA_HOME="${R_JAVA_HOME}"}
+if test -z "${JAVA_HOME}"; then
+   AC_MSG_ERROR([absent
+R was configured without Java support. Please run
+R CMD javareconf
+as root to add Java support to R.
+
+If you do not have root privileges, run
+R CMD javareconf -e
+to set all Java-related variables and then install rJava.])
+fi
+
+: ${JAR=`"${RBIN}" CMD config JAR|sed 's/ERROR:.*//'`}
+: ${JAVA=`"${RBIN}" CMD config JAVA|sed 's/ERROR:.*//'`}
+: ${JAVAC=`"${RBIN}" CMD config JAVAC|sed 's/ERROR:.*//'`}
+: ${JAVAH=`"${RBIN}" CMD config JAVAH|sed 's/ERROR:.*//'`}
+: ${JAVA_CPPFLAGS=`"${RBIN}" CMD config JAVA_CPPFLAGS|sed 's/ERROR:.*//'`}
+: ${JAVA_LIBS=`"${RBIN}" CMD config JAVA_LIBS|sed 's/ERROR:.*//'`}
+
+AC_MSG_RESULT([present:
+interpreter : '${JAVA}'
+archiver    : '${JAR}'
+compiler    : '${JAVAC}'
+header prep.: '${JAVAH}'
+cpp flags   : '${JAVA_CPPFLAGS}'
+java libs   : '${JAVA_LIBS}'])
+
+java_error='One or more Java configuration variables are not set.'
+if test -z "${JAVA}"; then
+   java_error='Java interpreter is missing or not registered in R'
+fi
+if test -z "${JAVAC}"; then
+   java_error='Java Development Kit (JDK) is missing or not registered in R'
+fi
+
+have_all_flags=no
+if test -n "${JAVA}" && test -n "${JAVAC}" && test -n "${JAVAH}" && \
+   test -n "${JAVA_CPPFLAGS}" && test -n "${JAVA_LIBS}" && test -n "${JAR}"; then
+  have_all_flags=yes;
+fi
+if test "${have_all_flags}" = no; then
+  AC_MSG_ERROR([${java_error}
+Make sure R is configured with full Java support (including JDK). Run
+R CMD javareconf
+as root to add Java support to R.
+
+If you don't have root privileges, run
+R CMD javareconf -e
+to set all Java-related variables and then install rJava.
+])
+fi
+
+if test `echo foo | sed -e 's:foo:bar:'` = bar; then
+   JAVA_CPPFLAGS0=`echo ${JAVA_CPPFLAGS} | sed -e 's:$(JAVA_HOME):'${JAVA_HOME}':g'`
+   JAVA_LIBS0=`echo ${JAVA_LIBS} | sed -e 's:$(JAVA_HOME):'${JAVA_HOME}':g'`
+   JAVA_LD_LIBRARY_PATH0=`echo ${JAVA_LD_LIBRARY_PATH} | sed -e 's:$(JAVA_HOME):'${JAVA_HOME}':g'`
+else
+   AC_MSG_WARN([sed is not working properly - the configuration may fail])
+   JAVA_CPPFLAGS0="${JAVA_CPPFLAGS}"
+   JAVA_LIBS0="${JAVA_LIBS}"
+   JAVA_LD_LIBRARY_PATH0="${JAVA_LD_LIBRARY_PATH}"
+fi
+
+OSNAME=`uname -s 2>/dev/null`
+
+LIBS="${LIBS} ${JAVA_LIBS0}"
+CFLAGS="${CFLAGS} ${JAVA_CPPFLAGS0}"
+LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${JAVA_LD_LIBRARY_PATH0}"
+if test "x$OSNAME" = xDarwin; then
+  ## we need to pull that out of R in case re-export fails (which is does on 10.11)
+  DYLD_FALLBACK_LIBRARY_PATH=`"${RBIN}" --slave --vanilla -e 'cat(Sys.getenv("DYLD_FALLBACK_LIBRARY_PATH"))'`
+  export DYLD_FALLBACK_LIBRARY_PATH
+fi
+
+AC_MSG_CHECKING([whether Java run-time works])
+if "$JAVA" -classpath . getsp; then
+   AC_MSG_RESULT(yes)
+else
+   AC_MSG_RESULT(no)
+   AC_MSG_ERROR([Java interpreter '$JAVA' does not work])
+fi
+
+has_xrs="$want_xrs"
+if test x"$has_xrs" = xauto; then
+   AC_MSG_CHECKING([whether -Xrs is supported])
+   if "$JAVA" -Xrs -classpath . getsp; then
+      has_xrs=yes
+   else
+      has_xrs=no
+   fi
+   AC_MSG_RESULT(${has_xrs})
+fi
+
+AC_MSG_CHECKING([whether -Xrs will be used])
+AC_MSG_RESULT(${has_xrs})
+if test "$has_xrs" = xyes; then
+   AC_DEFINE(HAVE_XRS, 1, [Set if the Java parameter -Xrs is supported])
+fi
+
+AC_MSG_CHECKING([whether JNI programs can be compiled])
+AC_LINK_IFELSE([AC_LANG_SOURCE([
+#include <jni.h>
+int main(void) {
+    jobject o;
+    JNI_CreateJavaVM(0, 0, 0);
+    return 0;
+}
+	])],[AC_MSG_RESULT(yes)],
+	[AC_MSG_ERROR([Cannot compile a simple JNI program. See config.log for details.
+
+Make sure you have Java Development Kit installed and correctly registered in R.
+If in doubt, re-run "R CMD javareconf" as root.
+])])
+
+AC_MSG_CHECKING([JNI data types])
+AC_TRY_RUN(
+	[
+#include <jni.h>
+int main(void) {
+  return (sizeof(int)==sizeof(jint) && sizeof(long)==sizeof(long) && sizeof(jbyte)==sizeof(char) && sizeof(jshort)==sizeof(short) && sizeof(jfloat)==sizeof(float) && sizeof(jdouble)==sizeof(double))?0:1;
+}
+	],
+	[AC_MSG_RESULT([ok])],
+	[AC_MSG_ERROR([One or more JNI types differ from the corresponding native type. You may need to use non-standard compiler flags or a different compiler in order to fix this.])],
+	[AC_MSG_RESULT([don't know (cross-compiling)])])
+
+if test "${want_jri}" = auto; then
+   AC_MSG_CHECKING([whether JRI should be compiled (autodetect)])
+   AC_MSG_RESULT([${has_R_shlib}])
+   want_jri=${has_R_shlib}
+fi
+AM_CONDITIONAL(WANT_JRI, [test "x${want_jri}" = xyes])
+
+AC_MSG_CHECKING([whether debugging output should be enabled])
+if test "${want_debug}" = yes; then
+  JAVA_CPPFLAGS="-g -DRJ_DEBUG ${JAVA_CPPFLAGS}"
+  AC_MSG_RESULT([yes])
+else
+  AC_MSG_RESULT([no])
+fi
+
+AC_MSG_CHECKING([whether memory profiling is desired])
+if test "${want_memprof}" = debug; then
+   want_memprof="${want_debug}"
+fi
+if test "${want_memprof}" = yes; then
+  AC_DEFINE(MEMPROF, 1, [memory profiling is enabled when defined])
+  AC_MSG_RESULT([yes])
+else
+  AC_MSG_RESULT([no])
+fi
+
+AC_SUBST(JAVA_LIBS)
+AC_SUBST(JAVA_CPPFLAGS)
+AC_SUBST(JAVA_HOME)
+AC_SUBST(JAVA)
+AC_SUBST(JAVAC)
+AC_SUBST(JAVAH)
+
+use_threads=no
+AC_MSG_CHECKING([whether threads support is requested])
+if test "${want_threads}" = yes; then
+  AC_MSG_RESULT([yes])
+  AC_MSG_CHECKING([whether threads can be enabled])
+  # check whether we can add THREADS support
+  # we don't want to run full AC_CANONICAL_HOST, all we care about is OS X
+  if test "x$OSNAME" = xDarwin; then
+    use_threads=yes
+    AC_DEFINE(THREADS, 1, [Set if threading support should be enabled.])
+  fi
+  AC_MSG_RESULT([${use_threads}])
+else
+  AC_MSG_RESULT([no])
+fi
+
+## enable callbacks if desired
+AC_MSG_CHECKING([whether callbacks support is requested])
+if test "${want_callbacks}" = yes; then
+   AC_MSG_RESULT([yes])
+   if test "${want_jri}" != yes; then
+      AC_MSG_ERROR([Callbacks support can be only enabled if JRI is enabled as well.])
+   fi
+   AC_DEFINE(ENABLE_JRICB, 1, [define if callbacks support is enabled.])
+else
+   AC_MSG_RESULT([no])
+fi
+
+AC_MSG_CHECKING([whether JNI cache support is requested])
+if test "${want_jni_cache}" = yes; then
+  AC_MSG_RESULT([yes])
+  if test "${use_threads}" = yes; then
+    AC_MSG_ERROR([Threads and JNI cache cannot be used at the same time, because JNI cache is by definition not thread-safe. Please disable either option.])
+  fi
+  AC_DEFINE(JNI_CACHE, 1, [Set if caching JNI environment is enabled.])
+else
+  AC_MSG_RESULT([no])
+fi
+
+AC_MSG_CHECKING([whether headless init is enabled])
+if test "${want_headless}" = auto; then
+  want_headless=no
+  ## only Darwin defaults to headless
+  if test "x$OSNAME" = xDarwin; then
+    want_headless=yes
+  fi
+fi
+AC_MSG_RESULT([${want_headless}])
+if test "${want_headless}" = yes; then
+  AC_DEFINE(USE_HEADLESS_INIT, 1, [Set if headless mode is to be used when starting the JVM])
+fi
+
+AC_MSG_CHECKING([whether JRI is requested])
+if test "${want_jri}" = yes; then
+  AC_MSG_RESULT([yes])
+  export R_HOME
+  export JAVA_HOME JAVA_CPPFLAGS JAVA_LIBS JAVA_LD_LIBRARY_PATH JAVA JAVAC JAVAH JAR
+  CONFIGURED=1
+  export CONFIGURED
+  AC_CONFIG_SUBDIRS(jri)
+else
+  AC_MSG_RESULT([no])
+fi
+
+AC_CONFIG_FILES([src/Makevars])
+AC_CONFIG_FILES([R/zzz.R])
+AC_OUTPUT
diff --git a/com.oracle.truffle.r.pkgs/rJava/configure.win b/com.oracle.truffle.r.pkgs/rJava/configure.win
new file mode 100644
index 0000000000000000000000000000000000000000..cd1b09a2521a9d2f6f7cdb8e3b01bf4b398a2c95
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/configure.win
@@ -0,0 +1,61 @@
+#!/bin/sh
+
+echo "Generate Windows-specific files (src/jvm-w32) ..."
+make -C src/jvm-w32
+
+if [ $? != 0 ]; then
+  exit 1
+fi
+
+echo "Find Java..."
+# findjava honors JAVA_HOME environment variable, so we can safely overwite it 
+if [ -e src/jvm-w32/findjava.exe ]; then
+    JAVA_HOME=`src/jvm-w32/findjava -s -f`
+fi
+if [ x$JAVA_HOME = x ]; then
+    echo "ERROR: cannot find Java Development Kit." >&2
+    echo "       Please set JAVA_HOME to specify its location manually" >&2
+    exit 1
+fi
+
+echo "  JAVA_HOME=$JAVA_HOME"
+
+echo "JAVA_HOME:=$JAVA_HOME" > src/Makevars.java
+
+if [ -e jri/configure.win ]; then
+    echo "=== Building JRI ==="
+    CONFIGURED=1
+    export CONFIGURED
+    if [ -z "${RHOME}" ]; then
+	RHOME="${R_HOME}"
+    fi
+    R_HOME=${RHOME}
+    export R_HOME
+    export RHOME
+    export JAVA_HOME
+    cd jri
+    sh configure.win
+    make
+    BR=$?
+    cd ..
+    if [ $BR = 0 ]; then
+	echo "=== JRI built ==="
+	mkdir -p inst/jri
+	# also copy into R_ARCH is present to avoid overwriting different archs
+	if [ -n "${R_ARCH}" ]; then
+	    mkdir -p inst/jri${R_ARCH}
+	    cp jri/src/jri.dll inst/jri${R_ARCH}/
+	fi
+	# yet still install into JRI in case users get confused
+	cp -r jri/run.bat jri/src/jri.dll jri/src/JRI.jar jri/examples inst/jri/
+    else
+	echo "**** WARNING: JRI could NOT be built" >&2
+	if [ -z "$INGORE" ]; then
+	    echo "Set IGNORE=1 if you want to build rJava anyway."
+	    exit 1
+	fi
+    fi
+fi
+
+echo "Configuration done."
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/getsp.java b/com.oracle.truffle.r.pkgs/rJava/getsp.java
new file mode 100644
index 0000000000000000000000000000000000000000..a4067b1c1e85660d27031b7635289cd7a95c36a7
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/getsp.java
@@ -0,0 +1,29 @@
+public class getsp {
+    public static void main(String[] args) {
+	if (args!=null && args.length>0) {
+	    if (args[0].compareTo("-libs")==0) {
+		String prefix="-L";
+		if (args.length>1) prefix=args[1];
+		String lp=System.getProperty("java.library.path");
+		// we're not using StringTokenizer in case the JVM is very crude
+		int i=0,j,k=0;
+		String r=null;
+		String pss=System.getProperty("path.separator");
+		char ps=':';
+		if (pss!=null && pss.length()>0) ps=pss.charAt(0);
+		j=lp.length();
+		while (i<=j) {
+		    if (i==j || lp.charAt(i)==ps) {
+			String lib=lp.substring(k,i);
+			k=i+1;
+			if (lib.compareTo(".")!=0)
+			    r=(r==null)?(prefix+lib):(r+" "+prefix+lib);
+		    }
+		    i++;
+		}
+		if (r!=null) System.out.println(r);
+	    } else
+		System.out.println(System.getProperty(args[0]));
+	}
+    }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/install-sh b/com.oracle.truffle.r.pkgs/rJava/install-sh
new file mode 100755
index 0000000000000000000000000000000000000000..d4744f0c706e3d5d8c4a5957d81ab68b3686589b
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/install-sh
@@ -0,0 +1,269 @@
+#!/bin/sh
+#
+# install - install a program, script, or datafile
+#
+# This originates from X11R5 (mit/util/scripts/install.sh), which was
+# later released in X11R6 (xc/config/util/install.sh) with the
+# following copyright and license.
+#
+# Copyright (C) 1994 X Consortium
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to
+# deal in the Software without restriction, including without limitation the
+# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+# sell copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
+# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
+# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+# Except as contained in this notice, the name of the X Consortium shall not
+# be used in advertising or otherwise to promote the sale, use or other deal-
+# ings in this Software without prior written authorization from the X Consor-
+# tium.
+#
+#
+# FSF changes to this file are in the public domain.
+#
+# Calling this script install-sh is preferred over install.sh, to prevent
+# `make' implicit rules from creating a file called install from it
+# when there is no Makefile.
+#
+# This script is compatible with the BSD install script, but was written
+# from scratch.  It can only install one file at a time, a restriction
+# shared with many OS's install programs.
+
+
+# set DOITPROG to echo to test this script
+
+# Don't use :- since 4.3BSD and earlier shells don't like it.
+doit="${DOITPROG-}"
+
+
+# put in absolute paths if you don't have them in your path; or use env. vars.
+
+mvprog="${MVPROG-mv}"
+cpprog="${CPPROG-cp}"
+chmodprog="${CHMODPROG-chmod}"
+chownprog="${CHOWNPROG-chown}"
+chgrpprog="${CHGRPPROG-chgrp}"
+stripprog="${STRIPPROG-strip}"
+rmprog="${RMPROG-rm}"
+mkdirprog="${MKDIRPROG-mkdir}"
+
+transformbasename=""
+transform_arg=""
+instcmd="$mvprog"
+chmodcmd="$chmodprog 0755"
+chowncmd=""
+chgrpcmd=""
+stripcmd=""
+rmcmd="$rmprog -f"
+mvcmd="$mvprog"
+src=""
+dst=""
+dir_arg=""
+
+while [ x"$1" != x ]; do
+    case $1 in
+	-c) instcmd="$cpprog"
+	    shift
+	    continue;;
+
+	-d) dir_arg=true
+	    shift
+	    continue;;
+
+	-m) chmodcmd="$chmodprog $2"
+	    shift
+	    shift
+	    continue;;
+
+	-o) chowncmd="$chownprog $2"
+	    shift
+	    shift
+	    continue;;
+
+	-g) chgrpcmd="$chgrpprog $2"
+	    shift
+	    shift
+	    continue;;
+
+	-s) stripcmd="$stripprog"
+	    shift
+	    continue;;
+
+	-t=*) transformarg=`echo $1 | sed 's/-t=//'`
+	    shift
+	    continue;;
+
+	-b=*) transformbasename=`echo $1 | sed 's/-b=//'`
+	    shift
+	    continue;;
+
+	*)  if [ x"$src" = x ]
+	    then
+		src=$1
+	    else
+		# this colon is to work around a 386BSD /bin/sh bug
+		:
+		dst=$1
+	    fi
+	    shift
+	    continue;;
+    esac
+done
+
+if [ x"$src" = x ]
+then
+	echo "install:	no input file specified"
+	exit 1
+else
+	true
+fi
+
+if [ x"$dir_arg" != x ]; then
+	dst=$src
+	src=""
+	
+	if [ -d $dst ]; then
+		instcmd=:
+		chmodcmd=""
+	else
+		instcmd=mkdir
+	fi
+else
+
+# Waiting for this to be detected by the "$instcmd $src $dsttmp" command
+# might cause directories to be created, which would be especially bad 
+# if $src (and thus $dsttmp) contains '*'.
+
+	if [ -f $src -o -d $src ]
+	then
+		true
+	else
+		echo "install:  $src does not exist"
+		exit 1
+	fi
+	
+	if [ x"$dst" = x ]
+	then
+		echo "install:	no destination specified"
+		exit 1
+	else
+		true
+	fi
+
+# If destination is a directory, append the input filename; if your system
+# does not like double slashes in filenames, you may need to add some logic
+
+	if [ -d $dst ]
+	then
+		dst="$dst"/`basename $src`
+	else
+		true
+	fi
+fi
+
+## this sed command emulates the dirname command
+dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'`
+
+# Make sure that the destination directory exists.
+#  this part is taken from Noah Friedman's mkinstalldirs script
+
+# Skip lots of stat calls in the usual case.
+if [ ! -d "$dstdir" ]; then
+defaultIFS=' 	
+'
+IFS="${IFS-${defaultIFS}}"
+
+oIFS="${IFS}"
+# Some sh's can't handle IFS=/ for some reason.
+IFS='%'
+set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'`
+IFS="${oIFS}"
+
+pathcomp=''
+
+while [ $# -ne 0 ] ; do
+	pathcomp="${pathcomp}${1}"
+	shift
+
+	if [ ! -d "${pathcomp}" ] ;
+        then
+		$mkdirprog "${pathcomp}"
+	else
+		true
+	fi
+
+	pathcomp="${pathcomp}/"
+done
+fi
+
+if [ x"$dir_arg" != x ]
+then
+	$doit $instcmd $dst &&
+
+	if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else true ; fi &&
+	if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else true ; fi &&
+	if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else true ; fi &&
+	if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else true ; fi
+else
+
+# If we're going to rename the final executable, determine the name now.
+
+	if [ x"$transformarg" = x ] 
+	then
+		dstfile=`basename $dst`
+	else
+		dstfile=`basename $dst $transformbasename | 
+			sed $transformarg`$transformbasename
+	fi
+
+# don't allow the sed command to completely eliminate the filename
+
+	if [ x"$dstfile" = x ] 
+	then
+		dstfile=`basename $dst`
+	else
+		true
+	fi
+
+# Make a temp file name in the proper directory.
+
+	dsttmp=$dstdir/#inst.$$#
+
+# Move or copy the file name to the temp name
+
+	$doit $instcmd $src $dsttmp &&
+
+	trap "rm -f ${dsttmp}" 0 &&
+
+# and set any options; do chmod last to preserve setuid bits
+
+# If any of these fail, we abort the whole thing.  If we want to
+# ignore errors from any of these, just make sure not to ignore
+# errors from the above "$doit $instcmd $src $dsttmp" command.
+
+	if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else true;fi &&
+	if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else true;fi &&
+	if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else true;fi &&
+	if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else true;fi &&
+
+# Now rename the file to the real destination.
+
+	$doit $rmcmd -f $dstdir/$dstfile &&
+	$doit $mvcmd $dsttmp $dstdir/$dstfile 
+
+fi &&
+
+
+exit 0
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/LGPL.txt b/com.oracle.truffle.r.pkgs/rJava/jri/LGPL.txt
new file mode 100644
index 0000000000000000000000000000000000000000..3b473dbfc06e6c902647af6b363331ac42188ddf
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/LGPL.txt
@@ -0,0 +1,458 @@
+		  GNU LESSER GENERAL PUBLIC LICENSE
+		       Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  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
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/LICENSE b/com.oracle.truffle.r.pkgs/rJava/jri/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..1ca0a22bded5610a67de5310af7fb392bfc7d017
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/LICENSE
@@ -0,0 +1,17 @@
+    JRI - Java/R Interface
+    Copyright (C) 2004-2007 Simon Urbanek  <simon.urbanek@r-project.org>
+
+    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;
+    version 2.1 of the License.
+
+    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 (LGPL.txt); if not, write to the
+    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+    Boston, MA  02110-1301  USA
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/Makefile.all b/com.oracle.truffle.r.pkgs/rJava/jri/Makefile.all
new file mode 100644
index 0000000000000000000000000000000000000000..ad56e5e7fd3f18aa184c298c3759ca13bdeeab05
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/Makefile.all
@@ -0,0 +1,47 @@
+# JRI 0.2   (C) Simon Urbanek
+# This is the actual Makefile - all autconf'ed values should
+# be passed as vars, because we also want to use this for
+# the Windows build that has no autoconf
+#
+# Note: the dependencies are often across directories mainly
+# for historical reasons. The Java sources are actually compiled
+# by the Makefile in the src directory, although they are here,
+# because they originally belonged to src.
+
+EX_JAVA=$(wildcard examples/*.java)
+EX_CLASS=$(EX_JAVA:%.java=%.class)
+
+JFLAGS+=-target 1.6 -source 1.6
+
+TARGETS=src/JRI.jar $(JRILIB) $(EX_CLASS)
+
+all: $(TARGETS)
+
+src/JRI.jar:
+	$(MAKE) -C src JRI.jar
+
+src/${JRILIB}:
+	$(MAKE) -C src $(JRILIB)
+
+$(JRILIB): src/$(JRILIB)
+	rm -f $@
+	cp $< $@
+
+examples/%.class: examples/%.java src/JRI.jar
+	$(JAVAC) $(JFLAGS) -classpath src/JRI.jar -d examples $<
+
+clean:
+	$(MAKE) -C src clean
+	rm -rf $(TARGETS) *~ examples/*.class
+
+examples: $(EX_CLASS)
+
+JRI_JDOCSRC=$(wildcard *.java)
+
+doc:	$(JRI_JDOCSRC)
+	rm -rf JavaDoc
+	mkdir JavaDoc
+	$(JAVA)doc -d JavaDoc -author -version -breakiterator -link http://java.sun.com/j2se/1.4.2/docs/api $^
+
+.PHONY: clean all examples doc
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/Makefile.in b/com.oracle.truffle.r.pkgs/rJava/jri/Makefile.in
new file mode 100644
index 0000000000000000000000000000000000000000..7ccbfca411ed64cfb5760e0588bfe39a6e3f233c
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/Makefile.in
@@ -0,0 +1,13 @@
+# JRI - Java/R Interface      experimental!
+#--------------------------------------------------------------------------
+# See Makefile.all for the actual building process
+
+# The values are all auto-configured
+RHOME=@R_HOME@
+JAVAC=@JAVAC@
+JAVAH=@JAVAH@
+JAVA=@JAVA_PROG@
+
+JRILIB=@JNIPREFIX@jri@JNISO@
+
+include Makefile.all
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/Makefile.win b/com.oracle.truffle.r.pkgs/rJava/jri/Makefile.win
new file mode 100644
index 0000000000000000000000000000000000000000..69770f5a56751f95dbe34d65ef36e6ffa29db940
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/Makefile.win
@@ -0,0 +1,15 @@
+# Windows-specific part of the Makefile
+
+include src/Makefile.wconf
+include Makevars.win
+
+windows.all: all run.bat
+
+$(RHOME)/src/gnuwin32/libR.a:
+	make -C $(RHOME)/src/gnuwin32 libR.a
+
+run.bat: jri.dll
+	echo "set PATH=%PATH%;$(RHOME)\\bin;$(RHOME)\\lib" > run.bat
+	echo "$(JAVA_PROG) -cp .;examples;JRI.jar;src/JRI.jar rtest \$$*" >> run.bat
+
+include Makefile.all
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/Makevars.win b/com.oracle.truffle.r.pkgs/rJava/jri/Makevars.win
new file mode 100644
index 0000000000000000000000000000000000000000..24a7a15c0252992e7aa5e46a9b976d5d44f64ed5
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/Makevars.win
@@ -0,0 +1,17 @@
+R_HOME=$(RHOME)
+JAVA_HOME=$(JAVAHOME)
+JAVAINC=-I$(JAVAHOME)/include -I$(JAVAHOME)/include/win32
+RINC=-I$(R_HOME)/include
+JNISO=.dll
+JAVA_LIBS=-Lwin32 -ljvm
+JNILD=-shared $(JAVA_LIBS) -L$(RHOME)/src/gnuwin32 -L$(RHOME)/bin$(R_ARCH) -lR -Wl,--kill-at
+CFLAGS+=-DWin32 -D_JNI_IMPLEMENTATION_
+JAVA_PROG=$(JAVAHOME)/bin/java
+JAVA=$(JAVAHOME)/bin/java
+JAVAC=$(JAVAHOME)/bin/javac
+JAVAH=$(JAVAHOME)/bin/javah
+JAR=$(JAVAHOME)/bin/jar
+JRIDEPS=win32/libjvm.dll.a
+JNIPREFIX=
+PLATFORMT=run.bat
+JRILIB=jri.dll
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/Mutex.java b/com.oracle.truffle.r.pkgs/rJava/jri/Mutex.java
new file mode 100644
index 0000000000000000000000000000000000000000..f447ab488d9f96fa97eec37518d95deea9acb3c0
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/Mutex.java
@@ -0,0 +1,112 @@
+package org.rosuda.JRI;
+
+/** This class implements a (not so) simple mutex. The initial state of the mutex is unlocked. */
+public class Mutex {
+    public static boolean verbose=false;
+
+    /** defines the current mutex state */
+    private boolean locked=false;
+
+    /** thread that locked this mutex (used for simple deadlock-detection) */
+    private Thread lockedBy=null;
+
+    /** locks the mutex. If the mutex is already locked, waits until the mutex becomes free. Make sure the same thread doesn't issue two locks, because that will cause a deadlock. Use {@link #safeLock()} instead if you wish to detect such deadlocks. */
+    public synchronized void lock()
+    {
+        while (locked) {
+            if (lockedBy==Thread.currentThread())
+                System.err.println("FATAL ERROR: org.rosuda.JRI.Mutex detected a deadlock! The application is likely to hang indefinitely!");
+            if (verbose)
+                System.out.println("INFO: "+toString()+" is locked by "+lockedBy+", but "+Thread.currentThread()+" waits for release (no timeout)");
+            try {
+                wait();
+            } catch (InterruptedException e) {
+                if (verbose)
+                    System.out.println("INFO: "+toString()+" caught InterruptedException");
+            }
+        }
+        locked=true;
+        lockedBy=Thread.currentThread();
+        if (verbose) System.out.println("INFO: "+toString()+" locked by "+lockedBy);
+    }
+
+    /** locks the mutex. If the mutex is already locked, waits until the mutex becomes free. Make sure the same thread doesn't issue two locks, because that will cause a deadlock.
+        @param to timeout in milliseconds, see {@link #wait()}.
+        @return <code>true</code> if the lock was successful, <code>false</code> if not
+        */
+    public synchronized boolean lockWithTimeout(long to)
+    {
+        if (locked) {
+            if (lockedBy==Thread.currentThread())
+                System.err.println("FATAL ERROR: org.rosuda.JRI.Mutex detected a deadlock! The application is likely to hang indefinitely!");
+            if (verbose)
+                System.out.println("INFO: "+toString()+" is locked by "+lockedBy+", but "+Thread.currentThread()+" waits for release (timeout "+to+" ms)");
+            try {
+                wait(to);
+            } catch (InterruptedException e) {
+                if (verbose)
+                    System.out.println("INFO: "+toString()+" caught InterruptedException");
+            }
+        }
+        if (!locked) {
+            locked=true;
+            lockedBy=Thread.currentThread();
+            if (verbose) System.out.println("INFO: "+toString()+" locked by "+lockedBy);
+            return true;
+        }
+        if (verbose) System.out.println("INFO: "+toString()+" timeout, failed to obtain lock for "+Thread.currentThread());
+        return false;
+    }
+
+    /** attempts to lock the mutex and returns information about its success.
+        @return 0 if the mutex was locked sucessfully<br>1 if the mutex is already locked by another thread<br>-1 is the mutex is already locked by the same thread (hence a call to {@link #lock()} would cause a deadlock). */
+    public synchronized int tryLock()
+    {
+        if (verbose) System.out.println("INFO: "+toString()+" tryLock by "+Thread.currentThread());
+        if (locked) return (lockedBy==Thread.currentThread())?-1:1;
+        locked=true;
+        lockedBy=Thread.currentThread();
+        if (verbose) System.out.println("INFO: "+toString()+" locked by "+lockedBy);
+        return 0;
+    }
+
+    /** Locks the mutex. It works like {@link #lock()} except that it returns immediately if the same thread already owns the lock. It is safer to use this function rather than {@link #lock()}, because lock can possibly cause a deadlock which won't be resolved.
+        @return <code>true</code> is the mutex was successfully locked, <code>false</code> if deadlock was detected (i.e. the same thread has already the lock). */
+    public synchronized boolean safeLock()
+    {
+        if (locked && lockedBy==Thread.currentThread()) {
+            if (verbose) System.out.println("INFO: "+toString()+" unable to provide safe lock for "+Thread.currentThread());
+            return false;
+        }
+        lock();
+        return true;
+    }
+
+    /** Locks the mutex. It works like {@link #lockWithTimeout(long)} except that it returns immediately if the same thread already owns the lock. It is safer to use this function rather than {@link #lockWithTimeout(long)}, because lock can possibly cause a deadlock which won't be resolved.
+        @return <code>true</code> is the mutex was successfully locked, <code>false</code> if deadlock was detected or timeout elapsed. */
+    public synchronized boolean safeLockWithTimeout(long to)
+    {
+        if (locked && lockedBy==Thread.currentThread()) {
+            if (verbose) System.out.println("INFO: "+toString()+" unable to provide safe lock (deadlock detected) for "+Thread.currentThread());
+            return false;
+        }
+        return lockWithTimeout(to);
+    }
+
+    /** unlocks the mutex. It is possible to unlock an unlocked mutex, but a warning may be issued. */
+    public synchronized void unlock()
+    {
+        if (locked && lockedBy!=Thread.currentThread())
+            System.err.println("WARNING: org.rosuda.JRI.Mutex was unlocked by other thread than locked! This may soon lead to a crash...");
+        locked=false;
+        if (verbose) System.out.println("INFO: "+toString()+" unlocked by "+Thread.currentThread());
+
+        // notify just 1 in case more of them are waiting
+        notify();
+    }
+
+    public String toString()
+    {
+        return super.toString()+"["+((locked)?"":"un")+"locked"+((!locked)?"":(", by "+((lockedBy==Thread.currentThread())?"current":"another")+" thread"))+"]";
+    }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/NEWS b/com.oracle.truffle.r.pkgs/rJava/jri/NEWS
new file mode 100644
index 0000000000000000000000000000000000000000..55dda70728af0d23004e1b3bdf5752943b5c7dfa
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/NEWS
@@ -0,0 +1,154 @@
+ NEWS/ChangeLog for JRI
+--------------------------
+
+0.5-5	(under development)
+    o	fix compilation in parallel using the -j switch for GNU Make
+    o	some more Win64 fixes
+
+0.5-4	2010-09-17
+    o	added more options to rniStop() on unix and changed the
+	default to use interrupt flags instead of signals since
+	signals cause problems in some JVM implmentations. The
+	previous behavior can be achieved by rniStop(1).
+
+0.5-3	2010-09-02
+    o	fixed changed by the Win64 support which broke some other OSes by
+	using sign extension when converting to long storage.
+
+    o	avoid the use of the sign of pointers for signaling. Note
+	that rniEval() now returns 0 on error and not -1 or -2. The
+	old behavior was undocumented (and dangerous) and thus should
+	not be relied upon. (fixes #172)
+
+0.5-2	2010-04-28
+    o	fixed handling of NAs in strings - they are now correctly
+	converted to <null>s on the Java side.
+
+	IMPORTANT: previously NAs would come as the string "NA"
+	from R which is incorrect since it is not distinguishable from
+	a literal "NA" string. Code that deals with NAs must be prepared
+	to receive nulls in string arrays (note that nulls where
+	correctly converted to NA string, it's just that incoming
+	string were not converted).
+
+	(Thanks to Stephan Wahlbrink for pointing out the inconsistency)
+
+    o	multiple fixes to Windows support: common command line
+	arguments are now correctly processed, sub-architectures are
+	supported, Win64 is now also supported
+
+0.5-1	2010-03-16
+   o	API 1.10: rniAssign now returns boolean to denote success/failure
+
+   o	numerous bug fixes and additions
+
+0.5-0	2009-08-22
+    o	API 1.9: added rniPreserve, rniRelease, rniParentEnv, rniFindVar,
+	         rniListEnv, rniSpecialObject, rniPrintValue,
+		 rniGetRawArray, rniPutRawArray, rniGetAttrNames methods
+		 added jriLoaded field (boolean)
+
+    o	new REngine-based API (org.rosuda.REngine.JRI.JRIEngine)
+	has been created - this allows the same code to interface
+	JRI or Rserve without re-compilation
+
+	Note: the JAR files are currently shipped separately from the JRI
+	installation and can be obtained from
+	http://rforge.net/JRI/files/
+
+    o	proxy references are now preserved until finalized
+
+    o	if jri.ignore.ule=yes property is set, JRI will not abort on
+	failing to load the JRI library (UnsatisfiedLinkException).
+	This can be used by GUIs to display a more meaningful message
+	instead of abort. The jriLoaded flag is false in that case.
+
+
+0.4-2
+    o	declare string encoding as UTF-8 and convert incoming strings
+	to UTF-8 if possible (R >= 2.7.0 required).
+
+0.4-1	(part of rJava 0.5-1 and later)
+    o	fixed configuration to work with multi-arch builds
+
+0.4-0	2007-08-22 (part of rJava 0.5-0)
+    o	adapt to changes in R-devel
+
+    o	add -I. to CFLAGS for compatibility (thanks to BDR)
+
+    o	added RConsoleOuputStream class
+
+    o	API 1.8: added rniPrint, added int oType parameter to the
+	rWriteConsole callback
+
+    o	work around broken MinGW runtimes
+
+    o	allow JRI to hook into a running R process (and thusly provide
+	rJava with callbacks)
+
+    o	added: inMainRThread(), isStandAlone()
+
+    o	include configure in SVN and don't rebuild it on mkdist
+
+0.3-7	2006-01-14
+    o	make sure rniJavaToXref creates a global reference
+
+    o	API 1.7: rniCons can accept two new arguments: tag and lang
+	rniLCons was added
+
+    o	assign now supports raw REXPs (XT_NONE)
+
+    o	createRJavaRef was added to create jobjRef R objects from
+	Java objects
+
+0.3-6	2006-11-29
+    o	adapted to API change in R-devel
+
+    o	fixed double-inclusion of JFLAGS which throws off GIJ
+
+0.3-5	2006-10-06
+    o	remove variadic macros to be compatible with compilers
+	that don't support C99
+
+0.3-4	2006-09-14
+    o	updated Makefiles to force 1.4 target and sources
+
+0.3-3	2006-09-12
+    o	fixed API version in Java sources and added version check
+	to examples
+
+0.3-2	2006-09-11
+    o	New API (1.6): add handling of boolean type
+
+0.3-1	2006-08-31
+
+0.3-0	2006-05-31
+    o	New API (1.5) entries: rniGetTAG, rniInherits,
+	rniGetSymbolName, rniInstallName
+	allows handling of symbols, named lists and inheritance
+
+    o	fixed/improved REXP, RList and RFactor
+
+0.2-5	2006-05-08
+    o	Use configure to detect CStackXXX and R_SignalHandlers
+	set the latter to 0 if present (solves threading issues)
+
+0.2-4	2006-05-03
+    o	added support for pre-configuration passed from rJava
+
+0.2-3	2006-04-20
+    o	fix warnings and issues with R 2.3.0
+
+0.2-2	2006-04-11
+    o	licensed under LGPL
+
+0.2-1	2006-03-07
+    o	fixed Java detection, fixed eval double-unlock,
+	use R shlib flags, added FreeBSD support
+
+0.2-0	2005-12-19
+    o	switched to autoconf process for configuration/installation 
+
+0.1-0
+    o	First JRI release
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/RBool.java b/com.oracle.truffle.r.pkgs/rJava/jri/RBool.java
new file mode 100644
index 0000000000000000000000000000000000000000..991f4d570d1467d51c1be352b195298ef67c8d91
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/RBool.java
@@ -0,0 +1,32 @@
+package org.rosuda.JRI;
+
+// JRclient library - client interface to Rserve, see http://www.rosuda.org/Rserve/
+// Copyright (C) 2004 Simon Urbanek
+// --- for licensing information see LICENSE file in the original JRclient distribution ---
+
+/** Implementation of tri-state logical data type in R.
+    The three states are TRUE, FALSE and NA. To obtain truly boolean
+    value, you'll need to use {@link #isTRUE} or {@link #isFALSE} since there is
+    no canonical representation of RBool in boolean
+
+    @version $Id: RBool.java 2720 2007-03-15 17:35:42Z urbanek $
+*/
+public class RBool extends Object {
+    int val;
+
+    public RBool(boolean b) {
+	val=(b)?1:0;
+    };
+    public RBool(RBool r) {
+	val=r.val;
+    };
+    public RBool(int i) { /* 0=FALSE, 2=NA, anything else = TRUE */
+	val=(i==0||i==2)?i:1;
+    };
+
+    public boolean isNA() { return (val==2); };
+    public boolean isTRUE() { return (val==1); };
+    public boolean isFALSE() { return (val==0); };
+
+    public String toString() { return (val==0)?"FALSE":((val==2)?"NA":"TRUE"); };
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/RConsoleOutputStream.java b/com.oracle.truffle.r.pkgs/rJava/jri/RConsoleOutputStream.java
new file mode 100644
index 0000000000000000000000000000000000000000..9773ade4ed4910ed4586cc73885206fd79a2dd7f
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/RConsoleOutputStream.java
@@ -0,0 +1,43 @@
+// RConsoleOutputStream, part of Java/R Interface
+//
+// (C)Copyright 2007 Simon Urbanek
+//
+// For licensing terms see LICENSE in the root if the JRI distribution
+
+package org.rosuda.JRI;
+
+import java.io.OutputStream;
+import java.io.IOException;
+
+/** RConsoleOutputStream provides an OutputStream which causes its output to be written to the R console. It is a pseudo-stream as there is no real descriptor connected to the R console and thusly it is legal to have multiple console streams open. The synchonization happens at the RNI level.<p>Note that stdout/stderr are not connected to the R console by default, so one way of using this stream is to re-route Java output to R console:<pre>
+System.setOut(new PrintStream(new RConsoleOutputStream(engine, 0)));
+System.setErr(new PrintStream(new RConsoleOutputStream(engine, 1)));
+</pre>
+
+@since JRI 0.4-0
+*/
+public class RConsoleOutputStream extends OutputStream {
+	Rengine eng;
+	int oType;
+	boolean isOpen;
+	
+	/** opens a new output stream to R console
+		@param eng R engine
+		@param oType output type (0=regular, 1=error/warning) */
+	public RConsoleOutputStream(Rengine eng, int oType) {
+		this.eng = eng;
+		this.oType = oType;
+		isOpen = true;
+	}
+	
+	public void write(byte[] b, int off, int len) throws IOException {
+		if (!isOpen) throw new IOException("cannot write to a closed stream");
+		if (eng == null) throw new IOException("missing R engine");
+		String s = new String(b, off, len);
+		eng.rniPrint(s, oType);
+	}
+	
+	public void write(byte[] b) throws IOException { write(b, 0, b.length); }
+	public void write(int b) throws IOException { write(new byte[] { (byte)(b&255) }); }
+	public void close() throws IOException { isOpen=false; eng=null; }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/README b/com.oracle.truffle.r.pkgs/rJava/jri/README
new file mode 100644
index 0000000000000000000000000000000000000000..247488b1f220c2207e2b9be5d9f11e09959b7075
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/README
@@ -0,0 +1,73 @@
+ JRI - Java/R Interface
+------------------------
+
+ Copyright (C) 2006  Simon Urbanek  <simon.urbanek@r-project.org>
+
+ 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;
+ version 2.1 of the License.
+
+ 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 (LGPL.txt).
+
+
+This package contains code that is necessary to run
+R as a single thread of a Java application. It provides
+callback that make it possible to run R in REPL mode
+thus giving the Java application full access to the
+console.
+
+Currently the API is very, very low-level, comparable
+to the C level interface to R. Convenience methods for
+mid to high-level are planned, but not implemented yet.
+
+For R-to-Java interface, use rJava package which
+integrates fine with JRI. rJava hooks into the same
+JVM, so both are opertaing in the same environment.
+
+Java to R: JRI
+R to Java: rJava
+
+ How to compile
+----------------
+
+As of JRI 0.2 everything is 'autoconf'igured.
+
+1) Make sure JDK 1.4 or higher is installed (on Linux
+   1.5 or later must be installed) and all java
+   commands are ont the PATH. Alternatively you can
+   set JAVA_HOME instead.
+2) ./configure
+3) make
+
+On Windows run "sh configure.win" instead of configure
+
+Note for Windows users: you will need the same tools
+that are necessary to build R, i.e. the /bin tools
+and MinGW. See R for details.
+
+ How to use JRI
+----------------
+
+There are two Java examples in the JRI directory:
+
+rtest.java   - demonstrates the use of the low-level
+               interface to construct and retrieve
+               complex R objects. It also demonstrates
+               how to setup callbacks for handling of
+               the console.
+rtest2.java  - a very simple console using stdin as input
+               and a TextField for output.
+
+The examples can be run with
+./run rtest
+./run rtest2
+
+On Windows use run.bat instead
+
+---
+04/2006 Simon Urbanek
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REXP.java b/com.oracle.truffle.r.pkgs/rJava/jri/REXP.java
new file mode 100644
index 0000000000000000000000000000000000000000..3e5748dc94d4559742a9b9ba70a565e62f865ed5
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REXP.java
@@ -0,0 +1,762 @@
+package org.rosuda.JRI;
+
+import java.util.Vector;
+
+/**
+ * This class encapsulates and caches R objects as returned from R. Currently it
+ * only converts certain SEXPs references from R into Java obejcts, but
+ * eventually bi-directional support should be added. The currently supported
+ * objects are string, integer and numeric vectors. All other types can be
+ * accessed only using {@link #xp} reference and RNI methods.
+ */
+public class REXP {
+	/** xpression type: NULL */
+	public static final int XT_NULL = 0;
+
+	/** xpression type: integer */
+	public static final int XT_INT = 1;
+
+	/** xpression type: double */
+	public static final int XT_DOUBLE = 2;
+
+	/** xpression type: String */
+	public static final int XT_STR = 3;
+
+	/** xpression type: language construct (currently content is same as list) */
+	public static final int XT_LANG = 4;
+
+	/** xpression type: symbol (content is symbol name: String) */
+	public static final int XT_SYM = 5;
+
+	/** xpression type: RBool */
+	public static final int XT_BOOL = 6;
+
+	/** xpression type: Vector */
+	public static final int XT_VECTOR = 16;
+
+	/** xpression type: RList */
+	public static final int XT_LIST = 17;
+	
+	/**
+	 * xpression type: closure (there is no java class for that type (yet?).
+	 * currently the body of the closure is stored in the content part of the
+	 * REXP. Please note that this may change in the future!)
+	 */
+	public static final int XT_CLOS = 18;
+
+	/** xpression type: int[] */
+	public static final int XT_ARRAY_INT = 32;
+
+	/** xpression type: double[] */
+	public static final int XT_ARRAY_DOUBLE = 33;
+
+	/** xpression type: String[] (currently not used, Vector is used instead) */
+	public static final int XT_ARRAY_STR = 34;
+
+	/** internal use only! this constant should never appear in a REXP */
+	public static final int XT_ARRAY_BOOL_UA = 35;
+
+	/** xpression type: RBool[] */
+	public static final int XT_ARRAY_BOOL = 36;
+
+	/** xpression type: int[] to be interpreted as boolean */
+	public static final int XT_ARRAY_BOOL_INT = 37;
+
+	/** xpression type: unknown; no assumptions can be made about the content */
+	public static final int XT_UNKNOWN = 48;
+
+	/** xpression type: pure reference, no internal type conversion performed */
+	public static final int XT_NONE = -1;
+
+	/**
+	 * xpression type: RFactor; this XT is internally generated (ergo is does
+	 * not come from Rsrv.h) to support RFactor class which is built from
+	 * XT_ARRAY_INT
+	 */
+	public static final int XT_FACTOR = 127;
+
+	/* internal SEXP types in R - taken directly from Rinternals.h */
+	public static final int NILSXP = 0; /* nil = NULL */
+
+	public static final int SYMSXP = 1; /* symbols */
+
+	public static final int LISTSXP = 2; /* lists of dotted pairs */
+
+	public static final int CLOSXP = 3; /* closures */
+
+	public static final int ENVSXP = 4; /* environments */
+
+	public static final int PROMSXP = 5; /*
+											 * promises: [un]evaluated closure
+											 * arguments
+											 */
+
+	public static final int LANGSXP = 6; /*
+											 * language constructs (special
+											 * lists)
+											 */
+
+	public static final int SPECIALSXP = 7; /* special forms */
+
+	public static final int BUILTINSXP = 8; /* builtin non-special forms */
+
+	public static final int CHARSXP = 9; /*
+											 * "scalar" string type (internal
+											 * only)
+											 */
+
+	public static final int LGLSXP = 10; /* logical vectors */
+
+	public static final int INTSXP = 13; /* integer vectors */
+
+	public static final int REALSXP = 14; /* real variables */
+
+	public static final int CPLXSXP = 15; /* complex variables */
+
+	public static final int STRSXP = 16; /* string vectors */
+
+	public static final int DOTSXP = 17; /* dot-dot-dot object */
+
+	public static final int ANYSXP = 18; /* make "any" args work */
+
+	public static final int VECSXP = 19; /* generic vectors */
+
+	public static final int EXPRSXP = 20; /* expressions vectors */
+
+	public static final int BCODESXP = 21; /* byte code */
+
+	public static final int EXTPTRSXP = 22; /* external pointer */
+
+	public static final int WEAKREFSXP = 23; /* weak reference */
+
+	public static final int RAWSXP = 24; /* raw bytes */
+
+	public static final int S4SXP = 25; /* S4 object */
+
+	public static final int FUNSXP = 99; /* Closure or Builtin */
+
+	/**
+	 * Engine which this EXP was obtained from. EXPs are valid only for the
+	 * engine they were obtained from - it's illegal to mix EXP between engines.
+	 * There is a speacial case when the engine may be null - if a REXP creating
+	 * was requested but deferred until an engine is available.
+	 */
+	Rengine eng;
+
+	/**
+	 * native reference to the SEXP represented in R. It's usually a pointer,
+	 * but can be any handle obtained from the engine. This reference can be
+	 * used when calling RNI commands directly.
+	 */
+	public long xp;
+
+	/**
+	 * native type of the represented expression (see ...SXP constants in R).
+	 * Please note that this type is cached and may have changed in the
+	 * meantime. If the possibility of changing type exists (mainly list/lang)
+	 * then use rniExpType to make sure
+	 */
+	public int rtype;
+
+	/**
+	 * create a REXP directly from a R SEXP reference. SEXP types STRSXP, INTSXP
+	 * and REALSXP are automatically converted. All others are represented as
+	 * SEXP references only.
+	 */
+	public REXP(Rengine re, long exp) {
+		this(re, exp, true);
+	}
+	
+	protected void finalize() throws Throwable {
+		try {
+			if (Xt == XT_NONE && xp != 0 && eng != null) // release underlying R obejct if it was preserved
+				eng.rniRelease(xp);
+		} finally {
+			super.finalize();
+		}
+	}
+
+	public REXP(Rengine re, long exp, boolean convert) {
+		eng = re;
+		xp = exp;
+		rtype = re.rniExpType(xp);
+		//System.out.println("["+rtype+"@"+exp+","+convert+"]");
+
+		if (!convert) {
+			Xt = XT_NONE;
+			if (re != null && xp != 0)
+				re.rniPreserve(xp); // preserve the object so it doesn't get garbage-collected while we are referencing it
+			return;
+		}
+				
+		if (rtype == STRSXP) {
+			String[] s = re.rniGetStringArray(xp);
+			if (s != null && s.length == 1) {
+				cont = s[0];
+				Xt = XT_STR;
+			} else {
+				cont = s;
+				Xt = XT_ARRAY_STR;
+			}
+		} else if (rtype == INTSXP) {
+			cont = null;
+			if (re.rniInherits(xp, "factor")) {
+				long levx = re.rniGetAttr(xp, "levels");
+				if (levx != 0) {
+					String[] levels = null;
+					// we're using low-lever calls here (FIXME?)
+					int rlt = re.rniExpType(levx);
+					if (rlt == STRSXP) {
+						levels = re.rniGetStringArray(levx);
+						int[] ids = re.rniGetIntArray(xp);
+						cont = new RFactor(ids, levels, 1);
+						Xt = XT_FACTOR;
+					}
+				}
+			}
+			// if it's not a factor, then we use int[] instead
+			if (cont == null ) {
+				cont = re.rniGetIntArray(xp);
+				Xt = XT_ARRAY_INT;
+			}
+		} else if (rtype == REALSXP) {
+			cont = re.rniGetDoubleArray(xp);
+			Xt = XT_ARRAY_DOUBLE;
+		} else if (rtype == LGLSXP) {
+		    cont = re.rniGetBoolArrayI(xp);
+		    Xt = XT_ARRAY_BOOL_INT;
+		} else if (rtype == VECSXP) {
+			long[] l = re.rniGetVector(xp);
+			cont = new RVector();
+			int i = 0;
+			//System.out.println("VECSXP, length="+l.length);
+			Xt = XT_VECTOR;
+			while (i < l.length)
+				((RVector)cont).addElement(new REXP(re, l[i++]));
+			long na = re.rniGetAttr(xp, "names");
+			if (na!=0 && re.rniExpType(na)==STRSXP)
+				((RVector)cont).setNames(re.rniGetStringArray(na));
+		} else if (rtype == LISTSXP) {
+			long car = re.rniCAR(xp);
+			long cdr = re.rniCDR(xp);
+			long tag = re.rniTAG(xp);
+
+			REXP cdrx = (cdr==0 || re.rniExpType(cdr)!=LISTSXP)?null:new REXP(re,re.rniCDR(xp));
+			cont = new RList(new REXP(re,car), (tag==0)?null:new REXP(re,tag), cdrx);
+			Xt = XT_LIST;
+		} else if (rtype == SYMSXP) {
+			cont = re.rniGetSymbolName(xp);
+			Xt = XT_SYM;
+		} else
+			Xt = XT_NULL;
+		
+		//System.out.println("new REXP: "+toString());
+	}
+
+	/** xpression type */
+	int Xt;
+
+	/** attribute xpression or <code>null</code> if none */
+	REXP attr;
+
+	/** content of the xpression - its object type is dependent of {@link #Xt} */
+	Object cont;
+
+	/** cached binary length; valid only if positive */
+	long cachedBinaryLength = -1;
+
+	/** construct a new, empty (NULL) expression w/o attribute */
+	public REXP() {
+		Xt = XT_NULL;
+		attr = null;
+		cont = null;
+	}
+
+	/**
+	 * construct a new xpression of type t and content o, but no attribute
+	 * 
+	 * @param t
+	 *            xpression type (XT_...)
+	 * @param o
+	 *            content
+	 */
+	public REXP(int t, Object o) {
+		Xt = t;
+		cont = o;
+		attr = null;
+	}
+
+	/**
+	 * construct a new xpression of type t, content o and attribute at
+	 * 
+	 * @param t
+	 *            xpression type
+	 * @param o
+	 *            content
+	 * @param at
+	 *            attribute
+	 */
+	public REXP(int t, Object o, REXP at) {
+		Xt = t;
+		cont = o;
+		attr = at;
+	}
+
+	/**
+	 * construct a new xpression of type XT_ARRAY_DOUBLE and content val
+	 * 
+	 * @param val
+	 *            array of doubles to store in the REXP
+	 */
+	public REXP(double[] val) {
+		this(XT_ARRAY_DOUBLE, val);
+	}
+
+	/**
+	 * construct a new xpression of type XT_ARRAY_INT and content val
+	 * 
+	 * @param val
+	 *            array of integers to store in the REXP
+	 */
+	public REXP(int[] val) {
+		this(XT_ARRAY_INT, val);
+	}
+
+	/**
+	 * construct a new xpression of type XT_ARRAY_INT and content val
+	 * 
+	 * @param val
+	 *            array of integers to store in the REXP
+	 */
+	public REXP(String[] val) {
+		this(XT_ARRAY_STR, val);
+	}
+
+    /** construct new expression with the contents of a boolean vector
+	@since JRI 0.3-2
+	@param val contents */
+	public REXP(boolean[] val) {
+	    Xt = XT_ARRAY_BOOL_INT;
+	    if (val==null) { cont = new int[0]; } else {
+		int [] ic = new int[val.length];
+		int i=0;
+		while (i<val.length) { ic[i]=val[i]?1:0; i++; }
+		cont = ic;
+	    }
+	    attr = null;
+	}
+
+	/**	get attributes of the REXP. In R every object can have attached attribute
+		xpression. Some more complex structures such as classes are built that
+		way.
+		@return attribute xpression or <code>null</code> if there is none associated
+		@since JRI 0.3, replaces <code>getAttribute()</code> but should be avoided if possible - use {@link #getAttribute(String)} instead.
+		*/
+	public REXP getAttributes() {
+		return attr;
+	}
+
+	/** retrieve a specific attribute.<br>
+		<b>Note:</b> the current representation fetches the attribute ad-hoc, so it breaks the assumption that the expression is no longer accessed after the constructor was called. This should change in the future.
+		@param name name of the attribute
+		@return REXP containing the attribute or <code>null</code> if the attribute doesn't exist. The conversion flag is inherited from this REXP.
+		@since JRI 0.3
+		*/
+	public REXP getAttribute(String name) {
+		// FIXME: we could do some caching if attr is not null ...
+		long aref = eng.rniGetAttr(xp, name);
+		if (aref==0) return null;
+		return new REXP(eng, aref, (Xt != XT_NONE));
+	}
+	
+	/**
+	 * get raw content. Use as... methods to retrieve contents of known type.
+	 * 
+	 * @return content of the REXP
+	 */
+	public Object getContent() {
+		return cont;
+	}
+
+	/**
+	 * get xpression type (see XT_.. constants) of the content. It defines the
+	 * type of the content object.
+	 * 
+	 * @return xpression type
+	 */
+	public int getType() {
+		return Xt;
+	}
+
+	/**
+	 * Obtains R engine object which supplied this REXP.
+	 * 
+	 * @returns {@link Rengine} object
+	 */
+	Rengine getEngine() {
+		return eng;
+	};
+
+	/** return the first element of a character vector if this REXP is a character vector of length 1 or more, return <code>null</code> otherwise */
+	public String asString() {
+		if (cont == null)
+			return null;
+		if (Xt == XT_STR)
+			return (String) cont;
+		if (Xt == XT_ARRAY_STR) {
+			String[] sa = (String[]) cont;
+			return (sa.length > 0) ? sa[0] : null;
+		}
+		return null;
+	}
+
+	/** return the name of the symbol represented by this REXP if is it a symbol or <code>null</code> otherwise */
+	public String asSymbolName() {
+		return (Xt == XT_SYM)?((String) cont):null;
+	}
+	
+	/** return the contents of this REXP as an array of strings if this REXP is a character vector, return <code>null</code> otherwise */
+	public String[] asStringArray() {
+		if (cont == null)
+			return null;
+		if (Xt == XT_STR) {
+			String[] sa = new String[1];
+			sa[0] = (String) cont;
+			return sa;
+		}
+		if (Xt == XT_ARRAY_STR)
+			return (String[]) cont;
+		return null;
+	}
+
+	/**
+	 * get content of the REXP as int (if it is one)
+	 * 
+	 * @return int content or 0 if the REXP is no integer
+	 */
+	public int asInt() {
+		if (Xt == XT_ARRAY_INT) {
+			int i[] = (int[]) cont;
+			if (i != null && i.length > 0)
+				return i[0];
+		}
+		return (Xt == XT_INT) ? ((Integer) cont).intValue() : 0;
+	}
+
+	/**
+	 * get content of the REXP as double (if it is one)
+	 * 
+	 * @return double content or 0.0 if the REXP is no double
+	 */
+	public double asDouble() {
+		if (Xt == XT_ARRAY_DOUBLE) {
+			double d[] = (double[]) cont;
+			if (d != null && d.length > 0)
+				return d[0];
+		}
+		return (Xt == XT_DOUBLE) ? ((Double) cont).doubleValue() : 0.0;
+	}
+
+	/**
+	 * get content of the REXP as {@link Vector} (if it is one)
+	 * 
+	 * @return Vector content or <code>null</code> if the REXP is no Vector
+	 */
+	public RVector asVector() {
+		return (Xt == XT_VECTOR) ? (RVector) cont : null;
+	}
+
+	/**
+	 * get content of the REXP as {@link RFactor} (if it is one)
+	 * 
+	 * @return {@link RFactor} content or <code>null</code> if the REXP is no
+	 *         factor
+	 */
+	public RFactor asFactor() {
+		return (Xt == XT_FACTOR) ? (RFactor) cont : null;
+	}
+
+	/**
+	 * get content of the REXP as {@link RList} if the contents is a list or a generic vector
+	 * 
+	 * @return {@link RList} content or <code>null</code> if the REXP is neither a list nor a generic vector
+	 */
+	public RList asList() {
+		return (Xt == XT_LIST) ?
+		(RList) cont :
+		( // for compatibility with Rserve we convert vectors to lists
+		  (Xt == XT_VECTOR) ? new RList((RVector)cont) : null
+		  );
+	}
+
+	/**
+	 * get content of the REXP as {@link RBool} (if it is one)
+	 * 
+	 * @return {@link RBool} content or <code>null</code> if the REXP is no
+	 *         logical value
+	 */
+	public RBool asBool() {
+	    if (Xt == XT_ARRAY_BOOL_INT) {
+		int [] ba = (int[]) cont;
+		return (ba!=null && ba.length>0)?new RBool(ba[0]):null;
+	    }
+	    return (Xt == XT_BOOL) ? (RBool) cont : null;
+	}
+
+	/**
+	 * get content of the REXP as an array of doubles. Array of integers, single
+	 * double and single integer are automatically converted into such an array
+	 * if necessary.
+	 * 
+	 * @return double[] content or <code>null</code> if the REXP is not a
+	 *         array of doubles or integers
+	 */
+	public double[] asDoubleArray() {
+		if (Xt == XT_ARRAY_DOUBLE)
+			return (double[]) cont;
+		if (Xt == XT_DOUBLE) {
+			double[] d = new double[1];
+			d[0] = asDouble();
+			return d;
+		}
+		if (Xt == XT_INT) {
+			double[] d = new double[1];
+			d[0] = ((Integer) cont).doubleValue();
+			return d;
+		}
+		if (Xt == XT_ARRAY_INT) {
+			int[] i = asIntArray();
+			if (i == null)
+				return null;
+			double[] d = new double[i.length];
+			int j = 0;
+			while (j < i.length) {
+				d[j] = (double) i[j];
+				j++;
+			}
+			return d;
+		}
+		return null;
+	}
+
+	/**
+	 * get content of the REXP as an array of integers. Unlike
+	 * {@link #asDoubleArray} <u>NO</u> automatic conversion is done if the
+	 * content is not an array of the correct type, because there is no
+	 * canonical representation of doubles as integers. A single integer is
+	 * returned as an array of the length 1. This method can be also used
+	 * to access a logical array in its integer form (0=FALSE, 1=TRUE, 2=NA).
+	 * 
+	 * @return int[] content or <code>null</code> if the REXP is not a
+	 *         array of integers
+	 */
+	public int[] asIntArray() {
+		if (Xt == XT_ARRAY_INT || Xt == XT_ARRAY_BOOL_INT)
+			return (int[]) cont;
+		if (Xt == XT_INT) {
+			int[] i = new int[1];
+			i[0] = asInt();
+			return i;
+		}
+		return null;
+	}
+
+	/**
+	 * returns the content of the REXP as a matrix of doubles (2D-array:
+	 * m[rows][cols]). This is the same form as used by popular math packages
+	 * for Java, such as JAMA. This means that following leads to desired
+	 * results:<br>
+	 * <code>Matrix m=new Matrix(c.eval("matrix(c(1,2,3,4,5,6),2,3)").asDoubleMatrix());</code>
+	 * 
+	 * @return 2D array of doubles in the form double[rows][cols] or
+	 *         <code>null</code> if the contents is no 2-dimensional matrix of
+	 *         doubles
+	 */
+	public double[][] asDoubleMatrix() {
+		double[] ct = asDoubleArray();
+		if (ct==null) return null;
+		REXP dim = getAttribute("dim");
+		if (dim == null || dim.Xt != XT_ARRAY_INT)
+			return null; // we need dimension attr
+		int[] ds = dim.asIntArray();
+		if (ds == null || ds.length != 2)
+			return null; // matrix must be 2-dimensional
+		int m = ds[0], n = ds[1];
+		double[][] r = new double[m][n];
+		if (ct == null)
+			return null;
+		// R stores matrices as matrix(c(1,2,3,4),2,2) = col1:(1,2), col2:(3,4)
+		// we need to copy everything, since we create 2d array from 1d array
+		int i = 0, k = 0;
+		while (i < n) {
+			int j = 0;
+			while (j < m) {
+				r[j++][i] = ct[k++];
+			}
+			i++;
+		}
+		return r;
+	}
+
+	/** this is just an alias for {@link #asDoubleMatrix()}. */
+	public double[][] asMatrix() {
+		return asDoubleMatrix();
+	}
+
+	/**
+	 * displayable contents of the expression. The expression is traversed
+	 * recursively if aggregation types are used (Vector, List, etc.)
+	 * 
+	 * @return String descriptive representation of the xpression
+	 */
+	public String toString() {
+		StringBuffer sb = new StringBuffer("[" + xtName(Xt) + " ");
+
+		if (attr != null)
+			sb.append("\nattr=" + attr + "\n ");
+		if (Xt == XT_DOUBLE)
+			sb.append((Double) cont);
+		if (Xt == XT_INT)
+			sb.append((Integer) cont);
+		if (Xt == XT_BOOL)
+			sb.append((RBool) cont);
+		if (Xt == XT_FACTOR)
+			sb.append((RFactor) cont);
+		if (Xt == XT_ARRAY_DOUBLE) {
+			double[] d = (double[]) cont;
+			sb.append("(");
+			for (int i = 0; i < d.length; i++) {
+				sb.append(d[i]);
+				if (i < d.length - 1)
+					sb.append(", ");
+				if (i == 99) {
+					sb.append("... (" + (d.length - 100)
+							+ " more values follow)");
+					break;
+				}
+			}
+			sb.append(")");
+		}
+
+		if (Xt == XT_ARRAY_INT) {
+			int[] d = (int[]) cont;
+			sb.append("(");
+			for (int i = 0; i < d.length; i++) {
+				sb.append(d[i]);
+				if (i < d.length - 1)
+					sb.append(", ");
+				if (i == 99) {
+					sb.append("... (" + (d.length - 100)
+							+ " more values follow)");
+					break;
+				}
+			}
+			sb.append(")");
+		}
+
+		if (Xt == XT_ARRAY_BOOL) {
+			RBool[] d = (RBool[]) cont;
+			sb.append("(");
+			for (int i = 0; i < d.length; i++) {
+				sb.append(d[i]);
+				if (i < d.length - 1)
+					sb.append(", ");
+			}
+			sb.append(")");
+		}
+
+		if (Xt == XT_ARRAY_STR) {
+			String[] d = (String[]) cont;
+			sb.append("(");
+			for (int i = 0; i < d.length; i++) {
+				sb.append((d[i] == null) ? "NA" : ("\"" + d[i] + "\""));
+				if (i < d.length - 1)
+					sb.append(", ");
+				if (i == 10 && d.length > 14) {
+					sb.append("... (" + (d.length - 10) + " more values follow)");
+					break;
+				}
+			}
+			sb.append(")");
+		}
+		
+		if (Xt == XT_VECTOR) {
+			Vector v = (Vector) cont;
+			sb.append("(");
+			for (int i = 0; i < v.size(); i++) {
+				sb.append(((REXP) v.elementAt(i)).toString());
+				if (i < v.size() - 1)
+					sb.append(", ");
+			}
+			sb.append(")");
+		}
+
+		if (Xt == XT_STR) {
+			if (cont == null)
+				sb.append("NA");
+			else {
+				sb.append("\"");
+				sb.append((String) cont);
+				sb.append("\"");
+			}
+		}
+
+		if (Xt == XT_SYM) {
+			sb.append((String) cont);
+		}
+
+		if (Xt == XT_LIST || Xt == XT_LANG) {
+			RList l = (RList) cont;
+			sb.append(l.head);
+			sb.append(":");
+			sb.append(l.tag);
+			sb.append(",(");
+			sb.append(l.body); 
+			sb.append(")");
+		}
+
+		if (Xt == XT_NONE) {
+			sb.append("{"+rtype+"}");
+		}
+
+		if (Xt == XT_UNKNOWN)
+			sb.append((Integer) cont);
+		sb.append("]");
+		return sb.toString();
+	}
+
+	public static String quoteString(String s) {
+		// this code uses API introdiced in 1.4 so it needs to be re-written for
+		// earlier JDKs
+		if (s.indexOf('\\') >= 0)
+			s.replaceAll("\\", "\\\\");
+		if (s.indexOf('"') >= 0)
+			s.replaceAll("\"", "\\\"");
+		return "\"" + s + "\"";
+	}
+	
+    /** returns human-readable name of the xpression type as string. Arrays are denoted by a trailing asterisk (*).
+	@param xt xpression type
+	@return name of the xpression type */
+    public static String xtName(int xt) {
+		if (xt==XT_NULL) return "NULL";
+		if (xt==XT_INT) return "INT";
+		if (xt==XT_STR) return "STRING";
+		if (xt==XT_DOUBLE) return "REAL";
+		if (xt==XT_BOOL) return "BOOL";
+		if (xt==XT_ARRAY_INT) return "INT*";
+		if (xt==XT_ARRAY_STR) return "STRING*";
+		if (xt==XT_ARRAY_DOUBLE) return "REAL*";
+		if (xt==XT_ARRAY_BOOL) return "BOOL*";
+		if (xt==XT_ARRAY_BOOL_INT) return "BOOLi*";
+		if (xt==XT_SYM) return "SYMBOL";
+		if (xt==XT_LANG) return "LANG";
+		if (xt==XT_LIST) return "LIST";
+		if (xt==XT_CLOS) return "CLOS";
+		if (xt==XT_VECTOR) return "VECTOR";
+		if (xt==XT_FACTOR) return "FACTOR";
+		if (xt==XT_UNKNOWN) return "UNKNOWN";
+		if (xt==XT_NONE) return "(SEXP)";
+		return "<unknown "+xt+">";
+    }	
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/JRI/JRIEngine.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/JRI/JRIEngine.java
new file mode 100644
index 0000000000000000000000000000000000000000..6743489a4a198ec2f71be1869d55859cd8638697
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/JRI/JRIEngine.java
@@ -0,0 +1,830 @@
+// JRIEngine - REngine-based interface to JRI
+// Copyright(c) 2009 Simon Urbanek
+//
+// Currently it uses low-level calls from org.rosuda.JRI.Rengine, but
+// all REXP representations are created based on the org.rosuda.REngine API
+
+package org.rosuda.REngine.JRI;
+
+import org.rosuda.JRI.Rengine;
+import org.rosuda.JRI.Mutex;
+import org.rosuda.JRI.RMainLoopCallbacks;
+import org.rosuda.REngine.*;
+
+/** <code>JRIEngine</code> is a <code>REngine</code> implementation using JRI (Java/R Interface).
+ <p>
+ Note that at most one JRI instance can exist in a given JVM process, because R does not support multiple threads. <code>JRIEngine</code> itself is thread-safe, so it is possible to invoke its methods from any thread. However, this is achieved by serializing all entries into R, so be aware of possible deadlock conditions if your R code calls back into Java (<code>JRIEngine</code> is re-entrant from the same thread so deadlock issues can arise only with multiple threads inteacting thorugh R). */
+public class JRIEngine extends REngine implements RMainLoopCallbacks {
+	// internal R types as defined in Rinternals.h
+	static final int NILSXP = 0; /* nil = NULL */
+	static final int SYMSXP = 1; /* symbols */
+	static final int LISTSXP = 2; /* lists of dotted pairs */
+	static final int CLOSXP = 3; /* closures */
+	static final int ENVSXP = 4; /* environments */
+	static final int PROMSXP = 5; /* promises: [un]evaluated closure arguments */
+	static final int LANGSXP = 6; /* language constructs */
+	static final int SPECIALSXP = 7; /* special forms */
+	static final int BUILTINSXP = 8; /* builtin non-special forms */
+	static final int CHARSXP = 9; /* "scalar" string type (internal only) */
+	static final int LGLSXP = 10; /* logical vectors */
+	static final int INTSXP = 13; /* integer vectors */
+	static final int REALSXP = 14; /* real variables */
+	static final int CPLXSXP = 15; /* complex variables */
+	static final int STRSXP = 16; /* string vectors */
+	static final int DOTSXP = 17; /* dot-dot-dot object */
+	static final int ANYSXP = 18; /* make "any" args work */
+	static final int VECSXP = 19; /* generic vectors */
+	static final int EXPRSXP = 20; /* expressions vectors */
+	static final int BCODESXP = 21; /* byte code */
+	static final int EXTPTRSXP = 22; /* external pointer */
+	static final int WEAKREFSXP = 23; /* weak reference */
+	static final int RAWSXP = 24; /* raw bytes */
+	static final int S4SXP = 25; /* S4 object */
+	
+	/** minimal JRI API version that is required by this class in order to work properly (currently API 1.10, corresponding to JRI 0.5-1 or higher) */
+	static public final long requiredAPIversion = 0x010a;
+	
+	/** currently running <code>JRIEngine</code> - there can be only one and we store it here. Essentially if it is <code>null</code> then R was not initialized. */
+	static JRIEngine jriEngine = null;
+	
+	/** reference to the underlying low-level JRI (RNI) engine */
+	Rengine rni = null;
+	
+	/** event loop callbacks associated with this engine. */
+	REngineCallbacks callbacks = null;
+	
+	/** mutex synchronizing access to R through JRIEngine.<p> NOTE: only access through this class is synchronized. Any other access (e.g. using RNI directly) is NOT. */
+	Mutex rniMutex = null;
+	
+	// cached pointers of special objects in R
+	long R_UnboundValue, R_NilValue;
+	
+	/** special, global references */
+	public REXPReference globalEnv, emptyEnv, baseEnv, nullValueRef;
+	
+	/** canonical NULL object */
+	public REXPNull nullValue;
+
+	/** class used for wrapping raw pointers such that they are adequately protected and released according to the lifespan of the Java object */
+	class JRIPointer {
+		long ptr;
+		JRIPointer(long ptr, boolean preserve) {
+			this.ptr = ptr;
+			if (preserve && ptr != 0 && ptr != R_NilValue) {
+				boolean obtainedLock = rniMutex.safeLock(); // this will inherently wait for R to become ready
+				try {
+					rni.rniPreserve(ptr);
+				} finally {
+					if (obtainedLock) rniMutex.unlock();
+				}
+			}
+		}
+		
+		protected void finalize() throws Throwable {
+			try {
+				if (ptr != 0 && ptr != R_NilValue) {
+					boolean obtainedLock = rniMutex.safeLock();
+					try {
+						rni.rniRelease(ptr);
+					} finally {
+						if (obtainedLock)
+							rniMutex.unlock();
+					}
+				}
+			} finally {
+				super.finalize();
+			}
+		}	
+		
+		long pointer() { return ptr; }
+	}
+	
+	/** factory method called by <code>engineForClass</code> 
+	 @return new or current engine (new if there is none, current otherwise since R allows only one engine at any time) */
+	public static REngine createEngine() throws REngineException {
+		// there can only be one JRI engine in a process
+		if (jriEngine == null)
+			jriEngine = new JRIEngine();
+		return jriEngine;
+	}
+	
+	public static REngine createEngine(String[] args, REngineCallbacks callbacks, boolean runREPL) throws REngineException {
+		if (jriEngine != null)
+			throw new REngineException(jriEngine, "engine already running - cannot use extended constructor on a running instance");
+		return jriEngine = new JRIEngine(args, callbacks, runREPL);
+	}
+	
+	public Rengine getRni() {
+		return rni;
+	}
+	
+	/** default constructor - this constructor is also used via <code>createEngine</code> factory call and implies --no-save R argument, no callbacks and no REPL.
+	 <p>This is equivalent to <code>JRIEngine(new String[] { "--no-save" }, null, false)</code> */
+	public JRIEngine() throws REngineException {
+		this(new String[] { "--no-save" }, (REngineCallbacks) null, false);
+	}
+	
+	/** create <code>JRIEngine</code> with specified R command line arguments, no callbacks and no REPL.
+	 <p>This is equivalent to <code>JRIEngine(args, null, false)</code> */
+	public JRIEngine(String args[]) throws REngineException {
+		this(args, (REngineCallbacks) null, false);
+	}
+
+	/** creates a JRI engine with specified delegate for callbacks (JRI compatibility mode ONLY!). The event loop is started if <Code>callbacks</code> in not <code>null</code>.
+	 *  @param args arguments to pass to R (note that R usually requires something like <code>--no-save</code>!)
+	 *  @param callbacks delegate class to process event loop callback from R or <code>null</code> if no event loop is desired 
+	 **/
+	public JRIEngine(String args[], RMainLoopCallbacks callbacks) throws REngineException {
+		this(args, callbacks, (callbacks == null) ? false : true);
+	}
+
+	/** creates a JRI engine with specified delegate for callbacks
+	 *  @param args arguments to pass to R (note that R usually requires something like <code>--no-save</code>!)
+	 *  @param callback delegate class to process callbacks from R or <code>null</code> if no callbacks are desired
+	 *  @param runREPL if set to <code>true</code> then the event loop (REPL) will be started, otherwise the engine is in direct operation mode.
+	 */
+	public JRIEngine(String args[], REngineCallbacks callbacks, boolean runREPL) throws REngineException {
+		// if Rengine hasn't been able to load the native JRI library in its static 
+		// initializer, throw an exception 
+		if (!Rengine.jriLoaded)
+			throw new REngineException (null, "Cannot load JRI native library");
+		
+		if (Rengine.getVersion() < requiredAPIversion)
+			throw new REngineException(null, "JRI API version is too old, update rJava/JRI to match the REngine API");
+		
+		this.callbacks = callbacks;
+		// the default modus operandi is without event loop and with --no-save option
+		rni = new Rengine(args, runREPL, (callbacks == null) ? null : this);
+		rniMutex = rni.getRsync();
+		boolean obtainedLock = rniMutex.safeLock(); // this will inherently wait for R to become ready
+		try {
+			if (!rni.waitForR())
+				throw(new REngineException(this, "Unable to initialize R"));
+			if (rni.rniGetVersion() < requiredAPIversion)
+				throw(new REngineException(this, "JRI API version is too old, update rJava/JRI to match the REngine API"));
+			globalEnv = new REXPReference(this, new Long(rni.rniSpecialObject(Rengine.SO_GlobalEnv)));
+			nullValueRef = new REXPReference(this, new Long(R_NilValue = rni.rniSpecialObject(Rengine.SO_NilValue)));
+			emptyEnv = new REXPReference(this, new Long(rni.rniSpecialObject(Rengine.SO_EmptyEnv)));
+			baseEnv = new REXPReference(this, new Long(rni.rniSpecialObject(Rengine.SO_BaseEnv)));
+			nullValue = new REXPNull();
+			R_UnboundValue = rni.rniSpecialObject(Rengine.SO_UnboundValue);
+		} finally {
+			if (obtainedLock) rniMutex.unlock();
+		}
+		// register ourself as the main and last engine
+		lastEngine = this;
+		if (jriEngine == null)
+			jriEngine = this;
+	}
+	
+	/** creates a JRI engine with specified delegate for callbacks (JRI compatibility mode ONLY! Will be deprecated soon!)
+	 *  @param args arguments to pass to R (note that R usually requires something like <code>--no-save</code>!)
+	 *  @param callback delegate class to process callbacks from R or <code>null</code> if no callbacks are desired
+	 *  @param runREPL if set to <code>true</code> then the event loop (REPL) will be started, otherwise the engine is in direct operation mode.
+	 */
+	public JRIEngine(String args[], RMainLoopCallbacks callbacks, boolean runREPL) throws REngineException {
+		// if Rengine hasn't been able to load the native JRI library in its static 
+		// initializer, throw an exception 
+		if (!Rengine.jriLoaded)
+			throw new REngineException (null, "Cannot load JRI native library");
+		
+		if (Rengine.getVersion() < requiredAPIversion)
+			throw new REngineException(null, "JRI API version is too old, update rJava/JRI to match the REngine API");
+		// the default modus operandi is without event loop and with --no-save option
+		rni = new Rengine(args, runREPL, callbacks);
+		rniMutex = rni.getRsync();
+		boolean obtainedLock = rniMutex.safeLock(); // this will inherently wait for R to become ready
+		try {
+			if (!rni.waitForR())
+				throw(new REngineException(this, "Unable to initialize R"));
+			if (rni.rniGetVersion() < requiredAPIversion)
+				throw(new REngineException(this, "JRI API version is too old, update rJava/JRI to match the REngine API"));
+			globalEnv = new REXPReference(this, new Long(rni.rniSpecialObject(Rengine.SO_GlobalEnv)));
+			nullValueRef = new REXPReference(this, new Long(R_NilValue = rni.rniSpecialObject(Rengine.SO_NilValue)));
+			emptyEnv = new REXPReference(this, new Long(rni.rniSpecialObject(Rengine.SO_EmptyEnv)));
+			baseEnv = new REXPReference(this, new Long(rni.rniSpecialObject(Rengine.SO_BaseEnv)));
+			nullValue = new REXPNull();
+			R_UnboundValue = rni.rniSpecialObject(Rengine.SO_UnboundValue);
+		} finally {
+			if (obtainedLock) rniMutex.unlock();
+		}
+		// register ourself as the main and last engine
+		lastEngine = this;
+		if (jriEngine == null)
+			jriEngine = this;
+	}
+	
+	/** WARNING: legacy fallback for hooking from R into an existing Rengine - do NOT use for creating a new Rengine - it will go away eventually */
+	public JRIEngine(Rengine eng) throws REngineException {
+		// if Rengine hasn't been able to load the native JRI library in its static 
+		// initializer, throw an exception 
+		if (!Rengine.jriLoaded)
+			throw new REngineException (null, "Cannot load JRI native library");
+
+		rni = eng;
+		if (rni.rniGetVersion() < 0x109)
+			throw(new REngineException(this, "R JRI engine is too old - RNI API 1.9 (JRI 0.5) or newer is required"));
+		rniMutex = rni.getRsync();
+		boolean obtainedLock = rniMutex.safeLock();
+		try {
+			globalEnv = new REXPReference(this, new Long(rni.rniSpecialObject(Rengine.SO_GlobalEnv)));
+			nullValueRef = new REXPReference(this, new Long(R_NilValue = rni.rniSpecialObject(Rengine.SO_NilValue)));
+			emptyEnv = new REXPReference(this, new Long(rni.rniSpecialObject(Rengine.SO_EmptyEnv)));
+			baseEnv = new REXPReference(this, new Long(rni.rniSpecialObject(Rengine.SO_BaseEnv)));
+			nullValue = new REXPNull();
+			R_UnboundValue = rni.rniSpecialObject(Rengine.SO_UnboundValue);
+		} finally {
+			if (obtainedLock) rniMutex.unlock();
+		}
+		// register ourself as the main and last engine
+		lastEngine = this;
+		if (jriEngine == null)
+			jriEngine = this;
+	}
+	
+	public REXP parse(String text, boolean resolve) throws REngineException {
+		REXP ref = null;
+		boolean obtainedLock = rniMutex.safeLock();
+		try {
+			long pr = rni.rniParse(text, -1);
+			if (pr == 0 || pr == R_NilValue) throw(new REngineException(this, "Parse error"));
+			rni.rniPreserve(pr);
+			ref = new REXPReference(this, new Long(pr));
+			if (resolve)
+				try { ref = resolveReference(ref); } catch (REXPMismatchException me) { };
+		} finally {
+			if (obtainedLock)
+				rniMutex.unlock();
+		}
+		return ref;
+	}
+
+	public REXP eval(REXP what, REXP where, boolean resolve) throws REngineException, REXPMismatchException {
+		REXP ref = null;
+		long rho = 0;
+		if (where != null && !where.isReference()) {
+			if (!where.isEnvironment() || ((REXPEnvironment)where).getHandle() == null)
+				throw(new REXPMismatchException(where, "environment"));
+			else
+				rho = ((JRIPointer)((REXPEnvironment)where).getHandle()).pointer();
+		} else
+			if (where != null) rho = ((Long)((REXPReference)where).getHandle()).longValue();
+		if (what == null) throw(new REngineException(this, "null object to evaluate"));
+		if (!what.isReference()) {
+			if (what.isExpression() || what.isLanguage())
+				what = createReference(what);
+			else
+				throw(new REXPMismatchException(where, "reference, expression or language"));
+		}
+		boolean obtainedLock = rniMutex.safeLock();
+		try {
+			long pr = rni.rniEval(((Long)((REXPReference)what).getHandle()).longValue(), rho);
+			if (pr == 0) // rniEval() signals error by passing 0
+				throw new REngineEvalException(this, "error during evaluation", REngineEvalException.ERROR) ;
+			rni.rniPreserve(pr);
+			ref = new REXPReference(this, new Long(pr));
+			if (resolve)
+				ref = resolveReference(ref);
+		} finally {
+			if (obtainedLock)
+				rniMutex.unlock();
+		}
+		return ref;
+	}
+
+	public void assign(String symbol, REXP value, REXP env) throws REngineException, REXPMismatchException {
+		long rho = 0;
+		if (env != null && !env.isReference()) {
+			if (!env.isEnvironment() || ((REXPEnvironment)env).getHandle() == null)
+				throw(new REXPMismatchException(env, "environment"));
+			else
+				rho = ((JRIPointer)((REXPEnvironment)env).getHandle()).pointer();
+		} else
+			if (env != null) rho = ((Long)((REXPReference)env).getHandle()).longValue();
+		if (value == null) value = nullValueRef;
+		if (!value.isReference())
+			value = createReference(value); // if value is not a reference, we have to create one
+		boolean obtainedLock = rniMutex.safeLock(), succeeded = false;
+		try {
+			succeeded = rni.rniAssign(symbol, ((Long)((REXPReference)value).getHandle()).longValue(), rho);
+		} finally {
+			if (obtainedLock)
+				rniMutex.unlock();
+		}
+		if (!succeeded)
+			throw new REngineException(this, "assign failed (probably locked binding");
+	}
+	
+	public REXP get(String symbol, REXP env, boolean resolve) throws REngineException, REXPMismatchException {
+		REXP ref = null;
+		long rho = 0;
+		if (env != null && !env.isReference()) {
+			if (!env.isEnvironment() || ((REXPEnvironment)env).getHandle() == null)
+				throw(new REXPMismatchException(env, "environment"));
+			else
+				rho = ((JRIPointer)((REXPEnvironment)env).getHandle()).pointer();
+		} else
+			if (env != null) rho = ((Long)((REXPReference)env).getHandle()).longValue();
+		boolean obtainedLock = rniMutex.safeLock();
+		try {
+			long pr = rni.rniFindVar(symbol, rho);
+			if (pr == R_UnboundValue || pr == 0) return null;
+			rni.rniPreserve(pr);
+			ref = new REXPReference(this, new Long(pr));
+			if (resolve)
+				try { ref = resolveReference(ref); } catch (REXPMismatchException me) { };
+		} finally {
+			if (obtainedLock)
+				rniMutex.unlock();
+		}
+		return ref;
+	}
+
+	public REXP resolveReference(REXP ref) throws REngineException, REXPMismatchException {
+		REXP res = null;
+		if (ref == null) throw(new REngineException(this, "resolveReference called on NULL input"));
+		if (!ref.isReference()) throw(new REXPMismatchException(ref, "reference"));
+		long ptr = ((Long)((REXPReference)ref).getHandle()).longValue();
+		if (ptr == 0) return nullValue;
+		return resolvePointer(ptr);
+	}
+
+	/** 
+	 * Turn an R pointer (long) into a REXP object.
+	 * 
+	 * This is the actual implementation of <code>resolveReference</code> but it works directly on the long pointers to be more efficient when performing recursive de-referencing */
+	REXP resolvePointer(long ptr) throws REngineException, REXPMismatchException {
+		if (ptr == 0) return nullValue;
+		REXP res = null;
+		boolean obtainedLock = rniMutex.safeLock();
+		try {
+			int xt = rni.rniExpType(ptr);
+			String an[] = rni.rniGetAttrNames(ptr);
+			REXPList attrs = null;
+			if (an != null && an.length > 0) { // are there attributes? Then we need to resolve them first
+				// we allow special handling for Java references so we need the class and jobj
+				long jobj = 0;
+				String oclass = null;
+				RList attl = new RList();
+				for (int i = 0; i < an.length; i++) {
+					long aptr = rni.rniGetAttr(ptr, an[i]);
+					if (aptr != 0 && aptr != R_NilValue) {
+						if (an[i].equals("jobj")) jobj = aptr;
+						REXP av = resolvePointer(aptr);
+						if (av != null && av != nullValue) {
+							attl.put(an[i], av);
+							if (an[i].equals("class") && av.isString())
+								oclass = av.asString();
+						}
+					}
+				}
+				if (attl.size() > 0)
+					attrs = new REXPList(attl);
+				// FIXME: in general, we could allow arbitrary convertors here ...
+				// Note that the jobj hack is only needed because we don't support EXTPTRSXP conversion
+				// (for a good reason - we can't separate the PTR from the R object so the only way it can
+				// live is as a reference and we don't want resolvePointer to ever return REXPReference as
+				// that could trigger infinite recursions), but if we did, we could allow post-processing
+				// based on the class attribute on the converted REXP.. (better, we can leverage REXPUnknown
+				// and pass the ptr to the convertor so it can pull things like EXTPTR via rni)
+				if (jobj != 0 && oclass != null &&
+				    (oclass.equals("jobjRef") ||
+				     oclass.equals("jarrayRef") ||
+				     oclass.equals("jrectRef")))
+					return new REXPJavaReference(rni.rniXrefToJava(jobj), attrs);
+			}
+			switch (xt) {
+				case NILSXP:
+					return nullValue;
+					
+				case STRSXP:
+					String[] s = rni.rniGetStringArray(ptr);
+					res = new REXPString(s, attrs);
+					break;
+					
+				case INTSXP:
+					if (rni.rniInherits(ptr, "factor")) {
+						long levx = rni.rniGetAttr(ptr, "levels");
+						if (levx != 0) {
+							String[] levels = null;
+							// we're using low-level calls here (FIXME?)
+							int rlt = rni.rniExpType(levx);
+							if (rlt == STRSXP) {
+								levels = rni.rniGetStringArray(levx);
+								int[] ids = rni.rniGetIntArray(ptr);
+								res = new REXPFactor(ids, levels, attrs);
+							}
+						}
+					}
+					// if it's not a factor, then we use int[] instead
+					if (res == null)
+						res = new REXPInteger(rni.rniGetIntArray(ptr), attrs);
+					break;
+					
+				case REALSXP:
+					res = new REXPDouble(rni.rniGetDoubleArray(ptr), attrs);
+					break;
+					
+				case LGLSXP:
+				{
+					int ba[] = rni.rniGetBoolArrayI(ptr);
+					byte b[] = new byte[ba.length];
+					for (int i = 0; i < ba.length; i++)
+						b[i] = (ba[i] == 0 || ba[i] == 1) ? (byte) ba[i] : REXPLogical.NA;
+					res = new REXPLogical(b, attrs);
+				}
+					break;
+					
+				case VECSXP:
+				{
+					long l[] = rni.rniGetVector(ptr);
+					REXP rl[] = new REXP[l.length];
+					long na = rni.rniGetAttr(ptr, "names");
+					String[] names = null;
+					if (na != 0 && rni.rniExpType(na) == STRSXP)
+						names = rni.rniGetStringArray(na);
+					for (int i = 0; i < l.length; i++)
+						rl[i] = resolvePointer(l[i]);
+					RList list = (names == null) ? new RList(rl) : new RList(rl, names);
+					res = new REXPGenericVector(list, attrs);
+				}
+					break;
+					
+				case RAWSXP:
+					res = new REXPRaw(rni.rniGetRawArray(ptr), attrs);
+					break;
+					
+				case LISTSXP:
+				case LANGSXP:
+				{
+					RList l = new RList();
+					// we need to plow through the list iteratively - the recursion occurs at the value level
+					long cdr = ptr;
+					while (cdr != 0 && cdr != R_NilValue) {
+						long car = rni.rniCAR(cdr);
+						long tag = rni.rniTAG(cdr);
+						String name = null;
+						if (rni.rniExpType(tag) == SYMSXP)
+							name = rni.rniGetSymbolName(tag);
+						REXP val = resolvePointer(car);
+						if (name == null) l.add(val); else l.put(name, val);
+						cdr = rni.rniCDR(cdr);
+					}
+					res = (xt == LANGSXP) ? new REXPLanguage(l, attrs) : new REXPList(l, attrs);
+				}
+					break;
+					
+				case SYMSXP:
+					res = new REXPSymbol(rni.rniGetSymbolName(ptr));
+					break;
+					
+				case ENVSXP:
+					if (ptr != 0) rni.rniPreserve(ptr);
+					res = new REXPEnvironment(this, new JRIPointer(ptr, false));
+					break;
+					
+				case S4SXP:
+					res = new REXPS4(attrs);
+					break;
+					
+				default:
+					res = new REXPUnknown(xt, attrs);
+					break;
+			}
+		} finally {
+			if (obtainedLock)
+				rniMutex.unlock();
+		}
+		return res;
+	}
+
+	public REXP createReference(REXP value) throws REngineException, REXPMismatchException {
+		if (value == null) throw(new REngineException(this, "createReference from a NULL value"));
+		if (value.isReference()) return value;
+		long ptr = createReferencePointer(value);
+		if (ptr == 0) return null;
+		boolean obtainedLock = rniMutex.safeLock();
+		try {
+			rni.rniPreserve(ptr);
+		} finally {
+			if (obtainedLock)
+				rniMutex.unlock();
+		}
+		return new REXPReference(this, new Long(ptr));
+	}
+	
+	/** 
+	 * Create an R object, returning its pointer, from an REXP java object.
+	 * 
+	 * @param value
+	 * @return long R pointer
+	 * @throws REngineException if any of the RNI calls fails
+	 * @throws REXPMismatchException only if some internal inconsistency happens. The internal logic should prevent invalid access to valid objects.
+	 */
+	long createReferencePointer(REXP value) throws REngineException, REXPMismatchException {
+		if (value.isReference()) { // if it's reference, return the handle if it's from this engine
+			REXPReference vref = (REXPReference) value;
+			if (vref.getEngine() != this)
+				throw new REXPMismatchException(value, "reference (cross-engine reference is invalid)");
+			return ((Long)vref.getHandle()).longValue();
+		}
+		boolean obtainedLock = rniMutex.safeLock();
+		int upp = 0;
+		try {
+			long ptr = 0;
+			if (value.isNull()) // NULL cannot have attributes, hence get out right away
+				return R_NilValue;
+			else if (value.isLogical()) {
+				int v[] = value.asIntegers();
+				for (int i = 0; i < v.length; i++)
+					v[i] = (v[i] < 0) ? 2 : ((v[i] == 0) ? 0 : 1); // convert to logical NAs as used by R
+				ptr = rni.rniPutBoolArrayI(v);
+			}
+			else if (value.isInteger())
+				ptr = rni.rniPutIntArray(value.asIntegers());
+			else if (value.isRaw())
+				ptr = rni.rniPutRawArray(value.asBytes());
+			else if (value.isNumeric())
+				ptr = rni.rniPutDoubleArray(value.asDoubles());
+			else if (value.isString())
+				ptr = rni.rniPutStringArray(value.asStrings());
+			else if (value.isEnvironment()) {
+				JRIPointer l = (JRIPointer) ((REXPEnvironment)value).getHandle();
+				if (l == null) { // no associated reference, create a new environemnt
+					long p = rni.rniParse("new.env(parent=baseenv())", 1);
+					ptr = rni.rniEval(p, 0);
+					/* TODO: should we handle REngineEvalException.ERROR and REngineEvalException.INVALID_INPUT here, for completeness */
+				} else
+					ptr = l.pointer();
+			} else if (value.isPairList()) { // LISTSXP / LANGSXP
+				boolean lang = value.isLanguage();
+				RList rl = value.asList();
+				ptr = R_NilValue;
+				int j = rl.size();
+				if (j == 0)
+					ptr = rni.rniCons(R_NilValue, 0, 0, lang);
+				else
+					// we are in a somewhat unfortunate situation because we cannot append to the list (RNI has no rniSetCDR!) so we have to use Preserve and bulild the list backwards which may be a bit slower ...
+					for (int i = j - 1; i >= 0; i--) {
+						REXP v = rl.at(i);
+						String n = rl.keyAt(i);
+						long sn = 0;
+						if (n != null) sn = rni.rniInstallSymbol(n);
+						long vptr = createReferencePointer(v);
+						if (vptr == 0) vptr = R_NilValue;
+						long ent = rni.rniCons(vptr, ptr, sn, (i == 0) && lang); /* only the head should be LANGSXP I think - verify ... */
+						rni.rniPreserve(ent); // preserve current head
+						rni.rniRelease(ptr); // release previous head (since it's part of the new one already)
+						ptr = ent;
+					}
+			} else if (value.isList()) { // VECSXP
+				int init_upp = upp;
+				RList rl = value.asList();
+				long xl[] = new long[rl.size()];
+				for (int i = 0; i < xl.length; i++) {
+					REXP rv = rl.at(i);
+					if (rv == null || rv.isNull())
+						xl[i] = R_NilValue;
+					else {
+						long lv = createReferencePointer(rv);
+						if (lv != 0 && lv != R_NilValue) {
+							rni.rniProtect(lv);
+							upp++;
+						} else lv = R_NilValue;
+						xl[i] = lv;
+					}
+				}
+				ptr = rni.rniPutVector(xl);
+				if (init_upp > upp) {
+					rni.rniUnprotect(upp - init_upp);
+					upp = init_upp;
+				}
+			} else if (value.isSymbol())
+				return rni.rniInstallSymbol(value.asString()); // symbols need no attribute handling, hence get out right away
+			else if (value instanceof REXPJavaReference) { // we wrap Java references by calling new("jobjRef", ...)
+				Object jval = ((REXPJavaReference)value).getObject();
+				long jobj = rni.rniJavaToXref(jval);
+				rni.rniProtect(jobj);
+				long jobj_sym = rni.rniInstallSymbol("jobj");
+				long jclass_sym = rni.rniInstallSymbol("jclass");
+				String clname = "java/lang/Object";
+				if (jval != null) {
+					clname = jval.getClass().getName();
+					clname = clname.replace('.', '/');
+				}
+				long jclass = rni.rniPutString(clname);
+				rni.rniProtect(jclass);
+				long jobjRef = rni.rniPutString("jobjRef");
+				rni.rniProtect(jobjRef);
+				long ro = rni.rniEval(rni.rniLCons(rni.rniInstallSymbol("new"),
+								   rni.rniCons(jobjRef,
+									       rni.rniCons(jobj, 
+											   rni.rniCons(jclass, R_NilValue, jclass_sym, false),
+											   jobj_sym, false))
+								   ), 0);
+				rni.rniUnprotect(3);
+				ptr = ro;
+			}
+			if (ptr == R_NilValue)
+				return ptr;
+			if (ptr != 0) {
+				REXPList att = value._attr();
+				if (att == null || !att.isPairList()) return ptr; // no valid attributes? the we're done
+				RList al = att.asList();
+				if (al == null || al.size() < 1 || !al.isNamed()) return ptr; // again - no valid list, get out
+				rni.rniProtect(ptr); // symbols and other exotic creatures are already out by now, so it's ok to protect
+				upp++;
+				for (int i = 0; i < al.size(); i++) {
+					REXP v = al.at(i);
+					String n = al.keyAt(i);
+					if (n != null) {
+						long vptr = createReferencePointer(v);
+						if (vptr != 0 && vptr != R_NilValue)
+							rni.rniSetAttr(ptr, n, vptr);
+					}
+				}
+				return ptr;
+			}
+		} finally {
+			if (upp > 0)
+				rni.rniUnprotect(upp);
+			if (obtainedLock)
+				rniMutex.unlock();
+		}
+		// we fall thgough here if the object cannot be handled or something went wrong
+		return 0;
+	}
+	
+	public void finalizeReference(REXP ref) throws REngineException, REXPMismatchException {
+		if (ref != null && ref.isReference()) {
+			long ptr = ((Long)((REXPReference)ref).getHandle()).longValue();
+			boolean obtainedLock = rniMutex.safeLock();
+			try {
+				rni.rniRelease(ptr);
+			} finally {
+				if (obtainedLock)
+					rniMutex.unlock();
+			}
+		}
+	}
+
+	public REXP getParentEnvironment(REXP env, boolean resolve) throws REngineException, REXPMismatchException {
+		REXP ref = null;
+		long rho = 0;
+		if (env != null && !env.isReference()) {
+			if (!env.isEnvironment() || ((REXPEnvironment)env).getHandle() == null)
+				throw(new REXPMismatchException(env, "environment"));
+			else
+				rho = ((JRIPointer)((REXPEnvironment)env).getHandle()).pointer();
+		} else
+			if (env != null) rho = ((Long)((REXPReference)env).getHandle()).longValue();
+		boolean obtainedLock = rniMutex.safeLock();
+		try {
+			long pr = rni.rniParentEnv(rho);
+			if (pr == 0 || pr == R_NilValue) return null; // this should never happen, really
+			rni.rniPreserve(pr);
+			ref = new REXPReference(this, new Long(pr));
+			if (resolve)
+				ref = resolveReference(ref);
+		} finally {
+			if (obtainedLock)
+				rniMutex.unlock();
+		}
+		return ref;
+	}
+
+	public REXP newEnvironment(REXP parent, boolean resolve) throws REXPMismatchException, REngineException {
+		REXP ref = null;
+		boolean obtainedLock = rniMutex.safeLock();
+		try {
+			long rho = 0;
+			if (parent != null && !parent.isReference()) {
+				if (!parent.isEnvironment() || ((REXPEnvironment)parent).getHandle() == null)
+					throw(new REXPMismatchException(parent, "environment"));
+				else
+					rho = ((JRIPointer)((REXPEnvironment)parent).getHandle()).pointer();
+			} else
+				if (parent != null) rho = ((Long)((REXPReference)parent).getHandle()).longValue();
+			if (rho == 0)
+				rho = ((Long)((REXPReference)globalEnv).getHandle()).longValue();
+			long p = rni.rniEval(rni.rniLCons(rni.rniInstallSymbol("new.env"), rni.rniCons(rho, R_NilValue, rni.rniInstallSymbol("parent"), false)), 0);
+			/* TODO: should we handle REngineEvalException.INVALID_INPUT and REngineEvalException.ERROR here, for completeness */
+			if (p != 0) rni.rniPreserve(p);
+			ref = new REXPReference(this, new Long(p));
+			if (resolve)
+				ref = resolveReference(ref);
+		} finally {
+			if (obtainedLock)
+				rniMutex.unlock();
+		}
+		return ref;
+	}
+
+	public boolean close() {
+		if (rni == null) return false;
+		rni.end();
+		return true;
+	}
+
+	/** attempts to obtain a lock for this R engine synchronously (without waiting for it).
+	 @return 0 if the lock could not be obtained (R is busy) and some other value otherwise (1 = lock obtained, 2 = the current thread already holds a lock) -- the returned value must be used in a matching call to {@link #unlock(int)}. */
+	public synchronized int tryLock() {
+		int res = rniMutex.tryLock();
+		return (res == 1) ? 0 : ((res == -1) ? 2 : 1);
+	}
+	
+	/** obains a lock for this R engine, waiting until it becomes available.
+	 @return value that must be passed to {@link #unlock} in order to release the lock */
+	public synchronized int lock() {
+		return rniMutex.safeLock() ? 1 : 2;
+	}
+	
+	/** releases a lock previously obtained by {@link #lock()} or {@link #tryLock()}.
+	 @param lockValue value returned by {@link #lock()} or {@link #tryLock()}. */	 
+	public synchronized void unlock(int lockValue) {
+		if (lockValue == 1) rniMutex.unlock();
+	}
+	
+	public boolean supportsReferences() { return true; }
+	public boolean supportsEnvironments() { return true; }
+	// public boolean supportsREPL() { return true; }
+	public boolean supportsLocking() { return true; }
+	
+	/**
+	 * creates a <code>jobjRef</code> reference in R via rJava.<br><b>Important:</b> rJava must be loaded and intialized in R (e.g. via <code>eval("{library(rJava);.jinit()}",false)</code>, otherwise this will fail. Requires rJava 0.4-13 or higher!
+	 *
+	 * @param o object to push to R
+	 * 
+	 * @return unresolved REXPReference of the newly created <code>jobjRef</code> object
+	 *         or <code>null</code> upon failure
+	 */
+	public REXPReference createRJavaRef(Object o) throws REngineException {
+		/* precaution */
+		if( o == null ){
+			return null ;
+		}
+		
+		/* call Rengine api and make REXPReference from the result */
+		REXPReference ref = null ; 
+		boolean obtainedLock = rniMutex.safeLock();
+		try {
+			org.rosuda.JRI.REXP rx = rni.createRJavaRef( o );
+			if( rx == null){
+				throw new REngineException( this, "Could not push java Object to R" ) ; 
+			} else{ 
+				long p = rx.xp;
+				rni.rniPreserve(p) ;
+				ref = new REXPReference( this, new Long(p) ) ;
+			}
+		} finally {
+			if (obtainedLock)
+				rniMutex.unlock();
+		}
+		return ref ; 
+	}
+	
+	/** JRI callbacks forwarding */
+	public void   rWriteConsole (Rengine re, String text, int oType) {
+		if (callbacks != null && callbacks instanceof REngineOutputInterface)
+			((REngineOutputInterface)callbacks).RWriteConsole(this, text, oType);
+	}
+	
+	public void   rBusy         (Rengine re, int which) {
+		if (callbacks != null && callbacks instanceof REngineUIInterface)
+			((REngineUIInterface)callbacks).RBusyState(this, which);
+	}
+	
+	public synchronized String rReadConsole  (Rengine re, String prompt, int addToHistory) {
+		if (callbacks != null && callbacks instanceof REngineInputInterface)
+			return ((REngineInputInterface)callbacks).RReadConsole(this, prompt, addToHistory);
+		
+		try { wait(); } catch (Exception e) {}
+		return "";
+	}
+	
+	public void   rShowMessage  (Rengine re, String message) {
+		if (callbacks != null && callbacks instanceof REngineOutputInterface)
+			((REngineOutputInterface)callbacks).RShowMessage(this, message);
+	}
+	
+	public String rChooseFile   (Rengine re, int newFile) {
+		if (callbacks != null && callbacks instanceof REngineUIInterface)
+			return ((REngineUIInterface)callbacks).RChooseFile(this, (newFile == 0));
+		return null;
+	}
+	
+	public void   rFlushConsole (Rengine re) {
+		if (callbacks != null && callbacks instanceof REngineOutputInterface)
+			((REngineOutputInterface)callbacks).RFlushConsole(this);
+	}
+	
+	public void   rSaveHistory  (Rengine re, String filename) {
+		if (callbacks != null && callbacks instanceof REngineConsoleHistoryInterface)
+			((REngineConsoleHistoryInterface)callbacks).RSaveHistory(this, filename);
+	}
+	
+	public void   rLoadHistory  (Rengine re, String filename) {
+		if (callbacks != null && callbacks instanceof REngineConsoleHistoryInterface)
+			((REngineConsoleHistoryInterface)callbacks).RLoadHistory(this, filename);
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/JRI/Makefile b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/JRI/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..1bb088acac9b713cc236a13a58c8ba6be98968dd
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/JRI/Makefile
@@ -0,0 +1,27 @@
+## there are two ways to compile JRIEngine - either use
+## already installed REngine and JRI and then just
+## compile JRIEngine against those jars or use this
+## Makefile with all org sources checked out
+## in which case the JRIEngine.jar will implicitly
+## contain org.rosuda.JRI classes as well
+## However, that requires both:
+## org/rosuda/JRI
+## org/rosuda/REngine
+
+JRI_MAIN_SRC=$(wildcard ../../*.java)
+JRIENGINE_SRC=JRIEngine.java
+
+JAVAC=javac
+JAR=jar
+JFLAGS=-source 1.6 -target 1.6
+
+all: JRIEngine.jar
+
+JRIEngine.jar: $(JRI_MAIN_SRC) $(JRIENGINE_SRC)
+	rm -rf org
+	$(JAVAC) $(JFLAGS) -classpath ../REngine.jar -d . $^
+	$(JAR) fc $@ org
+
+clean:
+	rm -rf org *~ JRIEngine.jar *.class
+	make -C test clean
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/JRI/package-info.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/JRI/package-info.java
new file mode 100644
index 0000000000000000000000000000000000000000..883ed096b73521797a54814eb104231d105d33d6
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/JRI/package-info.java
@@ -0,0 +1,9 @@
+/**
+ * REngine-based interface to JRI
+ *
+ * <p>
+ * Currently it uses low-level calls from org.rosuda.JRI.Rengine, but
+ * all REXP representations are created based on the org.rosuda.REngine API
+ */
+package org.rosuda.REngine.JRI ;
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/JRI/test/Makefile b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/JRI/test/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..4ec688b474baf7c84db5f292c5d5514625afd0e6
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/JRI/test/Makefile
@@ -0,0 +1,27 @@
+## NOTE: the tests require rJava to be installed in the current R
+##       since they also test the JRI/rJava connectivity
+
+CP=../../REngine.jar:../JRIEngine.jar:$(RJAVA)/java/boot:$(RJAVA)/jri/JRI.jar
+JFLAGS=-source 1.6 -target 1.6
+
+RJAVA=$(shell echo "cat(system.file(package='rJava'))"|R --slave --no-save)
+JRI=$(shell if test -e ../../../JRI/src/JRI.jar; then echo ../../../JRI/src; else echo $(RJAVA)/jri; fi)
+
+JRT=-Djava.library.path=$(JRI):.
+
+JAVAC=javac
+JAVA=java
+
+all: run
+
+RTest.class: RTest.java
+	$(JAVAC) $(JFLAGS) -classpath $(CP) $^
+
+run: RTest.class
+	R CMD $(JAVA) -cp $(CP):. $(JRT) RTest
+
+clean:
+	rm -rf org *.class *~
+
+.PHONY: run clean
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/JRI/test/RTest.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/JRI/test/RTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..d92d6b8de67cc13cd93eec2c1214d3a5d29ac597
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/JRI/test/RTest.java
@@ -0,0 +1,384 @@
+import org.rosuda.REngine.*;
+
+class TestException extends Exception {
+	public TestException(String msg) { super(msg); }
+}
+
+// This is the same test as in Rserve but it's using JRI instead
+
+public class RTest {
+	public static void main(String[] args) {
+		try { 
+			// the simple initialization is done using
+			// REngine eng = REngine.engineForClass("org.rosuda.REngine.JRI.JRIEngine");
+			// but the one below allows us to see all output from R via REngineStdOutput()
+			// However, it won't succeed if the engine doesn't support callbacks, so be prepared to fall back
+			REngine eng = REngine.engineForClass("org.rosuda.REngine.JRI.JRIEngine", args, new REngineStdOutput(), false);
+
+			if (args.length > 0 && args[0].equals("--debug")) { // --debug waits for <Enter> so a debugger can be attached
+				System.out.println("R Version: " + eng.parseAndEval("R.version.string").asString());
+				System.out.println("ok, connected, press <enter> to continue\n");
+				System.in.read();
+			}
+			
+			{
+				System.out.println("* Test string and list retrieval");
+				RList l = eng.parseAndEval("{d=data.frame(\"huhu\",c(11:20)); lapply(d,as.character)}").asList();
+				int cols = l.size();
+				int rows = l.at(0).length();
+				String[][] s = new String[cols][];
+				for (int i=0; i<cols; i++) s[i]=l.at(i).asStrings();
+				System.out.println("PASSED");
+			}
+			
+			{
+				System.out.println("* Test NA/NaN support in double vectors...");
+				double x[] = { 1.0, 0.5, REXPDouble.NA, Double.NaN, 3.5 };
+				eng.assign("x",x);
+				String nas = eng.parseAndEval("paste(capture.output(print(x)),collapse='\\n')").asString();
+				System.out.println(nas);
+				if (!nas.equals("[1] 1.0 0.5  NA NaN 3.5"))
+					throw new TestException("NA/NaN assign+retrieve test failed");
+				// regression: the inverse failed becasue Java screwed up the bits in the NA value
+				REXP v = eng.parseAndEval("c(1.5, NA, NaN)");
+				if (v == null || v.length() != 3)
+					throw new TestException("NA/NaN double retrieve test failed");
+				System.out.println("  v = "+v.toDebugString());
+				boolean b[] = v.isNA();
+				if (b == null || b.length != 3 || b[0] != false || b[1] != true || b[2] != false)
+					throw new TestException("isNA() test on doubles failed");
+				double d[] = v.asDoubles();
+				if (Double.isNaN(d[0]) || !Double.isNaN(d[1]) || !Double.isNaN(d[2]))
+					throw new TestException("Double.isNaN test on doubles failed");
+				System.out.println("PASSED");
+			}
+			
+			{
+				System.out.println("* Test assigning of lists and vectors ...");
+				RList l = new RList();
+				l.put("a",new REXPInteger(new int[] { 0,1,2,3}));
+				l.put("b",new REXPDouble(new double[] { 0.5,1.2,2.3,3.0}));
+				System.out.println("  assign x=pairlist");
+				eng.assign("x", new REXPList(l));
+				System.out.println("  assign y=vector");
+				eng.assign("y", new REXPGenericVector(l));
+				System.out.println("  assign z=data.frame");
+				eng.assign("z", REXP.createDataFrame(l));
+				System.out.println("  pull all three back to Java");
+				REXP x = eng.parseAndEval("x");
+				System.out.println("  x = "+x);
+				x = eng.parseAndEval("y");
+				System.out.println("  y = "+x);
+				x = eng.parseAndEval("z");
+				System.out.println("  z = "+x);
+				System.out.println("PASSED");
+			}
+			
+			{ // regression: object bit was not set for Java-side generated objects before 0.5-3
+				System.out.println("* Testing functionality of assembled S3 objects ...");
+				// we have already assigned the data.frame in previous test, so we jsut re-use it
+				REXP x = eng.parseAndEval("z[2,2]");
+				System.out.println("  z[2,2] = " + x);
+				if (x == null || x.length() != 1 || x.asDouble() != 1.2)
+					throw new TestException("S3 object bit regression test failed");
+				System.out.println("PASSED");
+			}
+			
+			{ // this test does a pull and push of a data frame. It will fail when the S3 test above failed.
+				System.out.println("* Testing pass-though capability for data.frames ...");
+				REXP df = eng.parseAndEval("{data(iris); iris}");
+				eng.assign("df", df);
+				REXP x = eng.parseAndEval("identical(df, iris)");
+				System.out.println("  identical(df, iris) = "+x);
+				if (x == null || !x.isLogical() || x.length() != 1 || !((REXPLogical)x).isTRUE()[0])
+					throw new TestException("Pass-through test for a data.frame failed");
+				System.out.println("PASSED");
+			}
+			
+            { // factors
+                System.out.println("* Test support of factors");
+                REXP f = eng.parseAndEval("factor(paste('F',as.integer(runif(20)*5),sep=''))");
+				System.out.println("  f="+f);
+                System.out.println("  isFactor: "+f.isFactor()+", asFactor: "+f.asFactor());
+                if (!f.isFactor() || f.asFactor() == null) throw new TestException("factor test failed");
+                System.out.println("  singe-level factor used to degenerate:");
+                f = eng.parseAndEval("factor('foo')");
+                System.out.println("  isFactor: "+f.isFactor()+", asFactor: "+f.asFactor());
+                if (!f.isFactor() || f.asFactor() == null) throw new TestException("single factor test failed (not a factor)");
+				if (!f.asFactor().at(0).equals("foo")) throw new TestException("single factor test failed (wrong value)");
+                System.out.println("  test factors with null elements contents:");
+				eng.assign("f", new REXPFactor(new RFactor(new String[] { "foo", "bar", "foo", "foo", null, "bar" })));
+				f = eng.parseAndEval("f");
+                if (!f.isFactor() || f.asFactor() == null) throw new TestException("factor assign-eval test failed (not a factor)");
+				System.out.println("  f = "+f.asFactor());
+				f = eng.parseAndEval("as.factor(c(1,'a','b',1,'b'))");
+				System.out.println("  f = "+f);
+                if (!f.isFactor() || f.asFactor() == null) throw new TestException("factor test failed (not a factor)");
+				System.out.println("PASSED");
+            }
+			
+			
+			{
+				System.out.println("* Lowess test");
+				double x[] = eng.parseAndEval("rnorm(100)").asDoubles();
+				double y[] = eng.parseAndEval("rnorm(100)").asDoubles();
+				eng.assign("x", x);
+				eng.assign("y", y);
+				RList l = eng.parseAndEval("lowess(x,y)").asList();
+				System.out.println("  "+l);
+				x = l.at("x").asDoubles();
+				y = l.at("y").asDoubles();
+				System.out.println("PASSED");
+			}
+			
+			{
+				// multi-line expressions
+				System.out.println("* Test multi-line expressions");
+				System.out.print("    multi-line single expression");
+				if (eng.parseAndEval("{ a=1:10\nb=11:20\nmean(b-a) }\n").asInteger()!=10)
+					throw new TestException("multi-line test failed.");
+				System.out.println("    : ok");
+				
+				System.out.print("    multitle expressions" ); 
+				if (eng.parseAndEval("a=1:10; b=11:20; mean(b-a)").asInteger()!=10)
+					throw new TestException("multi-expression test failed.");
+				System.out.println("    : ok");
+				
+				System.out.print("    comment (0 expressions)" ); 
+				if (! eng.parseAndEval("# comment").isNull() )
+					throw new TestException("eval comment (zero expression) failed");
+				System.out.println("    : ok");
+				
+				
+				System.out.println("PASSED");
+			}
+			{
+				System.out.println("* Matrix tests\n  matrix: create a matrix");
+				int m=100, n=100;
+				double[] mat=new double[m*n];
+				int i=0;
+				while (i<m*n) mat[i++]=i/100;
+				System.out.println("  matrix: assign a matrix");
+				eng.assign("m", mat);
+				eng.parseAndEval("m<-matrix(m,"+m+","+n+")", null, false); // don't return the result - it has a similar effect to voidEval in Rserve
+				System.out.println("matrix: cross-product");
+				double[][] mr=eng.parseAndEval("crossprod(m,m)").asDoubleMatrix();
+				System.out.println("PASSED");
+			}
+			
+			{ /* NAs in character vectors are mapped to null references in String[] and vice versa. JRI 0.5-0 and older incorrectly returned "NA" instead of null */
+				System.out.println("* Test handling of NAs in character vectors ('foo', NA, 'NA')");
+				System.out.print("  push String[] with NAs: ");
+				eng.assign("s", new String[] { "foo", null, "NA" });
+				int nas[] = eng.parseAndEval("is.na(s)").asIntegers();
+				for (int i = 0; i < nas.length; i++) System.out.print(nas[i] + " ");
+				if (nas.length != 3 || nas[0] != REXPLogical.FALSE || nas[1] != REXPLogical.TRUE || nas[2] != REXPLogical.FALSE)
+					throw new TestException("assigning null Strings as NAs has failed");
+				System.out.println(" - OK");
+				System.out.print("  pull String[] with NAs: ");
+				String s[] = eng.parseAndEval("c('foo', NA, 'NA')").asStrings();
+				for (int i = 0; i < s.length; i++) System.out.print(s[i] + " ");
+				if (s.length != 3 || s[0] == null || s[1] != null || s[2] == null)
+					throw new TestException("pulling Strings containin NAs has failed");
+				System.out.println(" - OK");
+				System.out.print("  compare pushed and constructed strings: ");
+				if (eng.parseAndEval("identical(s, c('foo', NA, 'NA'))").asInteger() != REXPLogical.TRUE)
+					throw new TestException("comparing Strings with NAs has failed");
+				System.out.println(" - OK");
+				System.out.print("  check isNA() for REXPString");
+				boolean na[] = eng.parseAndEval("s").isNA();
+				for (int i = 0; i < na.length; i++) System.out.print(" " + na[i]);
+				if (na.length != 3 || na[0] || !na[1] || na[2])
+					throw new TestException("isNA() test failed");
+				System.out.println(" - OK");
+				System.out.println("PASSED");
+			}
+			    
+			
+			{
+				System.out.println("* Test serialization and raw vectors");
+				byte[] b = eng.parseAndEval("serialize(ls, NULL, ascii=FALSE)").asBytes();
+				System.out.println("  serialized ls is "+b.length+" bytes long");
+				eng.assign("r", new REXPRaw(b));
+				String[] s = eng.parseAndEval("unserialize(r)()").asStrings();
+				System.out.println("  we have "+s.length+" items in the workspace");
+				System.out.println("PASSED");
+			}
+			
+			{
+				System.out.println("* Test environment support");
+				REXP x = eng.parseAndEval("new.env(parent=baseenv())");
+				System.out.println("  new.env() = " + x);
+				if (x == null || !x.isEnvironment()) throw new TestException("pull of an environemnt failed");
+				REXPEnvironment e = (REXPEnvironment) x;
+				e.assign("foo", new REXPString("bar"));
+				x = e.get("foo");
+				System.out.println("  get(\"foo\") = " + x);
+				if (x == null || !x.isString() || !x.asString().equals("bar")) throw new TestException("assign/get in an environemnt failed");
+				x = eng.newEnvironment(e, true);
+				System.out.println("  eng.newEnvironment() = " + x);
+				if (x == null || !x.isEnvironment()) throw new TestException("Java-side environment creation failed");
+				x = ((REXPEnvironment)x).parent(true);
+				System.out.println("  parent = " + x);
+				if (x == null || !x.isEnvironment()) throw new TestException("parent environment pull failed");
+				x = e.get("foo");
+				System.out.println("  get(\"foo\",parent) = " + x);
+				if (x == null || !x.isString() || !x.asString().equals("bar")) throw new TestException("get in the parent environemnt failed");
+				System.out.println( "  " ) ; 
+				eng.parseAndEval( "{ .env <- new.env(); .env$x <- 2 }" ) ;
+				REXP env = eng.get(".env", null, false );
+				x = eng.parseAndEval( "x+1", env, true ); 
+				System.out.println( "  R> { .env <- new.env(); .env$x <- 2 }" ); 
+				System.out.println( "  env = eng.get(\".env\", null, false )  " );
+				System.out.print( "  parseAndEval( \"x+1\", env, true)" );
+				if( !( x instanceof REXPDouble ) || x.asDouble() != 3.0 ) throw new TestException("eval within environment failed") ;
+				System.out.println( "  == 3.0     : ok" ); 
+				System.out.println("PASSED");
+			}
+			
+			/* SU: wrap() tests removed since they didn't even compile ... */
+			
+			{
+				System.out.println("* Test generation of exceptions");
+				
+				/* parse exceptions */
+				String cmd = "rnorm(10))" ; // syntax error
+				System.out.println("  eng.parse(\"rnorm(10))\", false )     ->  REngineException( \"Parse Error\" ) " ) ;
+				boolean ok = false; 
+				try{
+					eng.parse( cmd, false ) ; 
+				} catch( REngineException e){
+					ok = true ; 
+				}
+				if( !ok ){
+					throw new TestException( "parse did not generate an exception on syntax error" ) ; 
+				}
+				System.out.println("  eng.parseAndEval(\"rnorm(10))\" )     ->  REngineException( \"Parse Error\" ) " ) ;
+				ok = false; 
+				try{
+					eng.parseAndEval( cmd ) ; 
+				} catch( REngineException e){
+					ok = true ; 
+				}
+				if( !ok ){
+					throw new TestException( "parseAndEval did not generate an exception on syntax error" ) ; 
+				}
+				
+				/* eval exceptions */
+				cmd = "rnorm(5); stop('error'); rnorm(2)" ;
+				System.out.print("  " + cmd  ) ;
+				ok = false; 
+				try{
+					eng.parseAndEval( cmd ) ; 
+				}	catch( REngineException e){
+					if( e instanceof REngineEvalException ){
+						ok = true ; 
+					}
+				}
+				if( !ok ){
+					throw new TestException( "error in R did not generate REngineEvalException" ) ; 
+				}
+				System.out.println( "   -> REngineEvalException  : ok" ) ;
+					
+				System.out.println("PASSED");
+				
+			}
+			
+			{
+				System.out.println("* Test creation of references to java objects");
+				if (!((REXPLogical)eng.parseAndEval("require(rJava)")).isTRUE()[0]) {
+					System.out.println("  - rJava is not available, skipping test\n");
+				} else if (!(eng instanceof org.rosuda.REngine.JRI.JRIEngine)) {
+					System.out.println("  - the used engine is not JRIEngine, skipping test\n");
+				} else {
+					/* try to use rJava before it is initialized */
+					System.out.print("  checking that rJava generate error if not yet loaded" ) ;
+					boolean error = false; 
+					try{
+						eng.parseAndEval( "p <- .jnew( 'java/awt/Point' ) " ) ; 
+					} catch( REngineException e){
+						error = true ;
+					}
+					if( !error ){
+						throw new TestException( "rJava not initiliazed, but did not generate error" ) ;
+					}
+					System.out.println( " : ok" ) ;
+					
+					eng.parseAndEval(".jinit()");
+					REXPReference ref = ((org.rosuda.REngine.JRI.JRIEngine)eng).createRJavaRef( null );
+					if( ref != null ){
+						throw new TestException( "null object should create null REXPReference" ) ; 
+					}
+					System.out.println("  eng.createRJavaRef(null)     ->  null : ok" ) ;
+					
+					System.out.println( "  pushing a java.awt.Point to R " ) ;
+					java.awt.Point p = new java.awt.Point( 10, 10) ;
+					ref = ((org.rosuda.REngine.JRI.JRIEngine)eng).createRJavaRef( p ); 
+					eng.assign( "p", ref ) ;
+					String cmd = "exists('p') && inherits( p, 'jobjRef') && .jclass(p) == 'java.awt.Point' " ; 
+					System.out.println( "  test if the object was pushed correctly " ) ;
+					boolean ok = ((REXPLogical)eng.parseAndEval( cmd )).isTRUE()[0] ;
+					if( !ok ){
+						throw new TestException( "could not push java object to R" ) ;
+					}
+					System.out.println( "  R> " + cmd + "  :  ok " ) ;
+				
+					eng.parseAndEval( ".jcall( p, 'V', 'move', 20L, 20L )" ) ; 
+					System.out.println("  manipulate the object " ) ;
+					if( p.x != 20 || p.y != 20 ){
+						throw new TestException( "not modified the java object with R" ) ; 
+					}
+					System.out.println("  R> .jcall( p, 'V', 'move', 20L, 20L )   -> p.x == 20 ,p.y == 20 : ok " ) ;
+					
+					/* bug #126, use of .jfield with guess of the return class using reflection */
+					System.out.print("  using .jfield with reflection (bug #126)" ) ;
+					eng.parseAndEval( ".jfield( p, , 'x')" ) ; /* used to crash the jvm; (not really - the code in the bgu just forgot to init rJava)  */
+					System.out.println(" : ok " ) ;
+				
+					System.out.println("PASSED");
+				}
+			}
+			
+			
+			/* setEncoding is Rserve's extension - with JRI you have to use UTF-8 locale so this test will fail unless run in UTF-8
+			{ // string encoding test (will work with Rserve 0.5-3 and higher only)
+				System.out.println("* Test string encoding support ...");
+				String t = "ひらがな"; // hiragana (literally, in hiragana ;))
+				eng.setStringEncoding("utf8"); 
+				// -- Just in case the console is not UTF-8 don't display it
+				//System.out.println("  unicode text: "+t);
+				eng.assign("s", t);
+				REXP x = eng.parseAndEval("nchar(s)");
+				System.out.println("  nchar = " + x);
+				if (x == null || !x.isInteger() || x.asInteger() != 4)
+					throw new TestException("UTF-8 encoding string length test failed");
+				// we cannot really test any other encoding ..
+				System.out.println("PASSED");
+			} */
+			
+			eng.close(); // close the engine connection
+			
+			System.out.println("Done.");
+			
+		} catch (REXPMismatchException me) {
+			// some type is different from what you (the programmer) expected
+			System.err.println("Type mismatch: "+me);
+			me.printStackTrace();
+			System.exit(1);
+		} catch (REngineException ee) {
+			// something went wring in the engine
+			System.err.println("REngine exception: "+ee);
+			ee.printStackTrace();
+			System.exit(1);
+		} catch (ClassNotFoundException cnfe) {
+			// class not found is thrown by engineForClass
+			System.err.println("Cannot find JRIEngine class - please fix your class path!\n"+cnfe);
+			System.exit(1);
+		} catch (Exception e) {
+			// some other exception ...
+			System.err.println("Exception: "+e);
+			e.printStackTrace();
+			System.exit(1);
+		}
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/LICENSE b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..42335b1c444381e8e9aa035a28f8d96f0d0747e8
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/LICENSE
@@ -0,0 +1,16 @@
+REngine - Java interface to R
+Copyright (C) 2004,5,6,7  Simon Urbanek
+
+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
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Makefile b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..a57a3109344aa54ba557426d6a2748dcdf6800f1
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Makefile
@@ -0,0 +1,51 @@
+RENG_SRC=$(wildcard *.java)
+RSRV_SRC=$(wildcard Rserve/*.java) $(wildcard Rserve/protocol/*.java)
+JRI_SRC=$(wildcard JRI/*.java)
+
+TARGETS=REngine.jar Rserve.jar
+
+all: $(TARGETS)
+
+JAVAC=javac
+JAVADOC=javadoc
+JDFLAGS=-author -version -breakiterator -link http://java.sun.com/j2se/1.4.2/docs/api/
+JFLAGS+=-source 1.6 -target 1.6
+
+REngine.jar: $(RENG_SRC)
+	@rm -rf org
+	$(JAVAC) -d . $(JFLAGS) $(RENG_SRC)
+	jar fc $@ org
+	rm -rf org
+
+Rserve.jar: $(RSRV_SRC) REngine.jar
+	@rm -rf org
+	$(JAVAC) -d . -cp REngine.jar $(RSRV_SRC)
+	jar fc $@ org
+	rm -rf org
+
+clean:
+	rm -rf org *~ $(TARGETS) doc
+	make -C Rserve clean
+	make -C JRI clean
+
+test:
+	make -C Rserve test
+
+rc:	Rserve.jar Rserve/test/jt.java
+	make -C Rserve/test jt
+
+doc:	$(RENG_SRC) $(RSRV_SRC) $(JRI_SRC)
+	rm -rf $@
+	mkdir $@
+	$(JAVADOC) -d $@ $(JDFLAGS) $^
+
+mvn.pkg:
+	mvn clean package install && (cd Rserve && mvn clean package)
+
+mvn.sign:
+	mvn clean verify install -P release && (cd Rserve && mvn clean verify -P release )
+
+mvn.deploy:
+	mvn clean deploy install -P release && (cd Rserve && mvn clean deploy -P release )
+
+.PHONY: clean all test
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/MutableREXP.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/MutableREXP.java
new file mode 100644
index 0000000000000000000000000000000000000000..8b84a7488cfb100fabdac8b42ba450c064c0b90c
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/MutableREXP.java
@@ -0,0 +1,5 @@
+package org.rosuda.REngine;
+
+public interface MutableREXP {
+	public void setAttribute(String name, REXP value);
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXP.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXP.java
new file mode 100644
index 0000000000000000000000000000000000000000..f1c65242c8c1e78879cfdf2c650434d1d3c2ef1d
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXP.java
@@ -0,0 +1,273 @@
+package org.rosuda.REngine;
+
+/** Basic class representing an object of any type in R. Each type in R in represented by a specific subclass.
+ <p>
+ This class defines basic accessor methods (<tt>as</tt><i>XXX</i>), type check methods (<tt>is</tt><i>XXX</i>), gives access to attributes ({@link #getAttribute}, {@link #hasAttribute}) as well as several convenience methods. If a given method is not applicable to a particular type, it will throw the {@link REXPMismatchException} exception.
+ <p>This root class will throw on any accessor call and returns <code>false</code> for all type methods. This allows subclasses to override accessor and type methods selectively.
+ */
+public class REXP {
+	/** attribute list. This attribute should never be accessed directly. */
+	protected REXPList attr;
+
+	/** public root contrsuctor, same as <tt>new REXP(null)</tt> */
+	public REXP() { }
+	/** public root constructor
+	 @param attr attribute list object (can be <code>null</code> */
+	public REXP(REXPList attr) { this.attr=attr; }
+
+	// type checks
+	/** check whether the <code>REXP</code> object is a character vector (string)
+	 @return <code>true</code> if the receiver is a character vector, <code>false</code> otherwise */
+	public boolean isString() { return false; }
+	/** check whether the <code>REXP</code> object is a numeric vector
+	 @return <code>true</code> if the receiver is a numeric vector, <code>false</code> otherwise */
+	public boolean isNumeric() { return false; }
+	/** check whether the <code>REXP</code> object is an integer vector
+	 @return <code>true</code> if the receiver is an integer vector, <code>false</code> otherwise */
+	public boolean isInteger() { return false; }
+	/** check whether the <code>REXP</code> object is NULL
+	 @return <code>true</code> if the receiver is NULL, <code>false</code> otherwise */
+	public boolean isNull() { return false; }
+	/** check whether the <code>REXP</code> object is a factor
+	 @return <code>true</code> if the receiver is a factor, <code>false</code> otherwise */
+	public boolean isFactor() { return false; }
+	/** check whether the <code>REXP</code> object is a list (either generic vector or a pairlist - i.e. {@link #asList()} will succeed)
+	 @return <code>true</code> if the receiver is a generic vector or a pair-list, <code>false</code> otherwise */
+	public boolean isList() { return false; }
+	/** check whether the <code>REXP</code> object is a pair-list
+	 @return <code>true</code> if the receiver is a pair-list, <code>false</code> otherwise */
+	public boolean isPairList() { return false; }
+	/** check whether the <code>REXP</code> object is a logical vector
+	 @return <code>true</code> if the receiver is a logical vector, <code>false</code> otherwise */
+	public boolean isLogical() { return false; }
+	/** check whether the <code>REXP</code> object is an environment
+	 @return <code>true</code> if the receiver is an environment, <code>false</code> otherwise */
+	public boolean isEnvironment() { return false; }
+	/** check whether the <code>REXP</code> object is a language object
+	 @return <code>true</code> if the receiver is a language object, <code>false</code> otherwise */
+	public boolean isLanguage() { return false; }
+	/** check whether the <code>REXP</code> object is an expression vector
+	 @return <code>true</code> if the receiver is an expression vector, <code>false</code> otherwise */
+	public boolean isExpression() { return false; }
+	/** check whether the <code>REXP</code> object is a symbol
+	 @return <code>true</code> if the receiver is a symbol, <code>false</code> otherwise */
+	public boolean isSymbol() { return false; }
+	/** check whether the <code>REXP</code> object is a vector
+	 @return <code>true</code> if the receiver is a vector, <code>false</code> otherwise */
+	public boolean isVector() { return false; }
+	/** check whether the <code>REXP</code> object is a raw vector
+	 @return <code>true</code> if the receiver is a raw vector, <code>false</code> otherwise */
+	public boolean isRaw() { return false; }
+	/** check whether the <code>REXP</code> object is a complex vector
+	 @return <code>true</code> if the receiver is a complex vector, <code>false</code> otherwise */
+	public boolean isComplex() { return false; }
+	/** check whether the <code>REXP</code> object is a recursive obejct
+	 @return <code>true</code> if the receiver is a recursive object, <code>false</code> otherwise */
+	public boolean isRecursive() { return false; }
+	/** check whether the <code>REXP</code> object is a reference to an R object
+	 @return <code>true</code> if the receiver is a reference, <code>false</code> otherwise */
+	public boolean isReference() { return false; }
+
+	// basic accessor methods
+	/** returns the contents as an array of Strings (if supported by the represented object) */
+	public String[] asStrings() throws REXPMismatchException { throw new REXPMismatchException(this, "String"); }
+	/** returns the contents as an array of integers (if supported by the represented object) */
+	public int[] asIntegers() throws REXPMismatchException { throw new REXPMismatchException(this, "int"); }
+	/** returns the contents as an array of doubles (if supported by the represented object) */
+	public double[] asDoubles() throws REXPMismatchException { throw new REXPMismatchException(this, "double"); }
+	/** returns the contents as an array of bytes (if supported by the represented object) */
+	public byte[] asBytes() throws REXPMismatchException { throw new REXPMismatchException(this, "byte"); }
+	/** returns the contents as a (named) list (if supported by the represented object) */
+	public RList asList() throws REXPMismatchException { throw new REXPMismatchException(this, "list"); }
+	/** returns the contents as a factor (if supported by the represented object) */
+	public RFactor asFactor() throws REXPMismatchException { throw new REXPMismatchException(this, "factor"); }
+	/** attempt to represent the REXP by a native Java object and return it. Note that this may lead to loss of information (e.g., factors may be returned as a string array) and attributes are ignored. Not all R types can be converted to native Java objects. Also note that R has no concept of scalars, so vectors of length 1 will always be returned as an arrays (i.e., <code>int[1]</code> and not <code>Integer</code>). */
+	public Object asNativeJavaObject() throws REXPMismatchException { throw new REXPMismatchException(this, "native Java Object"); }
+
+	/** returns the length of a vector object. Note that we use R semantics here, i.e. a matrix will have a length of <i>m * n</i> since it is represented by a single vector (see {@link #dim} for retrieving matrix and multidimentional-array dimensions).
+	 * @return length (number of elements) in a vector object
+	 * @throws REXPMismatchException if this is not a vector object */
+	public int length() throws REXPMismatchException { throw new REXPMismatchException(this, "vector"); }
+
+	/** returns a boolean vector of the same length as this vector with <code>true</code> for NA values and <code>false</code> for any other values
+	 *  @return a boolean vector of the same length as this vector with <code>true</code> for NA values and <code>false</code> for any other values
+	 * @throws REXPMismatchException if this is not a vector object */
+	public boolean[] isNA() throws REXPMismatchException { throw new REXPMismatchException(this, "vector"); }
+	
+	// convenience accessor methods
+	/** convenience method corresponding to <code>asIntegers()[0]</code>
+	 @return first entry returned by {@link #asInteger} */
+	public int asInteger() throws REXPMismatchException { int[] i = asIntegers(); return i[0]; }
+	/** convenience method corresponding to <code>asDoubles()[0]</code>
+	 @return first entry returned by {@link #asDoubles} */
+	public double asDouble() throws REXPMismatchException { double[] d = asDoubles(); return d[0]; }
+	/** convenience method corresponding to <code>asStrings()[0]</code>
+	 @return first entry returned by {@link #asStrings} */
+	public String asString() throws REXPMismatchException { String[] s = asStrings(); return s[0]; }
+
+	// methods common to all REXPs
+	
+	/** retrieve an attribute of the given name from this object
+	 * @param name attribute name
+	 * @return attribute value or <code>null</code> if the attribute does not exist */
+	public REXP getAttribute(String name) {
+		final REXPList a = _attr();
+		if (a==null || !a.isList()) return null;
+		return a.asList().at(name);
+	}
+	
+	/** checks whether this obejct has a given attribute
+	 * @param name attribute name
+	 * @return <code>true</code> if the attribute exists, <code>false</code> otherwise */
+	public boolean hasAttribute(String name) {
+		final REXPList a = _attr();
+		return (a!=null && a.isList() && a.asList().at(name)!=null);
+	}
+	
+	
+	// helper methods common to all REXPs
+	
+	/** returns dimensions of the object (as determined by the "<code>dim</code>" attribute)
+	 * @return an array of integers with corresponding dimensions or <code>null</code> if the object has no dimension attribute */
+	public int[] dim() {
+		try {
+			return hasAttribute("dim")?_attr().asList().at("dim").asIntegers():null;
+		} catch (REXPMismatchException me) {
+		}
+		return null;
+	}
+	
+	/** determines whether this object inherits from a given class in the same fashion as the <code>inherits()</code> function in R does (i.e. ignoring S4 inheritance)
+	 * @param klass class name
+	 * @return <code>true</code> if this object is of the class <code>klass</code>, <code>false</code> otherwise */
+	public boolean inherits(String klass) {
+		if (!hasAttribute("class")) return false;
+		try {
+			String c[] = getAttribute("class").asStrings();
+			if (c != null) {
+				int i = 0;
+				while (i < c.length) {
+					if (c[i]!=null && c[i].equals(klass)) return true;
+					i++;
+				}
+			}
+		} catch (REXPMismatchException me) {
+		}
+		return false;
+	}
+
+	/** this method allows a limited access to object's attributes - <b>{@link #getAttribute} should be used instead to access specific attributes</b>!. Note that the {@link #attr} attribute should never be used directly incase the REXP implements a lazy access (e.g. via a reference)
+	    @return list of attributes or <code>null</code> if the object has no attributes
+	 */
+	public REXPList _attr() { return attr; }
+	
+	/** returns a string description of the object
+	 @return string describing the object - it can be of an arbitrary form and used only for debugging (do not confuse with {@link #asString()} for accessing string REXPs) */
+	public String toString() {
+		return super.toString()+((attr!=null)?"+":"");
+	}
+	
+	/** returns representation that it useful for debugging (e.g. it includes attributes and may include vector values -- see {@link #maxDebugItems})
+	 @return extended description of the obejct -- it may include vector values
+	 */
+	public String toDebugString() {
+		return (attr!=null)?(("<"+attr.toDebugString()+">")+super.toString()):super.toString();
+	}
+	
+	//======= complex convenience methods
+	/** returns the content of the REXP as a matrix of doubles (2D-array: m[rows][cols]). This is the same form as used by popular math packages for Java, such as JAMA. This means that following leads to desired results:<br>
+	 <code>Matrix m=new Matrix(c.eval("matrix(c(1,2,3,4,5,6),2,3)").asDoubleMatrix());</code><br>
+	 @return 2D array of doubles in the form double[rows][cols] or <code>null</code> if the contents is no 2-dimensional matrix of doubles */
+	public double[][] asDoubleMatrix() throws REXPMismatchException {
+		double[] ct = asDoubles();
+		REXP dim = getAttribute("dim");
+		if (dim == null) throw new REXPMismatchException(this, "matrix (dim attribute missing)");
+		int[] ds = dim.asIntegers();
+		if (ds.length != 2) throw new REXPMismatchException(this, "matrix (wrong dimensionality)");
+		int m = ds[0], n = ds[1];
+		
+		double[][] r = new double[m][n];
+		// R stores matrices as matrix(c(1,2,3,4),2,2) = col1:(1,2), col2:(3,4)
+		// we need to copy everything, since we create 2d array from 1d array
+		int k = 0;
+		for (int i = 0; i < n; i++)
+			for (int j = 0; j < m; j++) 
+				r[j][i] = ct[k++];
+		return r;
+	}
+	
+	/** creates a REXP that represents a double matrix in R based on matrix of doubles (2D-array: m[rows][cols]). This is the same form as used by popular math packages for Java, such as JAMA. The result of this function can be used in {@link REngine.assign} to store a matrix in R.
+	 @param matrix array <code>double[rows][colums]</code> containing the matrix to convert into a REXP. If <code>matrix</code> is <code>null</code> or either of the dimensions is 0 then the resulting matrix will have the dimensions <code>0 x 0</code> (Note: Java cannot represent <code>0 x n</code> matrices for <code>n &gt; 0</code>, so special matrices with one dimension of 0 can only be created by setting dimensions directly).
+	 @return <code>REXPDouble</code> with "dim" attribute which constitutes a matrix in R */
+	public static REXP createDoubleMatrix(double[][] matrix) {
+		int m = 0, n = 0;
+		double a[];
+		if (matrix != null && matrix.length != 0 && matrix[0].length != 0) {
+			m = matrix.length;
+			n = matrix[0].length;
+			a = new double[m * n];
+			int k = 0;
+			for (int j = 0; j < n; j++)
+				for (int i = 0; i < m; i++)
+					a[k++] = matrix[i][j];
+		} else a = new double[0];
+		return new REXPDouble(a,
+				      new REXPList(
+						   new RList(
+							     new REXP[] { new REXPInteger(new int[] { m, n }) },
+							     new String[] { "dim" })
+						   )
+				      );
+	}
+	
+	//======= tools
+	/** creates a data frame object from a list object using integer row names
+	 *  @param l a (named) list of vectors ({@link REXPVector} subclasses), each element corresponds to a column and all elements must have the same length
+	 *  @return a data frame object
+	 *  @throws REXPMismatchException if the list is empty or any of the elements is not a vector */
+	public static REXP createDataFrame(RList l) throws REXPMismatchException {
+		if (l == null || l.size() < 1) throw new REXPMismatchException(new REXPList(l), "data frame (must have dim>0)");
+		if (!(l.at(0) instanceof REXPVector)) throw new REXPMismatchException(new REXPList(l), "data frame (contents must be vectors)");
+		REXPVector fe = (REXPVector) l.at(0);
+		return
+		new REXPGenericVector(l,
+							  new REXPList(
+									new RList(
+										   new REXP[] {
+											   new REXPString("data.frame"),
+											   new REXPString(l.keys()),
+											   new REXPInteger(new int[] { REXPInteger.NA, -fe.length() })
+										   },
+										   new String[] {
+											   "class",
+											   "names",
+											   "row.names"
+										   })));
+	}
+
+	public static REXP asCall(REXP what, REXP[] args) {
+		RList l = new RList();
+		l.add(what);
+		for (int i = 0; i < args.length; i++) l.add(args[i]);
+		return new REXPLanguage(l);
+	}
+	public static REXP asCall(String name, REXP[] args) {
+		return asCall(new REXPSymbol(name), args);
+	}
+
+	public static REXP asCall(String name, REXP arg1) {
+		return new REXPLanguage(new RList(new REXP[] { new REXPSymbol(name), arg1 })); }
+	public static REXP asCall(String name, REXP arg1, REXP arg2) {
+		return new REXPLanguage(new RList(new REXP[] { new REXPSymbol(name), arg1, arg2 })); }
+	public static REXP asCall(String name, REXP arg1, REXP arg2, REXP arg3) {
+		return new REXPLanguage(new RList(new REXP[] { new REXPSymbol(name), arg1, arg2, arg3 })); }
+	public static REXP asCall(REXP what, REXP arg1) {
+		return new REXPLanguage(new RList(new REXP[] { what, arg1 })); }
+	public static REXP asCall(REXP what, REXP arg1, REXP arg2) {
+		return new REXPLanguage(new RList(new REXP[] { what, arg1, arg2 })); }
+	public static REXP asCall(REXP what, REXP arg1, REXP arg2, REXP arg3) {
+		return new REXPLanguage(new RList(new REXP[] { what, arg1, arg2, arg3 })); }
+	
+	/** specifies how many items of a vector or list will be displayed in {@link #toDebugString} */
+	public static int maxDebugItems = 32;
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPDouble.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPDouble.java
new file mode 100644
index 0000000000000000000000000000000000000000..c0d47c8201ce95866a01a19be5df0faa3d8584b3
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPDouble.java
@@ -0,0 +1,84 @@
+package org.rosuda.REngine;
+
+/** REXPDouble represents a vector of double precision floating point values. */
+public class REXPDouble extends REXPVector {
+	private double[] payload;
+	
+	/** NA real value as defined in R. Note: it can NOT be used in comparisons, you must use {@link #isNA(double)} instead. */
+	public static final double NA = Double.longBitsToDouble(0x7ff00000000007a2L);
+	
+	/** Java screws up the bits in NA real values, so we cannot compare to the real bits used by R (0x7ff00000000007a2L) but use this value which is obtained by passing the bits through Java's double type */
+	static final long NA_bits = Double.doubleToRawLongBits(Double.longBitsToDouble(0x7ff00000000007a2L));
+	
+	/** checks whether a given double value is a NA representation in R. Note that NA is NaN but not all NaNs are NA. */
+	public static boolean isNA(double value) {
+		/* on OS X i386 the MSB of the fraction is set even though R doesn't set it.
+		   Although this is technically a good idea (to make it a QNaN) it's not what R does and thus makes the comparison tricky */
+		return (Double.doubleToRawLongBits(value) & 0xfff7ffffffffffffL) == (NA_bits & 0xfff7ffffffffffffL);
+	}
+
+	/** create real vector of the length 1 with the given value as its first (and only) element */
+	public REXPDouble(double load) {
+		super();
+		payload=new double[] { load };
+	}
+	
+	public REXPDouble(double[] load) {
+		super();
+		payload=(load==null)?new double[0]:load;
+	}
+
+	public REXPDouble(double[] load, REXPList attr) {
+		super(attr);
+		payload=(load==null)?new double[0]:load;
+	}
+	
+	public int length() { return payload.length; }
+
+	public Object asNativeJavaObject() {
+		return payload;
+	}
+
+	/** return <code>true</code> */
+	public boolean isNumeric() { return true; }
+
+	/** returns the values represented by this vector */
+	public double[] asDoubles() { return payload; }
+
+	/** converts the values of this vector into integers by cast */
+	public int[] asIntegers() {
+		int[] a = new int[payload.length];
+		int i = 0;
+		while (i < payload.length) { a[i] = (int) payload[i]; i++; }
+		return a;
+	}
+
+	/** converts the values of this vector into strings */
+	public String[] asStrings() {
+		String[] s = new String[payload.length];
+		int i = 0;
+		while (i < payload.length) { s[i] = ""+payload[i]; i++; }
+		return s;
+	}
+	
+	/** returns a boolean vector of the same length as this vector with <code>true</code> for NA values and <code>false</code> for any other values (including NaNs) */
+	public boolean[] isNA() {
+		boolean a[] = new boolean[payload.length];
+		int i = 0;
+		while (i < a.length) { a[i] = isNA(payload[i]); i++; }
+		return a;
+	}
+	
+	public String toDebugString() {
+		StringBuffer sb = new StringBuffer(super.toDebugString()+"{");
+		int i = 0;
+		while (i < payload.length && i < maxDebugItems) {
+			if (i>0) sb.append(",");
+			sb.append(payload[i]);
+			i++;
+		}
+		if (i < payload.length) sb.append(",..");
+		return sb.toString()+"}";
+	}
+	
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPEnvironment.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPEnvironment.java
new file mode 100644
index 0000000000000000000000000000000000000000..d4d4ab386c2475062b8c12a26f7c08f80a6d7211
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPEnvironment.java
@@ -0,0 +1,70 @@
+package org.rosuda.REngine;
+// environments are like REXPReferences except that they cannot be resolved
+
+/** REXPEnvironment represents an environment in R. Very much like {@link org.rosuda.REngine.REXPReference} this is a proxy object to the actual object on the R side. It provides methods for accessing the content of the environment. The actual implementation may vary by the back-end used and not all engines support environments. Check {@link org.rosuda.REngine.REngine.supportsEnvironments()} for the given engine. Environments are specific for a given engine, they cannot be passed across engines.
+ */
+public class REXPEnvironment extends REXP {
+	/** engine associated with this environment */
+	REngine eng;
+	/** transparent handle that can be used by the engine to indentify the environment. It is not used by REngine API itself. */
+	Object handle;
+	
+	/** create a new environemnt reference - this constructor should never be used directly, use {@link REngine.newEnvironment()} instead.
+	 *  @param eng engine responsible for this environment
+	 *  @param handle handle used by the engine to identify this environment
+	 */
+	public REXPEnvironment(REngine eng, Object handle) {
+		super();
+		this.eng = eng;
+		this.handle = handle;
+	}
+	
+	public boolean isEnvironment() { return true; }
+	
+	/** returns the handle used to identify this environemnt in the engine - for internal use by engine implementations only
+	 *  @return handle of this environment */
+	public Object getHandle() { return handle; }
+	
+	/** get a value from this environment
+	 *  @param name name of the value
+	 *  @param resolve if <code>false</code> returns a reference to the object, if <code>false</code> the reference is resolved
+	 *  @return value corresponding to the symbol name or possibly <code>null</code> if the value is unbound (the latter is currently engine-specific) */
+	public REXP get(String name, boolean resolve) throws REngineException {
+		try {
+			return eng.get(name, this, resolve);
+		} catch (REXPMismatchException e) { // this should never happen because this is always guaranteed to be REXPEnv
+			throw(new REngineException(eng, "REXPMismatchException:"+e+" in get()"));
+		}
+	}
+
+	/** get a value from this environment - equavalent to <code>get(name, true)</code>.
+	 *  @param name name of the value
+	 *  @return value (see {@link #get(String,boolean)}) */
+	public REXP get(String name) throws REngineException {
+		return get(name, true);
+	}
+	
+	/** assigns a value to a given symbol name
+	 *  @param name symbol name
+	 *  @param value value */
+	public void assign(String name, REXP value) throws REngineException, REXPMismatchException {
+		eng.assign(name, value, this);
+	}
+	
+	/** returns the parent environment or a reference to it
+	 *  @param resolve if <code>true</code> returns the environemnt, otherwise a reference. 
+	 *  @return parent environemnt (or a reference to it) */
+	public REXP parent(boolean resolve) throws REngineException {
+		try {
+			return eng.getParentEnvironment(this, resolve);
+		} catch (REXPMismatchException e) { // this should never happen because this is always guaranteed to be REXPEnv
+			throw(new REngineException(eng, "REXPMismatchException:"+e+" in parent()"));
+		}
+	}
+
+	/** returns the parent environment. This is equivalent to <code>parent(true)</code>.
+	 *  @return parent environemnt */
+	public REXPEnvironment parent() throws REngineException {
+		return (REXPEnvironment) parent(true);
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPExpressionVector.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPExpressionVector.java
new file mode 100644
index 0000000000000000000000000000000000000000..c16ff5308a50ede9e7260fb79a170a2539cc1ee1
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPExpressionVector.java
@@ -0,0 +1,15 @@
+package org.rosuda.REngine;
+
+/** REXPExpressionVector represents a vector of expressions in R. It is essentially a special kind of generic vector - its elements are expected to be valid R expressions. */
+public class REXPExpressionVector extends REXPGenericVector {
+	/** create a new vector of expressions from a list of expressions.
+	 *  @param list list of expressions to store in this vector */
+	public REXPExpressionVector(RList list) { super(list); }	
+
+	/** create a new vector of expressions from a list of expressions.
+	 *  @param list list of expressions to store in this vector
+	 *  @param attr attributes for the R object */
+	public REXPExpressionVector(RList list, REXPList attr) { super(list, attr); }
+
+	public boolean isExpression() { return true; }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPFactor.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPFactor.java
new file mode 100644
index 0000000000000000000000000000000000000000..11c94a894666fd621815cb4926a4da47c22c7537
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPFactor.java
@@ -0,0 +1,74 @@
+package org.rosuda.REngine;
+
+/** REXPFactor represents a factor in R. It is an integer vector with levels for each contained category. */
+// FIXME: this is currently somehow screwed - the concept of RFactor and REXPFactor is duplicate - we need to remove this historical baggage
+public class REXPFactor extends REXPInteger {
+	private String[] levels;
+	private RFactor factor;
+	
+	/** create a new factor REXP
+	 *  @param ids indices (one-based!)
+	 *  @param levels levels */
+	public REXPFactor(int[] ids, String[] levels) {
+		super(ids);
+		this.levels = (levels==null)?(new String[0]):levels;
+		factor = new RFactor(this.payload, this.levels, false, 1);
+		attr = new REXPList(
+							new RList(
+									  new REXP[] {
+										  new REXPString(this.levels), new REXPString("factor")
+									  }, new String[] { "levels", "class" }));
+	}
+
+	/** create a new factor REXP
+	 *  @param ids indices (one-based!)
+	 *  @param levels levels
+	 *  @param attr attributes */
+	public REXPFactor(int[] ids, String[] levels, REXPList attr) {
+		super(ids, attr);
+		this.levels = (levels==null)?(new String[0]):levels;
+		factor = new RFactor(this.payload, this.levels, false, 1);
+	}
+	
+	/** create a new factor REXP from an existing RFactor
+	 *  @param factor factor object (can be of any index base, the contents will be pulled with base 1) */
+	public REXPFactor(RFactor factor) {
+		super(factor.asIntegers(1));
+		this.factor = factor;
+		this.levels = factor.levels();
+		attr = new REXPList(
+							new RList(
+									  new REXP[] {
+										  new REXPString(this.levels), new REXPString("factor")
+									  }, new String[] { "levels", "class" }));
+	}
+	
+	/** create a new factor REXP from an existing RFactor
+	 *  @param factor factor object (can be of any index base, the contents will be pulled with base 1)
+	 *  @param attr attributes */
+	public REXPFactor(RFactor factor, REXPList attr) {
+		super(factor.asIntegers(1), attr);
+		this.factor = factor;
+		this.levels = factor.levels();
+	}
+
+	public boolean isFactor() { return true; }
+
+	/** return the contents as a factor - the factor is guaranteed to have index base 1
+	 *  @return the contents as a factor */
+	public RFactor asFactor() {
+		return factor;
+	}
+
+	public String[] asStrings() {
+		return factor.asStrings();
+	}
+
+	public Object asNativeJavaObject() {
+		return asStrings();
+	}
+	
+	public String toString() {
+		return super.toString()+"["+levels.length+"]";
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPGenericVector.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPGenericVector.java
new file mode 100644
index 0000000000000000000000000000000000000000..f44a92c486d8c1ef37d9de5a0ca4ecd070f8264c
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPGenericVector.java
@@ -0,0 +1,93 @@
+package org.rosuda.REngine;
+import java.util.Vector;
+import java.util.HashMap;
+
+/** REXPGenericVector represents a generic vector in R. Its elements can be typically of any {@link REXP} type. */
+public class REXPGenericVector extends REXPVector {
+	/** payload */
+	private RList payload;
+	
+	/** creates a new generic vector from a list. If the list is named, the <code>"names"</code> attribute is created automatically from it.
+	 *  @param list list to create the vector from */
+	public REXPGenericVector(RList list) {
+		super();
+		payload=(list==null)?new RList():list;
+		// automatically generate 'names' attribute
+		if (payload.isNamed())
+			attr = new REXPList(
+				new RList(new REXP[] { new REXPString(payload.keys()) },
+						  new String[] { "names" }));
+	}
+	
+	/** creates a new generic vector from a list. Note that the names in the list are ignored as they are expected to be defined by the attributes parameter.
+	 *  @param list list to create the vector from (names are ignored - use {@link #REXPGenericVector(RList)} or the <code>"names"</code> attribute for named lists
+	 *  @param attr attributes */
+	public REXPGenericVector(RList list, REXPList attr) {
+		super(attr);
+		payload=(list==null)?new RList():list;
+	}
+
+	/* generic vectors are converted either to a <code>Map</code> (if it is a named vector and there are no duplicate names) or a <code>Vector</code>. The contained elements are converted using <code>asNativeJavaObject</code> recursively. */
+	public Object asNativeJavaObject() throws REXPMismatchException {
+		// we need to convert the inside as well
+		int n = payload.size();
+
+		// named list -> map but only if
+		//  a) all names are present
+		//  b) there are no duplicates in the names
+		if (payload.isNamed()) {
+			String[] names = payload.keys();
+			if (names.length == n) {
+				HashMap map = new HashMap();
+				boolean valid = true;
+				for (int i = 0; i < n; i++) {
+					if (map.containsKey(names[i])) {
+						valid = false;
+						break;
+					}
+					Object value = payload.elementAt(i);
+					if (value != null)
+						value = ((REXP) value).asNativeJavaObject();
+					map.put(names[i], value);
+				}
+				if (valid)
+					return map;
+			}
+		}
+
+		// otherwise drop names and use just a vector
+		Vector v = new Vector();
+		for (int i = 0; i < n; i++) {
+			Object value = payload.elementAt(i);
+			if (value != null)
+				value = ((REXP) value).asNativeJavaObject();
+			v.addElement(value);
+		}
+
+		return v;
+	}
+	
+	public int length() { return payload.size(); }
+
+	public boolean isList() { return true; }
+
+	public boolean isRecursive() { return true; }
+
+	public RList asList() { return payload; }
+	
+	public String toString() {
+		return super.toString()+(asList().isNamed()?"named":"");
+	}
+
+	public String toDebugString() {
+		StringBuffer sb = new StringBuffer(super.toDebugString()+"{");
+		int i = 0;
+		while (i < payload.size() && i < maxDebugItems) {
+			if (i>0) sb.append(",\n");
+			sb.append(payload.at(i).toDebugString());
+			i++;
+		}
+		if (i < payload.size()) sb.append(",..");
+		return sb.toString()+"}";
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPInteger.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPInteger.java
new file mode 100644
index 0000000000000000000000000000000000000000..efe17b766d67508e4f02bb69b1b96d7d4a7fc988
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPInteger.java
@@ -0,0 +1,77 @@
+package org.rosuda.REngine;
+
+/** REXPDouble represents a vector of integer values. */
+public class REXPInteger extends REXPVector {
+	protected int[] payload;
+	
+	/** NA integer value as defined in R. Unlike its real equivalent this one can be used in comparisons, although {@link #isNA(int) } is provided for consistency. */
+	public static final int NA = -2147483648;
+
+	public static boolean isNA(int value) {
+		return (value == NA);
+	}
+	
+	/** create integer vector of the length 1 with the given value as its first (and only) element */
+	public REXPInteger(int load) {
+		super();
+		payload=new int[] { load };
+	}
+	
+	/** create integer vector with the payload specified by <code>load</code> */
+	public REXPInteger(int[] load) {
+		super();
+		payload=(load==null)?new int[0]:load;
+	}
+
+	/** create integer vector with the payload specified by <code>load</code> and attributes <code>attr</code> */
+	public REXPInteger(int[] load, REXPList attr) {
+		super(attr);
+		payload=(load==null)?new int[0]:load;
+	}
+
+	public Object asNativeJavaObject() {
+		return payload;
+	}
+	
+	public int length() { return payload.length; }
+
+	public boolean isInteger() { return true; }
+	public boolean isNumeric() { return true; }
+
+	public int[] asIntegers() { return payload; }
+
+	/** returns the contents of this vector as doubles */
+	public double[] asDoubles() {
+		double[] d = new double[payload.length];
+		int i = 0;
+		while (i < payload.length) { d[i] = (double) payload[i]; i++; }
+		return d;
+	}
+
+	/** returns the contents of this vector as strings */
+	public String[] asStrings() {
+		String[] s = new String[payload.length];
+		int i = 0;
+		while (i < payload.length) { s[i] = ""+payload[i]; i++; }
+		return s;
+	}
+	
+	public boolean[] isNA() {
+		boolean a[] = new boolean[payload.length];
+		int i = 0;
+		while (i < a.length) { a[i] = (payload[i]==NA); i++; }
+		return a;
+	}
+	
+	public String toDebugString() {
+		StringBuffer sb = new StringBuffer(super.toDebugString()+"{");
+		int i = 0;
+		while (i < payload.length && i < maxDebugItems) {
+			if (i>0) sb.append(",");
+			sb.append(payload[i]);
+			i++;
+		}
+		if (i < payload.length) sb.append(",..");
+		return sb.toString()+"}";
+	}	
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPJavaReference.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPJavaReference.java
new file mode 100644
index 0000000000000000000000000000000000000000..305969748d52487809e723427e108ac4a7175c6d
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPJavaReference.java
@@ -0,0 +1,26 @@
+package org.rosuda.REngine;
+
+/** REXPJavaReference is a reference to a Java object that has been resolved from is R wrapper. Note that not all engines support references. */
+public class REXPJavaReference extends REXP {
+	/** the referenced Java object */
+	Object object;
+
+	/** creates a new Java reference R object
+	 *  @param o Java object referenced by the REXP */
+	public REXPJavaReference(Object o) { super(); this.object = o; }
+
+	/** creates a new Java reference R object
+	 *  @param o Java object referenced by the REXP
+	 *  @param attr attributes (of the R wrapper) */
+	public REXPJavaReference(Object o, REXPList attr) { super(attr); this.object = o; }
+	
+	/** returns the Java object referenced by this REXP
+	 *  @return Java object */
+	public Object getObject() { return object; }
+
+ 	public Object asNativeJavaObject() { return object; }
+	
+	public String toString() {
+		return super.toString() + "[" + object + "]";
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPLanguage.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPLanguage.java
new file mode 100644
index 0000000000000000000000000000000000000000..3ec3385ebd13f4438ca3dad45dd15a97770cb874
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPLanguage.java
@@ -0,0 +1,9 @@
+package org.rosuda.REngine;
+
+/** represents a language object in R */
+public class REXPLanguage extends REXPList {
+	public REXPLanguage(RList list) { super(list); }
+	public REXPLanguage(RList list, REXPList attr) { super(list, attr); }
+	
+	public boolean isLanguage() { return true; }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPList.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPList.java
new file mode 100644
index 0000000000000000000000000000000000000000..f510b7e9688ac7383217ac4fe0c62184e0c2128e
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPList.java
@@ -0,0 +1,64 @@
+package org.rosuda.REngine;
+
+/** Represents a pairlist in R. Unlike the actual internal R implementation this one
+    does not use CAR/CDR/TAG linked representation but a @link{RList} object. */
+public class REXPList extends REXPVector {
+	private RList payload;
+	
+	/* create a new pairlist with the contents of a named R list and no attributes.
+	   @param list named list with the contents */
+	public REXPList(RList list) {
+		super();
+		payload=(list==null)?new RList():list;
+	}
+
+	/* create a new pairlist with the contents of a named R list and attributes.
+	   @param list named list with the contents
+	   @param attr attributes */
+	public REXPList(RList list, REXPList attr) {
+		super(attr);
+		payload=(list==null)?new RList():list;
+	}
+
+	/* create a pairlist containing just one pair comprising of one value and one name.
+	   This is a convenience constructor most commonly used to create attribute pairlists.
+	   @param value of the element in the pairlist (must not be <code>null</code>)
+	   @param name of the element in the pairlist (must not be <code>null</code>) */
+	public REXPList(REXP value, String name) {
+		super();
+		payload = new RList(new REXP[] { value }, new String[] { name });
+	}
+
+	public Object asNativeJavaObject() throws REXPMismatchException {
+		// since REXPGenericVector does the hard work, we just cheat and use it in turn
+		REXPGenericVector v = new REXPGenericVector(payload);
+		return v.asNativeJavaObject();
+	}
+
+	public int length() { return payload.size(); }
+
+	public boolean isList() { return true; }
+	public boolean isPairList() { return true; }
+
+	public boolean isRecursive() { return true; }
+
+	public RList asList() { return payload; }
+	
+	public String toString() {
+		return super.toString()+(asList().isNamed()?"named":"");
+	}
+	
+	public String toDebugString() {
+		StringBuffer sb = new StringBuffer(super.toDebugString()+"{");
+		int i = 0;
+		while (i < payload.size() && i < maxDebugItems) {
+			if (i>0) sb.append(",\n");
+			String name = payload.keyAt(i);
+			if (name!=null) sb.append(name+"=");
+			sb.append(payload.at(i).toDebugString());
+			i++;
+		}
+		if (i < payload.size()) sb.append(",..");
+		return sb.toString()+"}";
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPLogical.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPLogical.java
new file mode 100644
index 0000000000000000000000000000000000000000..0769c279433ef81b05c59462513481b73357ff36
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPLogical.java
@@ -0,0 +1,140 @@
+package org.rosuda.REngine;
+
+/** REXPLogical represents a vector of logical values (TRUE, FALSE or NA). Unlike Java's boolean type R's logicals support NA values therefore either of {@link #isTRUE()}, {@link #isFALSE()} or {@link #isNA()} must be used to convert logicals to boolean values. */
+public class REXPLogical extends REXPVector {
+	protected byte[] payload;
+	
+	/** NA integer value as defined in R. Unlike its real equivalent this one can be used in comparisons, although {@link #isNA(int) } is provided for consistency. */
+	static final int NA_internal = -2147483648;
+
+	/** NA boolean value as used in REXPLogical implementation. This differs from the value used in R since R uses int data type and we use byte. Unlike its real equivalent this one can be used in comparisons, although {@link #isNA(byte) } is provided for consistency. */
+	public static final byte NA = -128;
+	public static final byte TRUE = 1;
+	public static final byte FALSE = 0;
+	
+	public static boolean isNA(byte value) {
+		return (value == NA);
+	}
+	
+	/** create logical vector of the length 1 with the given value as its first (and only) element */
+	public REXPLogical(boolean load) {
+		super();
+		payload = new byte[] { load ? TRUE : FALSE };
+	}
+
+	/** create logical vector of the length 1 with the given value as its first (and only) element */
+	public REXPLogical(byte load) {
+		super();
+		payload = new byte[] { load };
+	}
+	
+	/** create logical vector with the payload specified by <code>load</code> */
+	public REXPLogical(byte[] load) {
+		super();
+		payload = (load==null) ? new byte[0]:load;
+	}
+
+	/** create logical vector with the payload specified by <code>load</code> */
+	public REXPLogical(boolean[] load) {
+		super();
+		payload = new byte[(load == null) ? 0 : load.length];
+		if (load != null)
+			for (int i = 0; i < load.length; i++)
+				payload[i] = load[i] ? TRUE : FALSE;
+	}
+	
+	/** create integer vector with the payload specified by <code>load</code> and attributes <code>attr</code> */
+	public REXPLogical(byte[] load, REXPList attr) {
+		super(attr);
+		payload = (load==null) ? new byte[0] : load;
+	}
+	
+	/** create integer vector with the payload specified by <code>load</code> and attributes <code>attr</code> */
+	public REXPLogical(boolean[] load, REXPList attr) {
+		super(attr);
+		payload = new byte[(load == null) ? 0 : load.length];
+		if (load != null)
+			for (int i = 0; i < load.length; i++)
+				payload[i] = load[i] ? TRUE : FALSE;
+	}
+
+	public int length() { return payload.length; }
+
+	public boolean isLogical() { return true; }
+
+	public Object asNativeJavaObject() {
+		return payload;
+	}
+
+	public int[] asIntegers() {
+		int p[] = new int[payload.length];
+		for (int i = 0; i < payload.length; i++) // map bytes to integers including NA representation
+			p[i] = (payload[i] == NA) ? REXPInteger.NA : ((payload[i] == FALSE) ? 0 : 1);
+		return p;
+	}
+
+	public byte[] asBytes() { return payload; }
+
+	/** returns the contents of this vector as doubles */
+	public double[] asDoubles() {
+		double[] d = new double[payload.length];
+		for (int i = 0; i < payload.length; i++)
+			d[i] = (payload[i] == NA) ? REXPDouble.NA : ((payload[i] == FALSE) ? 0.0 : 1.0);
+		return d;
+	}
+
+	/** returns the contents of this vector as strings */
+	public String[] asStrings() {
+		String[] s = new String[payload.length];
+		for (int i = 0; i < payload.length; i++)
+			s[i] = (payload[i] == NA) ? "NA" : ((payload[i] == FALSE) ? "FALSE" : "TRUE");
+		return s;
+	}
+	
+	public boolean[] isNA() {
+		boolean a[] = new boolean[payload.length];
+		int i = 0;
+		while (i < a.length) { a[i] = (payload[i] == NA); i++; }
+		return a;
+	}
+	
+	/** returns a boolean array of the same langth as the receiver with <code>true</code> for <code>TRUE</code> values and <code>false</code> for <code>FALSE</code> and <code>NA</code> values.
+	 @return boolean array */
+	public boolean[] isTRUE() {
+		boolean a[] = new boolean[payload.length];
+		int i = 0;
+		while (i < a.length) { a[i] = (payload[i] != NA && payload[i] != FALSE); i++; }
+		return a;
+	}
+	
+	/** returns a boolean array of the same langth as the receiver with <code>true</code> for <code>FALSE</code> values and <code>false</code> for <code>TRUE</code> and <code>NA</code> values.
+	 @return boolean array */
+	public boolean[] isFALSE() {
+		boolean a[] = new boolean[payload.length];
+		int i = 0;
+		while (i < a.length) { a[i] = (payload[i] == FALSE); i++; }
+		return a;
+	}
+	
+	/** returns a boolean array of the same langth as the receiver with <code>true</code> for <code>TRUE</code> values and <code>false</code> for <code>FALSE</code> and <code>NA</code> values.
+	 @return boolean array
+	 @deprecated replaced by {@link #isTRUE()} for consistency with R nomenclature. */
+	public boolean[] isTrue() { return isTRUE(); }
+
+	/** returns a boolean array of the same langth as the receiver with <code>true</code> for <code>FALSE</code> values and <code>false</code> for <code>TRUE</code> and <code>NA</code> values.
+	 @return boolean array
+	 @deprecated replaced by {@link #isTRUE()} for consistency with R nomenclature. */
+	public boolean[] isFalse() { return isFALSE(); }
+
+	public String toDebugString() {
+		StringBuffer sb = new StringBuffer(super.toDebugString()+"{");
+		int i = 0;
+		while (i < payload.length && i < maxDebugItems) {
+			if (i>0) sb.append(",");
+			sb.append((payload[i] == NA) ? "NA" : ((payload[i] == FALSE) ? "FALSE" : "TRUE"));
+			i++;
+		}
+		if (i < payload.length) sb.append(",..");
+		return sb.toString()+"}";
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPMismatchException.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPMismatchException.java
new file mode 100644
index 0000000000000000000000000000000000000000..5b749a27b6efa5cfa91158461edb1a97a6495c6e
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPMismatchException.java
@@ -0,0 +1,40 @@
+// REngine - generic Java/R API
+//
+// Copyright (C) 2007,2008 Simon Urbanek
+// --- for licensing information see LICENSE file in the distribution ---
+//
+//  REXPMismatch.java
+//
+//  Created by Simon Urbanek on 2007/05/03
+//
+//  $Id: REngineException.java 2555 2006-06-21 20:36:42Z urbaneks $
+//
+
+package org.rosuda.REngine;
+
+/** This exception is thrown whenever the operation requested is not supported by the given R object type, e.g. using <tt>asStrings</tt> on an S4 object. Most {@link REXP} methods throw this exception. Previous R/Java interfaces were silently returning <code>null</code> in those cases, but using exceptions helps to write more robust code. */
+public class REXPMismatchException extends Exception {
+	REXP sender;
+	String access;
+	
+	/** primary constructor. The exception message will be formed as "attempt to access &lt;REXP-class&gt; as &lt;access-string&gt;"
+	 * @param sender R object that triggered this exception (cannot be <code>null</code>!)
+	 * @param access assumed type of the access that was requested. It should be a simple name of the assumed type (e.g. <tt>"vector"</tt>). The type name can be based on R semantics beyond basic types reflected by REXP classes. In cases where certain assertions were not satisfied, the string should be of the form <tt>"type (assertion)"</tt> (e.g. <tt>"data frame (must have dim>0)"</tt>). */
+    public REXPMismatchException(REXP sender, String access) {
+        super("attempt to access "+sender.getClass().getName()+" as "+access);
+		this.sender = sender;
+		this.access = access;
+    }
+	
+	/** retrieve the exception sender/origin
+	 * @return REXP object that triggered the exception */
+	public REXP getSender() {
+		return sender;
+	}
+	
+	/** get the assumed access type that was violated by the sender.
+	 * @return string describing the access type. See {@link #REXPMismatchException} for details. */
+	public String getAccess() {
+		return access;
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPNull.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPNull.java
new file mode 100644
index 0000000000000000000000000000000000000000..f183d28faf20f755e56db3af118a45c2cf3c3de6
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPNull.java
@@ -0,0 +1,15 @@
+package org.rosuda.REngine;
+
+/** represents a NULL object in R.
+ <p>
+ Note: there is a slight asymmetry - in R NULL is represented by a zero-length pairlist. For this reason <code>REXPNull</code> returns <code>true</code> for {@link #isList()} and {@link #asList()} will return an empty list. Nonetheless <code>REXPList</code> of the length 0 will NOT return <code>true</code> in {@link #isNull()} (currently), becasue it is considered a different object in Java. These nuances are still subject to change, because it's not clear how it should be treated. At any rate use <code>REXPNull</code> instead of empty <code>REXPList</code> if NULL is the intended value.
+ */
+public class REXPNull extends REXP {
+	public REXPNull() { super(); }
+	public REXPNull(REXPList attr) { super(attr); }
+	
+	public boolean isNull() { return true; }
+	public boolean isList() { return true; } // NULL is a list
+	public RList asList() { return new RList(); }
+	public Object asNativeJavaObject() { return null; }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPRaw.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPRaw.java
new file mode 100644
index 0000000000000000000000000000000000000000..4df46b5146d02dd95cd3982ba8f6940da23d5010
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPRaw.java
@@ -0,0 +1,31 @@
+package org.rosuda.REngine;
+
+/** REXPRaw represents a raw vector in R - essentially a sequence of bytes. */
+public class REXPRaw extends REXPVector {
+	private byte[] payload;
+	
+	/** create a new raw vector with the specified payload
+	 *  @param load payload of the raw vector */
+	public REXPRaw(byte[] load) {
+		super();
+		payload=(load==null)?new byte[0]:load;
+	}
+
+	/** create a new raw vector with the specified payload and attributes
+	 *  @param load payload of the raw vector 
+	 *  @param attr attributes for the resulting R object */
+	public REXPRaw(byte[] load, REXPList attr) {
+		super(attr);
+		payload=(load==null)?new byte[0]:load;
+	}
+	
+	public int length() { return payload.length; }
+
+	public boolean isRaw() { return true; }
+
+	public byte[] asBytes() { return payload; }
+
+	public Object asNativeJavaObject() {
+		return payload;
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPReference.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPReference.java
new file mode 100644
index 0000000000000000000000000000000000000000..dd402683991f08a7bb78d8e3bfd935f2ee077b66
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPReference.java
@@ -0,0 +1,89 @@
+package org.rosuda.REngine;
+
+/** this class represents a reference (proxy) to an R object.
+ <p>
+ The reference semantics works by calling {@link #resolve()} (which in turn uses {@link REngine#resolveReference(REXP)} on itself) whenever any methods are accessed. The implementation is not finalized yat and may change as we approach the JRI interface which is more ameanable to reference-style access. Subclasses are free to implement more efficient implementations. */
+public class REXPReference extends REXP {
+	/** engine which will be used to resolve the reference */
+	protected REngine eng;
+	/** an opaque (optional) handle */
+	protected Object handle;
+	/** resolved (cached) object */
+	protected REXP resolvedValue;
+
+	/** create an external REXP reference using given engine and handle. The handle value is just an (optional) identifier not used by the implementation directly. */
+	public REXPReference(REngine eng, Object handle) {
+		super();
+		this.eng = eng;
+		this.handle = handle;
+	}
+
+	/** shortcut for <code>REXPReference(eng, new Long(handle))</code> that is used by native code */
+	REXPReference(REngine eng, long handle) {
+		this(eng, new Long(handle));
+	}
+
+	/** resolve the external REXP reference into an actual REXP object. In addition, the value (if not <code>null</code>) will be cached for subsequent calls to <code>resolve</code> until <code>invalidate</code> is called. */
+	public REXP resolve() {
+		if (resolvedValue != null)
+			return resolvedValue;
+		try {
+			resolvedValue = eng.resolveReference(this);
+			return resolvedValue;
+		} catch (REXPMismatchException me) {
+			// this should never happen since we are REXPReference
+		} catch(REngineException ee) {
+			// FIXME: what to we do?
+		}
+		return null;
+	}
+
+	/** invalidates any cached representation of the reference */
+	public void invalidate() {
+		resolvedValue = null;
+	}
+	
+	/** finalization that notifies the engine when a reference gets collected */
+	protected void finalize() throws Throwable {
+		try {
+			eng.finalizeReference(this);
+		} finally {
+			super.finalize();
+		}
+	}	
+	// type checks
+	public boolean isString() { return resolve().isString(); }
+	public boolean isNumeric() { return resolve().isNumeric(); }
+	public boolean isInteger() { return resolve().isInteger(); }
+	public boolean isNull() { return resolve().isNull(); }
+	public boolean isFactor() { return resolve().isFactor(); }
+	public boolean isList() { return resolve().isList(); }
+	public boolean isLogical() { return resolve().isLogical(); }
+	public boolean isEnvironment() { return resolve().isEnvironment(); }
+	public boolean isLanguage() { return resolve().isLanguage(); }
+	public boolean isSymbol() { return resolve().isSymbol(); }
+	public boolean isVector() { return resolve().isVector(); }
+	public boolean isRaw() { return resolve().isRaw(); }
+	public boolean isComplex() { return resolve().isComplex(); }
+	public boolean isRecursive() { return resolve().isRecursive(); }
+	public boolean isReference() { return true; }
+
+	// basic accessor methods
+	public String[] asStrings() throws REXPMismatchException { return resolve().asStrings(); }
+	public int[] asIntegers() throws REXPMismatchException { return resolve().asIntegers(); }
+	public double[] asDoubles() throws REXPMismatchException { return resolve().asDoubles(); }
+	public RList asList() throws REXPMismatchException { return resolve().asList(); }
+	public RFactor asFactor() throws REXPMismatchException { return resolve().asFactor(); }
+
+	public int length() throws REXPMismatchException { return resolve().length(); }
+
+	public REXPList _attr() { return resolve()._attr(); }
+	
+	public Object getHandle() { return handle; }
+	
+	public REngine getEngine() { return eng; }
+
+	public String toString() {
+		return super.toString()+"{eng="+eng+",h="+handle+"}";
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPS4.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPS4.java
new file mode 100644
index 0000000000000000000000000000000000000000..92ff621de8ca82a3ea7921d6dbe2ebe508a539d6
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPS4.java
@@ -0,0 +1,7 @@
+package org.rosuda.REngine;
+
+/** S4 REXP is a completely vanilla REXP */
+public class REXPS4 extends REXP {
+	public REXPS4() { super(); }
+	public REXPS4(REXPList attr) { super(attr); }	
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPString.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPString.java
new file mode 100644
index 0000000000000000000000000000000000000000..63765152618d863997d46793c7a4566bf7127ccb
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPString.java
@@ -0,0 +1,60 @@
+package org.rosuda.REngine;
+
+/** REXPString represents a character vector in R. */
+public class REXPString extends REXPVector {
+	/** payload */
+	private String[] payload;
+	
+	/** create a new character vector of the length one
+	 *  @param load first (and only) element of the vector */
+	public REXPString(String load) {
+		super();
+		payload=new String[] { load };
+	}
+
+	/** create a new character vector
+	 *  @param load string elements of the vector */
+	public REXPString(String[] load) {
+		super();
+		payload=(load==null)?new String[0]:load;
+	}
+
+	/** create a new character vector with attributes
+	 *  @param load string elements of the vector
+	 *  @param attr attributes */
+	public REXPString(String[] load, REXPList attr) {
+		super(attr);
+		payload=(load==null)?new String[0]:load;
+	}
+	
+	public int length() { return payload.length; }
+
+	public boolean isString() { return true; }
+
+	public Object asNativeJavaObject() {
+		return payload;
+	}
+
+	public String[] asStrings() {
+		return payload;
+	}
+	
+	public boolean[] isNA() {
+		boolean a[] = new boolean[payload.length];
+		int i = 0;
+		while (i < a.length) { a[i] = (payload[i]==null); i++; }
+		return a;
+	}
+	
+	public String toDebugString() {
+		StringBuffer sb = new StringBuffer(super.toDebugString()+"{");
+		int i = 0;
+		while (i < payload.length && i < maxDebugItems) {
+			if (i>0) sb.append(",");
+			sb.append("\""+payload[i]+"\"");
+			i++;
+		}
+		if (i < payload.length) sb.append(",..");
+		return sb.toString()+"}";
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPSymbol.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPSymbol.java
new file mode 100644
index 0000000000000000000000000000000000000000..fc589f8c213cc135db3ac9a02ecb1ccfde62af17
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPSymbol.java
@@ -0,0 +1,35 @@
+package org.rosuda.REngine;
+
+/** REXPSymbol represents a symbol in R. */
+public class REXPSymbol extends REXP {
+	/** name of the symbol */
+	private String name;
+	
+	/** create a new symbol of the given name */
+	public REXPSymbol(String name) {
+		super();
+		this.name=(name==null)?"":name;
+	}
+	
+	public boolean isSymbol() { return true; }
+	
+	/** returns the name of the symbol
+	 *  @return name of the symbol */
+	public String asString() { return name; }
+
+	public String[] asStrings() {
+		return new String[] { name };
+	}
+	
+	public String toString() {
+		return getClass().getName()+"["+name+"]";
+	}
+
+	public String toDebugString() {
+		return super.toDebugString()+"["+name+"]";
+	}
+
+	public Object asNativeJavaObject() {
+		return name;
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPUnknown.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPUnknown.java
new file mode 100644
index 0000000000000000000000000000000000000000..f204709cb324f030adb05d087588f5dc232b2479
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPUnknown.java
@@ -0,0 +1,24 @@
+package org.rosuda.REngine;
+
+/** REXPUnknown is a stand-in for an object that cannot be represented in the REngine hierarchy. Usually this class can be encountered when new types are introduced in R or if a given engine doesn't support all data types. Usually REXPUnknown can only be retrieved from the engine but never assigned. */
+public class REXPUnknown extends REXP {
+	/** type of the unterlying obejct */
+	int type;
+
+	/** creates a new unknown object of the given type
+	 *  @param type internal R type code of this object */
+	public REXPUnknown(int type) { super(); this.type=type; }
+
+	/** creates a new unknown object of the given type
+	 *  @param type internal R type code of this object
+	 *  @param attr attributes */
+	public REXPUnknown(int type, REXPList attr) { super(attr); this.type=type; }
+	
+	/** returns the internal R type of this unknown obejct
+	 *  @return type code */
+	public int getType() { return type; }
+	
+	public String toString() {
+		return super.toString()+"["+type+"]";
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPVector.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPVector.java
new file mode 100644
index 0000000000000000000000000000000000000000..e8bde03de08d5bc40a2090393db75f33ddf357e4
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPVector.java
@@ -0,0 +1,31 @@
+package org.rosuda.REngine;
+
+/** abstract class representing all vectors in R */
+public abstract class REXPVector extends REXP {
+	public REXPVector() { super(); }
+	
+	public REXPVector(REXPList attr) {
+		super(attr);
+	}
+
+	/** returns the length of the vector (i.e. the number of elements)
+	 *  @return length of the vector */
+	public abstract int length();
+
+	public boolean isVector() { return true; }
+
+	/** returns a boolean vector of the same length as this vector with <code>true</code> for NA values and <code>false</code> for any other values
+	 *  @return a boolean vector of the same length as this vector with <code>true</code> for NA values and <code>false</code> for any other values */
+	public boolean[] isNA() {
+		boolean a[] = new boolean[length()];
+		return a;
+	}
+	
+	public String toString() {
+		return super.toString()+"["+length()+"]";
+	}
+	
+	public String toDebugString() {
+		return super.toDebugString()+"["+length()+"]";
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPWrapper.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPWrapper.java
new file mode 100644
index 0000000000000000000000000000000000000000..451026b23eb833d22e4e6a42f031cd0b7d23c2e1
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REXPWrapper.java
@@ -0,0 +1,282 @@
+package org.rosuda.REngine ;
+
+/**
+ * Utility class to wrap an Object into a REXP object. 
+ *
+ * This facilitates wrapping native java objects and arrays 
+ * into REXP objects that can be pushed to R
+ *
+ * @author Romain Francois <francoisromain@free.fr>
+ */
+public class REXPWrapper {
+
+	/* various classes */
+	private static Class byte_ARRAY ;
+	private static Class short_ARRAY ;
+	private static Class int_ARRAY ;
+	private static Class long_ARRAY ;
+	private static Class float_ARRAY ;
+	private static Class double_ARRAY ;
+	private static Class boolean_ARRAY ;
+	
+	private static Class String_ARRAY ;
+	
+	private static Class Byte_ARRAY ;
+	private static Class Short_ARRAY;
+	private static Class Integer_ARRAY ;
+	private static Class Long_ARRAY ;
+	private static Class Float_ARRAY ;
+	private static Class Double_ARRAY ;
+	private static Class Boolean_ARRAY ;
+		
+ 	static{
+		try{
+			byte_ARRAY     = Class.forName("[B") ;
+			short_ARRAY    = Class.forName("[S" ); 
+			int_ARRAY      = Class.forName("[I" ); 
+			long_ARRAY     = (new long[1]).getClass() ; /* FIXME */
+			float_ARRAY    = Class.forName("[F" ) ;
+			double_ARRAY   = Class.forName("[D" );
+			boolean_ARRAY  = Class.forName("[Z" ) ;
+			
+			String_ARRAY   = Class.forName( "[Ljava.lang.String;") ;
+			
+			Byte_ARRAY     = Class.forName( "[Ljava.lang.Byte;" ) ;
+			Short_ARRAY    = Class.forName( "[Ljava.lang.Short;" ) ;
+			Integer_ARRAY  = Class.forName( "[Ljava.lang.Integer;" ) ;
+			Long_ARRAY     = Class.forName( "[Ljava.lang.Long;" ) ;
+			Float_ARRAY    = Class.forName( "[Ljava.lang.Float;" ) ;
+			Double_ARRAY   = Class.forName( "[Ljava.lang.Double;" ) ;
+			Boolean_ARRAY  = Class.forName( "[Ljava.lang.Boolean;" ) ;
+			
+			
+		} catch( Exception e){
+			// should never happen
+			e.printStackTrace(); 
+			System.err.println( "problem while initiating the classes" ) ;
+		}
+	}
+	
+	/**
+	 * Wraps an Object into a REXP
+	 *
+	 * <p>Conversion :</p>
+	 *
+	 * <ul>
+	 * <li>Byte (byte) : REXPRaw </li>
+	 * <li>Short (short) : REXPInteger </li>
+	 * <li>Integer (int) : REXPInteger </li>
+	 * <li>Long (long) : REXPInteger</li>
+	 * <li>Float (float) : REXPDouble</li>
+	 * <li>Double (double) : REXPDouble </li>
+	 * <li>Boolean (boolean) : REXPLogical</li>
+	 * <li>--</li>
+	 * <li>String : REXPString </li>
+	 * <li>String[] : REXPString </li>
+	 * <li>--</li>
+	 * <li>byte[] or Byte[] : REXPRaw</li>
+	 * <li>short[] or Short[] : REXPInteger</li>
+	 * <li>int[] or Integer[] : REXPInteger</li>
+	 * <li>long[] or Long[] : REXPInteger</li>
+	 * <li>float[] or Float[] : REXPDouble</li>
+	 * <li>double[] or Double[] : REXPDouble </li>
+	 * <li>boolean[] or Boolean[]: REXPLogical</li>
+	 * <li>--</li>
+	 * <li>null for anything else</li>
+	 * </ul>
+	 * 
+	 * @param o object to wrap
+	 * @return REXP object that represents o or null if the conversion is not possible
+	 */
+	public static REXP wrap( Object o ) {
+		
+		/* nothing to do in that case */
+		if( o instanceof REXP){
+			return (REXP)o; 
+		} 
+		
+		Class clazz = o.getClass() ;
+		
+		/* primitives */
+		
+		if( clazz == Byte.class ){
+			byte[] load = new byte[1]; 
+			load[0] = ((Byte)o).byteValue() ;
+			return new REXPRaw( load ); 
+		} 
+		
+		if( clazz == Short.class ){
+			return new REXPInteger( ((Short)o).intValue() ) ;
+		} 
+		
+		if( clazz == Integer.class ){
+			return new REXPInteger( ((Integer)o).intValue() ) ;
+		} 
+		
+		if( clazz == Long.class ){
+			return new REXPInteger( ((Long)o).intValue() ) ;
+		} 
+		
+		if( clazz == Float.class ){
+			return new REXPDouble( ((Float)o).doubleValue() ) ;
+		}
+		
+		if( clazz == Double.class ){
+			return new REXPDouble( ((Double)o).doubleValue() ) ;
+		}
+		
+		if( clazz == Boolean.class ){
+			return new REXPLogical( ((Boolean)o).booleanValue() ) ;
+		}
+		
+		
+		/* Strings -> REXPString */
+		
+		if( clazz == String.class ){
+			return new REXPString( (String)o ) ;
+		} 
+		
+		if( clazz == String_ARRAY ){ /* String[] */
+			return new REXPString( (String[])o ); 
+		} 
+		
+		/* array of byte or Bytes -> REXPRaw */
+		
+		if( clazz == byte_ARRAY ){ /* byte[] */
+			return new REXPRaw( (byte[])o ) ; 
+		} 
+		
+		if( clazz == Byte_ARRAY ){ /* Byte[] */
+			Byte[] b = (Byte[])o;
+			int n = b.length ;
+			byte[] bytes = new byte[b.length];
+			for( int i=0; i<n; i++){
+				bytes[i] = b[i].byteValue() ;
+			}
+			return new REXPRaw( bytes ); 
+		}
+		
+		/* arrays of short or Short  -> REXPInteger */ 
+		
+		if( clazz == short_ARRAY ){ /* short[] */
+			short[] shorts = (short[])o ;
+			int[] ints = new int[ shorts.length ];
+			int n = ints.length; 
+			for( int i=0; i<n; i++ ){
+				ints[i] = shorts[i]; 
+			}
+			return new REXPInteger( ints ) ;
+		}
+		
+		if( clazz == Short_ARRAY ){ /* Short[] */
+			Short[] shorts = (Short[])o;
+			int n = shorts.length ;
+			int[] ints = new int[shorts.length];
+			for( int i=0; i<n; i++){
+				ints[i] = shorts[i].intValue() ;
+			}
+			return new REXPInteger( ints ); 
+		} 
+		
+		
+		/* arrays of int or Integer ->  REXPInteger */
+		
+		if( clazz == int_ARRAY ){ /* int[] */
+			return new REXPInteger( (int[])o ) ; 
+		} 
+		
+		if( clazz == Integer_ARRAY ){ /* Integer[] */
+			Integer[] integers = (Integer[])o;
+			int n = integers.length ;
+			int[] ints = new int[integers.length];
+			for( int i=0; i<n; i++){
+				ints[i] = integers[i].intValue() ;
+			}
+			return new REXPInteger( ints ); 
+		} 
+		
+		/* arrays of long or Long -> REXPInteger */
+		
+		if( clazz == long_ARRAY ){ /* long[] */
+			long[] longs = (long[])o;
+			int n = longs.length ;
+			int[] ints = new int[longs.length];
+			for( int i=0; i<n; i++){
+				ints[i] = (int)longs[i] ;
+			}
+			return new REXPInteger( ints ); 
+		} 
+		
+		if( clazz == Long_ARRAY ){ /* Long[] */
+			Long[] longs = (Long[])o;
+			int n = longs.length ;
+			int[] ints = new int[longs.length];
+			for( int i=0; i<n; i++){
+				ints[i] = longs[i].intValue() ;
+			}
+			return new REXPInteger( ints ); 
+		} 
+		
+		/* float or Float arrays -> REXPDouble */
+		
+		if( clazz == float_ARRAY ){ /* float[] */
+			float[] floats = (float[])o;
+			int n = floats.length ;
+			double[] doubles = new double[floats.length];
+			for( int i=0; i<n; i++){
+				doubles[i] = (double)floats[i] ;
+			}
+			return new REXPDouble( doubles ); 
+		} 
+		
+		if( clazz == Float_ARRAY ){ /* Float[] */
+			Float[] floats = (Float[])o;
+			int n = floats.length ;
+			double[] doubles = new double[floats.length];
+			for( int i=0; i<n; i++){
+				doubles[i] = floats[i].doubleValue() ;
+			}
+			return new REXPDouble( doubles ); 
+		}
+		
+		
+		/* double or Double arrays -> REXPDouble */
+		
+		if(clazz == double_ARRAY ) { /* double[] */
+			return new REXPDouble( (double[])o ) ;
+		}
+		
+		if( clazz == Double_ARRAY ){ /* Double[] */
+			Double[] doubles = (Double[])o;
+			double n = doubles.length ;
+			double[] d = new double[doubles.length];
+			for( int i=0; i<n; i++){
+				d[i] = doubles[i].doubleValue() ;
+			}
+			return new REXPDouble( d ); 
+		} 
+		
+		
+		/* boolean arrays -> REXPLogical */
+		
+		if( clazz == boolean_ARRAY ){ /* boolean[] */
+			return new REXPLogical( (boolean[])o ) ; 
+		} 
+		
+		if( clazz == Boolean_ARRAY ){ /* Boolean[] */
+			Boolean[] booleans = (Boolean[])o;
+			int n = booleans.length ;
+			boolean[] b = new boolean[booleans.length];
+			for( int i=0; i<n; i++){
+				b[i] = booleans[i].booleanValue() ;
+			}
+			return new REXPLogical( b ); 
+		} 
+		
+		/* give up and return null */
+		
+		return null ; 
+	}
+	
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngine.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngine.java
new file mode 100644
index 0000000000000000000000000000000000000000..d9fb32d377f32c0a8c1e38cf782b5ca47bf49281
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngine.java
@@ -0,0 +1,177 @@
+package org.rosuda.REngine;
+
+import java.lang.reflect.Method;
+
+/** REngine is an abstract base class for all implementations of R engines. Subclasses can implement interfaces to R in many different ways.
+ Clients should always use methods this class instead of its direct subclasses in order to maintian compatibility with any R engine implementation.
+ The canonical way of obtaining a new engine is to call {@link #engineForClass}. All subclasses must implement <code>createEngine()</code> method. */
+public abstract class REngine {
+    /** last created engine or <code>null</code> if there is none */
+    protected static REngine lastEngine = null;
+	
+    /** this is the designated constructor for REngine classes. It uses reflection to call createEngine method on the given REngine class.
+	@param klass fully qualified class-name of a REngine implementation
+	@return REngine implementation or <code>null</code> if <code>createEngine</code> invokation failed */
+    public static REngine engineForClass(String klass) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, java.lang.reflect.InvocationTargetException {
+		Class cl=Class.forName(klass);
+		if (cl==null) throw(new ClassNotFoundException("can't find engine class "+klass));
+		Method m=cl.getMethod("createEngine",(Class[])null);
+		Object o=m.invoke(null,(Object[])null);
+		return lastEngine=(REngine)o;
+    }
+
+	/** This is the extended constructor for REngine classes. It uses reflection to call createEngine method on the given REngine class with some additional control over the engine. Note that not all engines may support the extended version.
+	 @param klass fully qualified class-name of a REngine implementation
+	 @param args arguments to pass to R for initialization
+	 @param callbacks delegate for REngine callbacks or <code>null</code> if callbacks won't be serviced (engine may not support callbacks)
+	 @param runREPL if <code>true</code> then REPL will be started (if supported by the engine)
+	 @return REngine implementation or <code>null</code> if <code>createEngine</code> invokation failed */
+	public static REngine engineForClass(String klass, String[] args, REngineCallbacks callbacks, boolean runREPL) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, java.lang.reflect.InvocationTargetException {
+		Class cl = Class.forName(klass);
+		if (cl == null) throw new ClassNotFoundException("can't find engine class " + klass);
+		Method m = cl.getMethod("createEngine", new Class[] { String[].class, REngineCallbacks.class, Boolean.TYPE });
+		Object o = m.invoke(null, new Object[] { args, callbacks, new Boolean(runREPL) });
+		return lastEngine = (REngine)o;
+	}
+	
+    /** retrieve the last created engine
+		@return last created engine or <code>null</code> if no engine was created yet */
+    public static REngine getLastEngine() {
+		return lastEngine;
+    }
+
+	/** parse a string into an expression vector
+		@param text string to parse
+		@param resolve resolve the resulting REXP (<code>true</code>) or just return a reference (<code>false</code>)
+	    @return parsed expression */
+	public abstract REXP parse(String text, boolean resolve) throws REngineException;
+
+	/** evaluate an expression vector
+		@param what an expression (or vector of such) to evaluate
+		@param where environment to evaluate in (use <code>null</code> for the global environemnt and/or if environments are not supported by the engine)
+		@param resolve resolve the resulting REXP or just return a reference
+		@return the result of the evaluation of the last expression */
+    public abstract REXP eval(REXP what, REXP where, boolean resolve) throws REngineException, REXPMismatchException;
+
+	/** assign into an environment
+		@param symbol symbol name
+		@param value value to assign
+		@param env environment to assign to (use <code>null</code> for the global environemnt and/or if environments are not supported by the engine) */
+    public abstract void assign(String symbol, REXP value, REXP env) throws REngineException, REXPMismatchException;
+
+	/** get a value from an environment
+		@param symbol symbol name
+		@param env environment (use <code>null</code> for the global environemnt and/or if environments are not supported by the engine)
+		@param resolve resolve the resulting REXP or just return a reference		
+		@return value */
+    public abstract REXP get(String symbol, REXP env, boolean resolve) throws REngineException, REXPMismatchException;
+
+	/** fetch the contents of the given reference. The resulting REXP may never be REXPReference. The engine should raise a {@link #REngineException} exception if {@link #supportsReferences()} returns <code>false</code>.
+		@param ref reference to resolve
+		@return resolved reference */
+	public abstract REXP resolveReference(REXP ref) throws REngineException, REXPMismatchException;
+
+	/** create a reference by pushing local data to R and returning a reference to the data. If ref is a reference it is returned as-is. The engine should raise a {@link #REngineException} exception if {@link #supportsReferences()} returns <code>false</code>.
+	 @param value to create reference to
+	 @return reference to the value */
+	public abstract REXP createReference(REXP value) throws REngineException, REXPMismatchException;
+
+	/** removes reference from the R side. This method is called automatically by the finalizer of <code>REXPReference</code> and should never be called directly.
+	 @param ref reference to finalize */
+	public abstract void finalizeReference(REXP ref) throws REngineException, REXPMismatchException;
+	
+	/** get the parent environemnt of an environemnt
+	 @param env environment to query
+	 @param resolve whether to resolve the resulting environment reference
+	 @return parent environemnt of env */
+	public abstract REXP getParentEnvironment(REXP env, boolean resolve) throws REngineException, REXPMismatchException;
+	
+	/** create a new environemnt
+	 @param parent parent environment
+	 @param resolve whether to resolve the reference to the environemnt (usually <code>false</code> since the returned environment will be empty)
+	 @return resulting environment */
+	public abstract REXP newEnvironment(REXP parent, boolean resolve) throws REngineException, REXPMismatchException;
+	
+    /** convenince method equivalent to <code>eval(parse(text, false), where, resolve);</code>
+	 @param text to parse (see {@link #parse})
+	 @param where environment to evaluate in (see {@link #eval})
+	 @param resolve whether to resolve the resulting reference or not (see {@link #eval})
+	 @return result */
+	public REXP parseAndEval(String text, REXP where, boolean resolve) throws REngineException, REXPMismatchException {
+		REXP p = parse(text, false);
+		return eval(p, where, resolve);
+	}
+
+    /** convenince method equivalent to <code>eval(parse(cmd, false), null, true);</code>
+	 @param cmd expression to parse (see {@link #parse})
+	 @return result */
+    public REXP parseAndEval(String cmd) throws REngineException, REXPMismatchException { return parseAndEval(cmd, null, true); };
+	
+	/** performs a close operation on engines that support it. The engine may not be used after <code>close()</code> returned <code>true</code>. This operation is optional and will always return <code>false</code> if not implemented.
+	 @return <code>true</code> if the close opetaion was successful, <code>false</code> otherwise. */
+	public boolean close() { return false; }
+	
+	//--- capabilities ---
+	/** check whether this engine supports references to R objects
+	 @return <code>true</code> if this engine supports references, <code>false/code> otherwise */
+	public boolean supportsReferences() { return false; }
+	/** check whether this engine supports handing of environments (if not, {@link #eval} and {@link #assign} only support the global environment denoted by <code>null</code>).
+	 @return <code>true</code> if this engine supports environments, <code>false/code> otherwise */
+	public boolean supportsEnvironments() { return false; }
+	/** check whether this engine supports REPL (Read-Evaluate-Print-Loop) and corresponding callbacks.
+	 @return <code>true</code> if this engine supports REPL, <code>false/code> otherwise */
+	public boolean supportsREPL() { return false; }
+	/** check whether this engine supports locking ({@link #lock}, {@link #tryLock} and {@link #unlock}).
+	 @return <code>true</code> if this engine supports REPL, <code>false/code> otherwise */
+	public boolean supportsLocking() { return false; }
+
+	//--- convenience methods --- (the REXPMismatchException catches should be no-ops since the value type is guaranteed in the call to assign)
+	/** convenience method equivalent to <code>assign(symbol, new REXPDouble(d), null)</code> (see {@link #assign(String, REXP, REXP)})
+	 @param symbol symbol name to assign to
+	 @param d values to assign */
+	public void assign(String symbol, double[] d) throws REngineException { try { assign(symbol, new REXPDouble(d), null); } catch (REXPMismatchException e) { throw(new REngineException(this, "REXPMismatchException in assign(,double[]): "+e)); } }
+	/** convenience method equivalent to <code>assign(symbol, new REXPInteger(d), null)</code> (see {@link #assign(String, REXP, REXP)})
+	 @param symbol symbol name to assign to
+	 @param d values to assign */
+	public void assign(String symbol, int[] d) throws REngineException { try { assign(symbol, new REXPInteger(d), null); } catch (REXPMismatchException e) { throw(new REngineException(this, "REXPMismatchException in assign(,int[]): "+e)); } }
+	/** convenience method equivalent to <code>assign(symbol, new REXPString(d), null)</code> (see {@link #assign(String, REXP, REXP)})
+	 @param symbol symbol name to assign to
+	 @param d values to assign */
+	public void assign(String symbol, String[] d) throws REngineException { try { assign(symbol, new REXPString(d), null); } catch (REXPMismatchException e) { throw(new REngineException(this, "REXPMismatchException in assign(,String[]): "+e)); } }
+	/** convenience method equivalent to <code>assign(symbol, new REXPRaw(d), null)</code> (see {@link #assign(String, REXP, REXP)})
+	 @param symbol symbol name to assign to
+	 @param d values to assign */
+	public void assign(String symbol, byte[] d) throws REngineException { try { assign(symbol, new REXPRaw(d), null); } catch (REXPMismatchException e) { throw(new REngineException(this, "REXPMismatchException in assign(,byte[]): "+e)); } }
+	/** convenience method equivalent to <code>assign(symbol, new REXPString(d), null)</code> (see {@link #assign(String, REXP, REXP)})
+	 @param symbol symbol name to assign to
+	 @param d value to assign */
+	public void assign(String symbol, String d) throws REngineException { try { assign(symbol, new REXPString(d), null); } catch (REXPMismatchException e) { throw(new REngineException(this, "REXPMismatchException in assign(,String[]): "+e)); } }
+	/** convenience method equivalent to <code>assign(symbol, value, null)</code> (see {@link #assign(String, REXP, REXP)})
+	 @param symbol symbol name to assign to
+	 @param value values to assign */
+	public void assign(String symbol, REXP value) throws REngineException, REXPMismatchException { assign(symbol, value, null); }
+	
+	//--- locking API ---
+	/** attempts to obtain a lock for this R engine synchronously (without waiting for it).
+	    <br>Note: check for {@link #supportsLocking()} before relying on this capability. If not implemented, always returns 0.
+	 @return 0 if the lock could not be obtained (R engine is busy) and some other value otherwise -- the returned value must be used in a matching call to {@link #unlock(int)}. */
+	public synchronized int tryLock() { return 0; }
+
+	/** obtains a lock for this R engine, waiting until it becomes available.
+	 <br>Note: check for {@link #supportsLocking()} before relying on this capability. If not implemented, always returns 0.
+	 @return value that must be passed to {@link #unlock} in order to release the lock */
+	public synchronized int lock() { return 0; }
+
+	/** releases a lock previously obtained by {@link #lock()} or {@link #tryLock()}.
+	 <br>Note: check for {@link #supportsLocking()} before relying on this capability.  If not implemented, has no effect.
+	 @param lockValue value returned by {@link #lock()} or {@link #tryLock()}. */	 
+	public synchronized void unlock(int lockValue) {}
+
+	public String toString() {
+		return super.toString()+((lastEngine==this)?"{last}":"");
+	}
+	
+	public REXP wrap(Object o){
+		return REXPWrapper.wrap(o); 
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineCallbacks.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineCallbacks.java
new file mode 100644
index 0000000000000000000000000000000000000000..e974253476b31a4cd5450470e8a82f5473aa1758
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineCallbacks.java
@@ -0,0 +1,5 @@
+package org.rosuda.REngine;
+
+/** REngineCallbacks is a virtual interface that poses as a superclass of all callback delegate classes. */
+public interface REngineCallbacks {
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineConsoleHistoryInterface.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineConsoleHistoryInterface.java
new file mode 100644
index 0000000000000000000000000000000000000000..e37765fd9fff565214c2d1ef93edd1acf69b2c21
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineConsoleHistoryInterface.java
@@ -0,0 +1,16 @@
+package org.rosuda.REngine;
+
+/** interface defining delegate methods used by {@link REngine} to forward console history callbacks from R. */
+public interface REngineConsoleHistoryInterface {
+	/** called when R wants to save the history content.
+	 *  @param eng calling engine
+	 *  @param filename name of the file to save command history to
+	 */
+	public void   RSaveHistory  (REngine eng, String filename);	
+	
+	/** called when R wants to load the history content.
+	 *  @param eng calling engine
+	 *  @param filename name of the file to load the command history from
+	 */
+	public void   RLoadHistory  (REngine eng, String filename);
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineEvalException.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineEvalException.java
new file mode 100644
index 0000000000000000000000000000000000000000..09c4c873567359208354038e6a581b11e4f7cadc
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineEvalException.java
@@ -0,0 +1,59 @@
+package org.rosuda.REngine ;
+
+/**
+ * Exception thrown when an error occurs during eval. 
+ * 
+ * <p>
+ * This class is a placeholder and should be extended when more information
+ * can be extracted from R (call stack, etc ... )
+ * </p>
+ */
+public class REngineEvalException extends REngineException {
+	
+	/**
+	 * Value returned by the rniEval native method when the input passed to eval
+	 * is invalid
+	 */ 
+	public static final int INVALID_INPUT = -1 ;
+	
+	/**
+	 * Value returned by the rniEval native method when an error occured during 
+	 * eval (stop, ...)
+	 */
+	public static final int ERROR = -2 ;  
+
+	/**
+	 * Type of eval error
+	 */
+	protected int type ; 
+	
+	/**
+	 * Constructor
+	 *
+	 * @param eng associated REngine
+	 * @param message error message
+	 * @param type type of error (ERROR or INVALID_INPUT)
+	 */
+	public REngineEvalException( REngine eng, String message, int type ){
+		super( eng, message );
+		this.type = type ;
+	}
+	
+	/**
+	 * Constructor using ERROR type
+	 *
+	 * @param eng associated REngine
+	 * @param message error message
+	 */
+	public REngineEvalException( REngine eng, String message){
+		this( eng, message, ERROR );
+	}
+	
+	/**
+	 * @return the type of error (ERROR or INVALID_INPUT)
+	 */
+	public int getType(){
+		return type ;
+	}
+	
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineException.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineException.java
new file mode 100644
index 0000000000000000000000000000000000000000..8df12529013c574985554819052e4a60b2c510a4
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineException.java
@@ -0,0 +1,42 @@
+// REngine - generic Java/R API
+//
+// Copyright (C) 2006 Simon Urbanek
+// --- for licensing information see LICENSE file in the original JRclient distribution ---
+//
+//  RSrvException.java
+//
+//  Created by Simon Urbanek on Wed Jun 21 2006.
+//
+//  $Id$
+//
+
+package org.rosuda.REngine;
+
+/** <code>REngineException</code> is a generic exception that can be thrown by methods invoked on an R engine. */
+public class REngineException extends Exception {
+	/** engine associated with this exception */
+    protected REngine engine;
+
+    /** creates an R engine exception
+	@param engine engine associated with this exception
+	@param msg message describing the cause
+	@param cause original cause if this is a chained exception
+    */
+    public REngineException(REngine engine, String msg, Throwable cause) {
+        super(msg, cause);
+        this.engine = engine;
+    }
+ 
+    /** creates an R engine exception
+	@param engine engine associated with this exception
+	@param msg message describing the cause
+    */
+    public REngineException(REngine engine, String msg) {
+        super(msg);
+        this.engine = engine;
+    }
+
+    /** returns the engine associated with this exception
+	@return engine associated with this exception */
+    public REngine getEngine() { return engine; }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineInputInterface.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineInputInterface.java
new file mode 100644
index 0000000000000000000000000000000000000000..4a7894ed0fb7b053798fdf72b6c0b23add4ae7aa
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineInputInterface.java
@@ -0,0 +1,13 @@
+package org.rosuda.REngine;
+
+/** interface defining delegate methods used by {@link REngine} to forward input callbacks from R. */
+public interface REngineInputInterface {
+	/** called when R enters the read stage of the event loop.
+	 *  <p> Important: implementations should never use a direct return! That will cause a tigh-spinning event loop. Implementation must wait for input asynchronously (e.g., declare synchonized RReadConsole and use wait()) and return only when a complete line is available for processing.
+	 *  @param eng calling engine
+	 *  @param prompt prompt to display in the console
+	 *  @param addToHistory flag indicating whether the input is transient (<code>false</code>) or to be recorded in the command history (<code>true</code>).
+	 *  @return string to be processed as console input
+	 */
+	public String RReadConsole(REngine eng, String prompt, int addToHistory);
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineOutputInterface.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineOutputInterface.java
new file mode 100644
index 0000000000000000000000000000000000000000..42b85bd8f5e738ddc7e7af25336d58b44efe0abf
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineOutputInterface.java
@@ -0,0 +1,21 @@
+package org.rosuda.REngine;
+
+/** interface defining delegate methods used by {@link REngine} to forward output callbacks from R. */
+public interface REngineOutputInterface {
+	/** called when R prints output to the console.
+	 *  @param eng calling engine
+	 *  @param text text to display in the console
+	 *  @param oType output type (0=regular, 1=error/warning)
+	 */
+	public void RWriteConsole(REngine eng, String text, int oType);
+	
+	/** called when R wants to show a warning/error message box (not console-related).
+	 *  @param eng calling engine
+	 *  @param text text to display in the message
+	 */
+	public void RShowMessage(REngine eng, String text);
+	
+	/** called by R to flush (display) any pending console output.
+	 *  @param eng calling engine */
+	public void RFlushConsole(REngine eng);
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineStdOutput.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineStdOutput.java
new file mode 100644
index 0000000000000000000000000000000000000000..9b212de7480cba7e667e75bb5d5fae9dae4d6456
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineStdOutput.java
@@ -0,0 +1,15 @@
+package org.rosuda.REngine;
+
+/** implementation of the {@link REngineOutputInterface} which uses standard output. */
+public class REngineStdOutput implements REngineCallbacks, REngineOutputInterface {
+	public synchronized void RWriteConsole(REngine eng, String text, int oType) {
+		((oType == 0) ? System.out : System.err).print(text);
+	}
+	
+	public void RShowMessage(REngine eng, String text) {
+		System.err.println("*** "+text);
+	}
+	
+	public void RFlushConsole(REngine eng) {
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineUIInterface.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineUIInterface.java
new file mode 100644
index 0000000000000000000000000000000000000000..0bc0fdccf28e0e69e969604db0d366d7c952deff
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/REngineUIInterface.java
@@ -0,0 +1,17 @@
+package org.rosuda.REngine;
+
+/** interface defining delegate methods used by {@link REngine} to forward user interface callbacks from R. */
+public interface REngineUIInterface {
+	/** called when the busy state of R changes - usual response is to change the shape of the cursor
+	 *  @param eng calling engine
+	 *  @param state busy state of R (0 = not busy)
+	 */
+	public void   RBusyState  (REngine eng, int state);	
+	
+	/** called when R wants the user to choose a file.
+	 *  @param eng calling engine
+	 *  @param newFile if <code>true</code> then the user can specify a non-existing file to be created, otherwise an existing file must be selected.
+	 *  @return full path and name of the selected file or <code>null</code> if the selection was cancelled.
+	 */
+	public String RChooseFile  (REngine eng, boolean newFile);
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/RFactor.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/RFactor.java
new file mode 100644
index 0000000000000000000000000000000000000000..ca95997f2ac6a6081c1cb0421f066eefee397baa
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/RFactor.java
@@ -0,0 +1,224 @@
+package org.rosuda.REngine;
+
+// REngine
+// Copyright (C) 2007 Simon Urbanek
+// --- for licensing information see LICENSE file in the original distribution ---
+
+import java.util.*;
+
+/** representation of a factor variable. In R there is no actual object
+    type called "factor", instead it is coded as an int vector with a list
+    attribute. The parser code of REXP converts such constructs directly into
+    the RFactor objects and defines an own XT_FACTOR type 
+    
+    @version $Id$
+*/    
+public class RFactor {
+    int ids[];
+    String levels[];
+	int index_base;
+
+    /** create a new, empty factor var */
+    public RFactor() { ids=new int[0]; levels=new String[0]; }
+    
+    /** create a new factor variable, based on the supplied arrays.
+		@param i array of IDs (inde_base..v.length+index_base-1)
+		@param v values - cotegory names
+		@param copy copy above vaules or just retain them
+		@param index_base index of the first level element (1 for R factors, cannot be negtive)
+		*/
+    public RFactor(int[] i, String[] v, boolean copy, int index_base) {
+		if (i==null) i = new int[0];
+		if (v==null) v = new String[0];
+		if (copy) {
+			ids=new int[i.length]; System.arraycopy(i,0,ids,0,i.length);
+			levels=new String[v.length]; System.arraycopy(v,0,levels,0,v.length);
+		} else {
+			ids=i; levels=v;
+		}
+		this.index_base = index_base;
+    }
+
+	/** create a new factor variable by factorizing a given string array. The levels will be created in the orer of appearance.
+		@param c contents
+		@param index_base base of the level index */
+	public RFactor(String c[], int index_base) {
+		this.index_base = index_base;
+		if (c == null) c = new String[0];
+		Vector lv = new Vector();
+		ids = new int[c.length];
+		int i = 0;
+		while (i < c.length) {
+			int ix = (c[i]==null)?-1:lv.indexOf(c[i]);
+			if (ix<0 && c[i]!=null) {
+				ix = lv.size();
+				lv.add(c[i]);
+			}
+			ids[i] = (ix<0)?REXPInteger.NA:(ix+index_base);
+			i++;
+		}
+		levels = new String[lv.size()];
+		i = 0;
+		while (i < levels.length) {
+			levels[i] = (String) lv.elementAt(i);
+			i++;
+		}
+	}
+	
+	/** same as <code>RFactor(c, 1)</code> */
+	public RFactor(String c[]) {
+		this(c, 1);
+	}
+	
+	/** same as <code>RFactor(i,v, true, 1)</code> */
+	public RFactor(int[] i, String[] v) {
+		this(i, v, true, 1);
+	}
+	
+    /** returns the level of a given case
+		@param i case number
+		@return name. may throw exception if out of range */
+    public String at(int i) {
+		int li = ids[i] - index_base;
+		return (li<0||li>levels.length)?null:levels[li];
+    }
+
+	/** returns <code>true</code> if the data contain the given level index */
+	public boolean contains(int li) {
+		int i = 0;
+		while (i < ids.length) {
+			if (ids[i] == li) return true;
+			i++;
+		}
+		return false;
+	}
+	
+	/** return <code>true</code> if the factor contains the given level (it is NOT the same as levelIndex==-1!) */
+	public boolean contains(String name) {
+		int li = levelIndex(name);
+		if (li<0) return false;
+		int i = 0;
+		while (i < ids.length) {
+			if (ids[i] == li) return true;
+			i++;
+		}
+		return false;
+	}
+	
+	/** count the number of occurences of a given level index */
+	public int count(int levelIndex) {
+		int i = 0;
+		int ct = 0;
+		while (i < ids.length) {
+			if (ids[i] == levelIndex) ct++;
+			i++;
+		}
+		return ct;
+	}
+	
+	/** count the number of occurences of a given level name */
+	public int count(String name) {
+		return count(levelIndex(name));
+	}
+	
+	/** return an array with level counts. */
+	public int[] counts() {
+		int[] c = new int[levels.length];
+		int i = 0;
+		while (i < ids.length) {
+			final int li = ids[i] - index_base;
+			if (li>=0 && li<levels.length)
+				c[li]++;
+			i++;
+		}
+		return c;
+	}
+	
+	/** return the index of a given level name or -1 if it doesn't exist */
+	public int levelIndex(String name) {
+		if (name==null) return -1;
+		int i = 0;
+		while (i < levels.length) {
+			if (levels[i]!=null && levels[i].equals(name)) return i + index_base;
+			i++;
+		}
+		return -1;
+	}
+	
+	/** return the list of levels (0-based, use {@link #indexBase} correction if you want to access it by level index) */
+	public String[] levels() {
+		return levels;
+	}
+	
+	/** return the contents as integer indices (with the index base of this factor) */
+	public int[] asIntegers() {
+		return ids;
+	}
+	
+	/** return the contents as integer indices with a given index base */
+	public int[] asIntegers(int desired_index_base) {
+		if (desired_index_base == index_base) return ids;
+		int[] ix = new int[ids.length];
+		int j = 0; while (j < ids.length) { ix[j] = ids[j] - index_base + desired_index_base; j++; }
+		return ix;
+	}
+	
+	/** return the level name for a given level index */
+	public String levelAtIndex(int li) {
+		li -= index_base;
+		return (li<0||li>levels.length)?null:levels[li];
+	}
+	
+	/** return the level index for a given case */
+	public int indexAt(int i) {
+		return ids[i];
+	}
+	
+	/** return the factor as an array of strings */
+	public String[] asStrings() {
+		String[] s = new String[ids.length];
+		int i = 0;
+		while (i < ids.length) {
+			s[i] = at(i);
+			i++;
+		}
+		return s;	
+	}
+	
+	/** return the base of the levels index */
+	public int indexBase() {
+		return index_base;
+	}
+	
+    /** returns the number of cases */
+    public int size() { return ids.length; }
+
+	public String toString() {
+		return super.toString()+"["+ids.length+","+levels.length+",#"+index_base+"]";
+	}
+	
+    /** displayable representation of the factor variable
+    public String toString() {
+	//return "{"+((val==null)?"<null>;":("levels="+val.size()+";"))+((id==null)?"<null>":("cases="+id.size()))+"}";
+	StringBuffer sb=new StringBuffer("{levels=(");
+	if (val==null)
+	    sb.append("null");
+	else
+	    for (int i=0;i<val.size();i++) {
+		sb.append((i>0)?",\"":"\"");
+		sb.append((String)val.elementAt(i));
+		sb.append("\"");
+	    };
+	sb.append("),ids=(");
+	if (id==null)
+	    sb.append("null");
+	else
+	    for (int i=0;i<id.size();i++) {
+		if (i>0) sb.append(",");
+		sb.append((Integer)id.elementAt(i));
+	    };
+	sb.append(")}");
+	return sb.toString();
+    } */
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/RList.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/RList.java
new file mode 100644
index 0000000000000000000000000000000000000000..bedaede338e7ece5f3ccc935183f1cf9da8e5d0a
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/RList.java
@@ -0,0 +1,333 @@
+package org.rosuda.REngine;
+
+// REngine library - Java client interface to R
+// Copyright (C) 2004,2007,2008 Simon Urbanek
+
+import java.util.*;
+
+/** implementation of R-lists<br>
+    All lists (dotted-pair lists, language lists, expressions and vectors) are regarded as named generic vectors. 
+    Note: This implementation has changed radically in Rserve 0.5!
+
+    This class inofficially implements the Map interface. Unfortunately a conflict in the Java iterface classes Map and List doesn't allow us to implement both officially. Most prominently the Map 'remove' method had to be renamed to removeByKey.
+
+    @version $Id$
+*/
+public class RList extends Vector implements List {
+    public Vector names;
+
+    /** constructs an empty list */
+    public RList() { super(); names=null; }
+
+    /** constructs an initialized, unnamed list
+	 * @param contents - an array of {@link REXP}s to use as contents of this list */
+    public RList(REXP[] contents) {
+	super(contents.length);
+	int i=0;
+	while (i<contents.length)
+	    super.add(contents[i++]);
+	names=null;
+    }
+
+    public RList(int initSize, boolean hasNames) {
+	super(initSize);
+	names=null;
+	if (hasNames) names=new Vector(initSize);
+    }
+    
+    /** constructs an initialized, unnamed list
+	 * @param contents - a {@link Collection} of {@link REXP}s to use as contents of this list */
+    public RList(Collection contents) {
+	super(contents);
+	names=null;
+    }
+
+    /** constructs an initialized, named list. The length of the contents vector determines the length of the list.
+	 * @param contents - an array of {@link REXP}s to use as contents of this list
+	 * @param names - an array of {@link String}s to use as names */
+    public RList(REXP[] contents, String[] names) {
+	this(contents);
+	if (names!=null && names.length>0) {
+	    this.names=new Vector(names.length);
+	    int i = 0;
+	    while (i < names.length) this.names.add(names[i++]);
+	    while (this.names.size()<size()) this.names.add(null);
+	}
+    }
+    
+    /** constructs an initialized, named list. The size of the contents collection determines the length of the list.
+	 * @param contents - a {@link Collection} of {@link REXP}s to use as contents of this list
+	 * @param names - an array of {@link String}s to use as names */
+    public RList(Collection contents, String[] names) {
+	this(contents);
+	if (names!=null && names.length>0) {
+	    this.names=new Vector(names.length);
+	    int i = 0;
+	    while (i < names.length) this.names.add(names[i++]);
+	    while (this.names.size()<size()) this.names.add(null);
+	}
+    }
+
+    /** constructs an initialized, named list. The size of the contents collection determines the length of the list.
+	 * @param contents - a {@link Collection} of {@link REXP}s to use as contents of this list
+	 * @param names - an {@link Collection} of {@link String}s to use as names */
+    public RList(Collection contents, Collection names) {
+	this(contents);
+	if (names!=null && names.size()>0) {
+	    this.names=new Vector(names);
+	    while (this.names.size()<size()) this.names.add(null);
+	}
+    }
+
+	/** checks whether this list is named or unnamed
+	 * @return <code>true</code> if this list is named, <code>false</code> otherwise */
+    public boolean isNamed() {
+	return names!=null;
+    }
+
+    /** get xpression given a key
+	@param v key
+	@return value which corresponds to the given key or
+	        <code>null</code> if the list is unnamed or key not found */
+    public REXP at(String v) {
+	if (names==null) return null;
+	int i = names.indexOf(v);
+	if (i < 0) return null;
+	return (REXP)elementAt(i);
+    }
+
+    /** get element at the specified position
+	@param i index
+	@return value at the index or <code>null</code> if the index is out of bounds */
+    public REXP at(int i) {
+	return (i>=0 && i<size())?(REXP)elementAt(i):null;
+    }
+
+	/** return the key (name) at a given index
+	 @param i index
+	 @return ket at the index - can be <code>null</code> is the list is unnamed or the index is out of range */
+    public String keyAt(int i) {
+	return (names==null || i<0 || i>=names.size())?null:(String)names.get(i);
+    }
+
+	/** set key at the given index. Using this method automatically makes the list a named one even if the key is <code>null</code>. Out of range operations are undefined (currently no-ops)
+	 @param i index
+	 @param value key name */
+	public void setKeyAt(int i, String value) {
+		if (i < 0) return;
+		if (names==null)
+			names = new Vector();
+		if (names.size() < size()) names.setSize(size());
+		if (i < size()) names.set(i, value);
+	}
+
+    /** returns all keys of the list
+	 * @return array containing all keys or <code>null</code> if list unnamed */
+    public String[] keys() {
+	if (names==null) return null;
+	int i = 0;
+	String k[] = new String[names.size()];
+	while (i < k.length) { k[i] = keyAt(i); i++; };
+	return k;
+    }
+
+    // --- overrides that sync names
+
+    public void add(int index, Object element) {
+	super.add(index, element);
+	if (names==null) return;
+	names.add(index, null);
+    }
+
+	public boolean add(Object element) {
+		super.add(element);
+		if (names != null)
+			names.add(null);
+		return true;
+	}
+	
+    public boolean addAll(Collection c) {
+	boolean ch = super.addAll(c);
+	if (names==null) return ch;
+	int l = size();
+	while (names.size()<l) names.add(null);
+	return ch;
+    }
+
+    public boolean addAll(int index, Collection c) {
+	boolean ch = super.addAll(index, c);
+	if (names==null) return ch;
+	int l = c.size();
+	while (l-- > 0) names.add(index, null);
+	return ch;
+    }
+
+    public void clear() {
+	super.clear();
+	names=null;
+    }
+
+    public Object clone() {
+	return new RList(this, names);	
+    }
+
+    public Object remove(int index) {
+	Object o = super.remove(index);
+	if (names != null) {
+	    names.remove(index);
+	    if (size()==0) names=null;
+	}
+	return o;
+    }
+
+    public boolean remove(Object elem) {
+	int i = indexOf(elem);
+	if (i<0) return false;
+	remove(i);
+	if (size()==0) names=null;
+	return true;
+    }
+
+    public boolean removeAll(Collection c) {
+	if (names==null) return super.removeAll(c);
+	boolean changed=false;
+	Iterator it = c.iterator();
+	while (it.hasNext())
+	    changed|=remove(it.next());
+	return changed;
+    }
+
+    public boolean retainAll(Collection c) {
+	if (names==null) return super.retainAll(c);
+	boolean rm[] = new boolean[size()];
+	boolean changed=false;
+	int i = 0;
+	while (i<rm.length) {
+	    changed|=rm[i]=!c.contains(get(i));
+	    i++;
+	}
+	while (i>0) {
+	    i--;
+	    if (rm[i]) remove(i);
+	}
+	return changed;
+    }
+
+    // --- old API mapping
+    public void removeAllElements() { clear(); }
+    public void insertElementAt(Object obj, int index) { add(index, obj); }
+    public void addElement(Object obj) { add(obj); }
+    public void removeElementAt(int index) { remove(index); }
+    public boolean removeElement(Object obj) { return remove(obj); }
+
+    // --- Map interface
+
+    public boolean containsKey(Object key) {
+	return (names==null)?false:names.contains(key);
+    }
+
+    public boolean containsValue(Object value) {
+	return contains(value);
+    }
+
+    /** NOTE: THIS IS UNIMPLEMENTED and always returns <code>null</code>! Due to the fact that R lists are not proper maps we canot maintain a set-view of the list */
+    public Set entrySet() {
+	return null;
+    }
+
+    public Object get(Object key) {
+	return at((String)key);
+    }
+
+    /** Note: sinde RList is not really a Map, the returned set is only an approximation as it cannot reference duplicate or null names that may exist in the list */
+    public Set keySet() {
+	if (names==null) return null;
+	return new HashSet(names);
+    }
+
+    public Object put(Object key, Object value) {
+	if (key==null) {
+	    add(value);
+	    return null;
+	}
+	if (names != null) {
+	    int p = names.indexOf(key);
+	    if (p >= 0)
+		return super.set(p, value);
+	}
+	int i = size();
+	super.add(value);
+	if (names==null)
+	    names = new Vector(i+1);
+	while (names.size() < i) names.add(null);
+	names.add(key);
+	return null;
+    }
+
+    public void putAll(Map t) {
+	if (t==null) return;
+	// NOTE: this if branch is dead since RList cannot inherit from Map
+	if (t instanceof RList) { // we need some more sophistication for RLists as they may have null-names which we append
+	    RList l = (RList) t;
+	    if (names==null) {
+		addAll(l);
+		return;
+	    }
+	    int n = l.size();
+	    int i = 0;
+	    while (i < n) {
+		String key = l.keyAt(i);
+		if (key==null)
+		    add(l.at(i));
+		else
+		    put(key, l.at(i));
+		i++;
+	    }
+	} else {
+	    Set ks = t.keySet();
+	    Iterator i = ks.iterator();
+	    while (i.hasNext()) {
+		Object key = i.next();
+		put(key, t.get(key));
+	    }
+	}
+    }
+
+    public void putAll(RList t) {
+	if (t == null) return;
+	RList l = (RList) t;
+	if (names==null) {
+	    addAll(l);
+	    return;
+	}
+	int n = l.size();
+	int i = 0;
+	while (i < n) {
+	    String key = l.keyAt(i);
+	    if (key == null)
+		add(l.at(i));
+	    else
+		put(key, l.at(i));
+	    i++;
+	}
+    }
+    
+    public Object removeByKey(Object key) {
+	if (names==null) return null;
+	int i = names.indexOf(key);
+	if (i<0) return null;
+	Object o = elementAt(i);
+	removeElementAt(i);
+	names.removeElementAt(i);
+	return o;
+    }
+
+    public Collection values() {
+	return this;
+    }
+	
+	// other
+	public String toString() {
+		return "RList"+super.toString()+"{"+(isNamed()?"named,":"")+size()+"}";
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/Makefile b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..365f8c6573958b4cabc6536c96e44bd5cd4ca9b5
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/Makefile
@@ -0,0 +1,27 @@
+RENG_SRC=$(wildcard ../*.java)
+RSRV_SRC=$(wildcard *.java) $(wildcard protocol/*.java)
+
+TARGETS=Rserve.jar
+
+all: $(TARGETS)
+
+JAVAC=javac
+JFLAGS=-encoding utf8 -source 1.6 -target 1.6
+
+../REngine.jar: $(RENG_SRC)
+	make -C .. REngine.jar
+
+Rserve.jar: $(RSRV_SRC) ../REngine.jar
+	@rm -rf org
+	$(JAVAC) -d . -cp ../REngine.jar $(RSRV_SRC)
+	jar fc $@ org
+	rm -rf org
+
+clean:
+	rm -rf org *~ protocol/*~ $(TARGETS)
+	make -C test clean
+
+test:
+	make -C test test
+
+.PHONY: clean all test
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/RConnection.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/RConnection.java
new file mode 100644
index 0000000000000000000000000000000000000000..9543b6b247a584806610fae65c918e683e285d8b
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/RConnection.java
@@ -0,0 +1,553 @@
+package org.rosuda.REngine.Rserve;
+
+// JRclient library - client interface to Rserve, see http://www.rosuda.org/Rserve/
+// Copyright (C) 2004-08 Simon Urbanek
+// --- for licensing information see LICENSE file in the original JRclient distribution ---
+
+import java.util.*;
+import java.io.*;
+import java.net.*;
+import org.rosuda.REngine.*;
+import org.rosuda.REngine.Rserve.protocol.*;
+
+/**  class providing TCP/IP connection to an Rserve
+     @version $Id$
+*/
+public class RConnection extends REngine {
+    /** last error string */
+    String lastError=null;
+    Socket s;
+    boolean connected=false;
+    InputStream is;
+    OutputStream os;
+    boolean authReq=false;
+    int authType=AT_plain;
+    String Key=null;
+    RTalk rt=null;
+
+    String host;
+    int port;
+
+    /** This static variable specifies the character set used to encode string for transfer. Under normal circumstances there should be no reason for changing this variable. The default is UTF-8, which makes sure that 7-bit ASCII characters are sent in a backward-compatible fashion. Currently (Rserve 0.1-7) there is no further conversion on Rserve's side, i.e. the strings are passed to R without re-coding. If necessary the setting should be changed <u>before</u> connecting to the Rserve in case later Rserves will provide a possibility of setting the encoding during the handshake. */
+    public static String transferCharset="UTF-8";
+    
+    /** authorization type: plain text */
+    public static final int AT_plain = 0;
+    /** authorization type: unix crypt */
+    public static final int AT_crypt = 1;
+
+    /** version of the server (as reported in IDstring just after Rsrv) */
+    protected int rsrvVersion;
+    
+    /** make a new local connection on default port (6311) */
+    public RConnection() throws RserveException {
+		this("127.0.0.1",6311);
+    }
+
+    /** make a new connection to specified host on default port (6311)
+	@param host host name/IP
+    */
+    public RConnection(String host) throws RserveException {
+		this(host,6311);
+    }
+
+    /** make a new connection to specified host and given port.
+	 * Make sure you check {@link #isConnected} to ensure the connection was successfully created.
+	 * @param host host name/IP
+	 * @param port TCP port
+	 */
+    public RConnection(String host, int port) throws RserveException {
+		this(host, port, null);
+    }
+
+	/** restore a connection based on a previously detached session
+	 * @param session detached session object */
+    RConnection(RSession session) throws RserveException {
+		this(null, 0, session);
+    }
+
+
+    RConnection(String host, int port, RSession session) throws RserveException {
+        try {
+            if (connected) s.close();
+            s = null;
+        } catch (Exception e) {
+            throw new RserveException(this, "Cannot close previous connection: " + e.getMessage(), e);
+        }
+	if (session != null) {
+	    host = session.host;
+	    port = session.port;
+	}
+        connected = false;
+	this.host = host;
+	this.port = port;
+        try {
+            Socket ss = new Socket(host,port);
+	    // disable Nagle's algorithm since we really want immediate replies
+	    ss.setTcpNoDelay(true);
+	    initWithSocket(ss, session);
+        } catch (Exception sce) {
+            throw new RserveException(this, "Cannot connect: "+sce.getMessage(), sce);
+        }
+    }
+
+    /** create a connection based on a previously obtained
+	socket. This constructor allows the use of other communication
+	protocols than TCP/IP (if a Socket implementation exists) or
+	tunneling through other protocols that expose socket insteface
+	(such as SSL).
+	@param sock connected socket
+    */
+    
+    public RConnection(Socket sock) throws RserveException {
+	this.host = null;
+	this.port = 0;
+        try {
+            if (connected) s.close();
+	    connected = false;
+            s = null;
+        } catch (Exception e) {
+            throw new RserveException(this, "Cannot close previous connection: " + e.getMessage(), e);
+        }
+	initWithSocket(sock, null);
+    }
+
+    private void initWithSocket(Socket sock, RSession session) throws RserveException {
+	s = sock;
+        try {
+            is = s.getInputStream();
+            os = s.getOutputStream();
+        } catch (Exception gse) {
+            throw new RserveException(this, "Cannot get io stream: " + gse.getMessage(), gse);
+        }
+        rt = new RTalk(is,os);
+		if (session==null) {
+			byte[] IDs=new byte[32];
+			int n=-1;
+			try {
+				n=is.read(IDs);
+			} catch (Exception sre) {
+			    throw new RserveException(this, "Error while receiving data: "+sre.getMessage(), sre);
+			}
+			try {
+				if (n!=32) {
+					throw new RserveException(this,"Handshake failed: expected 32 bytes header, got "+n);
+				}
+				String ids=new String(IDs);
+				if (ids.substring(0,4).compareTo("Rsrv")!=0)
+					throw new RserveException(this, "Handshake failed: Rsrv signature expected, but received \""+ids+"\" instead.");
+				try {
+					rsrvVersion=Integer.parseInt(ids.substring(4,8));
+				} catch (Exception px) {}
+				// we support (knowingly) up to 103
+				if (rsrvVersion > 103)
+					throw new RserveException(this, "Handshake failed: The server uses more recent protocol than this client.");
+				if (ids.substring(8,12).compareTo("QAP1")!=0)
+					throw new RserveException(this, "Handshake failed: unupported transfer protocol ("+ids.substring(8,12)+"), I talk only QAP1.");
+				for (int i=12; i<32; i+=4) {
+					String attr=ids.substring(i,i+4);
+					if (attr.compareTo("ARpt")==0) {
+						if (!authReq) { // this method is only fallback when no other was specified
+							authReq=true;
+							authType=AT_plain;
+						}
+					}
+					if (attr.compareTo("ARuc")==0) {
+						authReq=true;
+						authType=AT_crypt;
+					}
+					if (attr.charAt(0)=='K') {
+						Key=attr.substring(1,3);
+					}
+				}
+			} catch (RserveException innerX) {
+				try { s.close(); } catch (Exception ex01) {}; is=null; os=null; s=null;
+				throw innerX;
+			}
+		} else { // we have a session to take care of
+			try {
+				os.write(session.key,0,32);
+			} catch (Exception sre) {
+			    throw new RserveException(this, "Error while sending session key: " + sre.getMessage(), sre);
+			}
+			rsrvVersion = session.rsrvVersion;
+		}
+		connected=true;
+		lastError="OK";
+    }    
+	
+    public void finalize() {
+        close();
+        is=null;
+	os=null;
+    }
+
+    /** get server version as reported during the handshake.
+        @return server version as integer (Rsrv0100 will return 100) */
+    public int getServerVersion() {
+        return rsrvVersion;
+    }
+    
+    /** closes current connection */
+    public boolean close() {
+        try {
+            if (s != null) s.close();
+            connected = false;
+			return true;
+        } catch(Exception e) { };
+		return false;
+    }
+    
+    /** evaluates the given command, but does not fetch the result (useful for assignment
+	operations)
+	@param cmd command/expression string */
+    public void voidEval(String cmd) throws RserveException {
+		if (!connected || rt==null)
+			throw new RserveException(this,"Not connected");
+		RPacket rp=rt.request(RTalk.CMD_voidEval,cmd+"\n");
+		if (rp!=null && rp.isOk()) return;
+        throw new RserveException(this,"voidEval failed",rp);
+    }
+
+	/** evaluates the given command, detaches the session (see @link{detach()}) and closes connection while the command is being evaluted (requires Rserve 0.4+).
+		Note that a session cannot be attached again until the commad was successfully processed. Techincally the session is put into listening mode while the command is being evaluated but accept is called only after the command was evaluated. One commonly used techique to monitor detached working sessions is to use second connection to poll the status (e.g. create a temporary file and return the full path before detaching thus allowing new connections to read it).
+		@param cmd command/expression string
+		@return session object that can be use to attach back to the session once the command completed */
+    public RSession voidEvalDetach(String cmd) throws RserveException {
+		if (!connected || rt==null)
+			throw new RserveException(this,"Not connected");
+		RPacket rp=rt.request(RTalk.CMD_detachedVoidEval,cmd+"\n");
+		if (rp==null || !rp.isOk())
+			throw new RserveException(this,"detached void eval failed",rp);
+		RSession s = new RSession(this, rp);
+		close();
+		return s;
+    }
+	
+    REXP parseEvalResponse(RPacket rp) throws RserveException {
+		int rxo=0;
+		byte[] pc=rp.getCont();
+		if (rsrvVersion>100) { /* since 0101 eval responds correctly by using DT_SEXP type/len header which is 4 bytes long */
+			rxo=4;
+			/* we should check parameter type (should be DT_SEXP) and fail if it's not */
+			if (pc[0]!=RTalk.DT_SEXP && pc[0]!=(RTalk.DT_SEXP|RTalk.DT_LARGE))
+				throw new RserveException(this,"Error while processing eval output: SEXP (type "+RTalk.DT_SEXP+") expected but found result type "+pc[0]+".");
+			if (pc[0]==(RTalk.DT_SEXP|RTalk.DT_LARGE))
+				rxo=8; // large data need skip of 8 bytes
+			/* warning: we are not checking or using the length - we assume that only the one SEXP is returned. This is true for the current CMD_eval implementation, but may not be in the future. */
+		}
+		if (pc.length>rxo) {
+			try {
+				REXPFactory rx=new REXPFactory();
+				rx.parseREXP(pc, rxo);
+				return rx.getREXP();
+			} catch (REXPMismatchException me) {
+				me.printStackTrace();
+				throw new RserveException(this, "Error when parsing response: " + me.getMessage(), me);
+			}
+		}
+		return null;
+    }
+
+    /** evaluates the given command and retrieves the result
+	@param cmd command/expression string
+	@return R-xpression or <code>null</code> if an error occured */
+    public REXP eval(String cmd) throws RserveException {
+		if (!connected || rt==null)
+            throw new RserveException(this,"Not connected");
+		RPacket rp=rt.request(RTalk.CMD_eval,cmd+"\n");
+		if (rp!=null && rp.isOk())
+			return parseEvalResponse(rp);
+        throw new RserveException(this,"eval failed",rp);
+    }
+
+    /** assign a string value to a symbol in R. The symbol is created if it doesn't exist already.
+        @param sym symbol name. Currently assign uses CMD_setSEXP command of Rserve, i.e. the symbol value is NOT parsed. It is the responsibility of the user to make sure that the symbol name is valid in R (recall the difference between a symbol and an expression!). In fact R will always create the symbol, but it may not be accessible (examples: "bar\nfoo" or "bar$foo").
+        @param ct contents
+        */
+    public void assign(String sym, String ct) throws RserveException {
+		if (!connected || rt==null)
+            throw new RserveException(this,"Not connected");
+        byte[] symn=sym.getBytes();
+        byte[] ctn=ct.getBytes();
+        int sl=symn.length+1;
+        int cl=ctn.length+1;
+        if ((sl&3)>0) sl=(sl&0xfffffc)+4; // make sure the symbol length is divisible by 4
+        if ((cl&3)>0) cl=(cl&0xfffffc)+4; // make sure the content length is divisible by 4
+        byte[] rq=new byte[sl+4+cl+4];
+        int ic;
+        for(ic=0;ic<symn.length;ic++) rq[ic+4]=symn[ic];
+        while (ic<sl) { rq[ic+4]=0; ic++; }
+        for(ic=0;ic<ctn.length;ic++) rq[ic+sl+8]=ctn[ic];
+        while (ic<cl) { rq[ic+sl+8]=0; ic++; }
+		RTalk.setHdr(RTalk.DT_STRING,sl,rq,0);
+		RTalk.setHdr(RTalk.DT_STRING,cl,rq,sl+4);
+		RPacket rp=rt.request(RTalk.CMD_setSEXP,rq);
+        if (rp!=null && rp.isOk()) return;
+        throw new RserveException(this,"assign failed",rp);
+    }
+
+    /** assign a content of a REXP to a symbol in R. The symbol is created if it doesn't exist already.
+     * @param sym symbol name. Currently assign uses CMD_setSEXP command of Rserve, i.e. the symbol value is NOT parsed. It is the responsibility of the user to make sure that the symbol name is valid in R (recall the difference between a symbol and an expression!). In fact R will always create the symbol, but it may not be accessible (examples: "bar\nfoo" or "bar$foo").
+	 * @param rexp contents
+	 */
+public void assign(String sym, REXP rexp) throws RserveException {
+	if (!connected || rt==null)
+	    throw new RserveException(this,"Not connected");
+	try {
+		REXPFactory r = new REXPFactory(rexp);
+		int rl=r.getBinaryLength();
+		byte[] symn=sym.getBytes();
+		int sl=symn.length+1;
+		if ((sl&3)>0) sl=(sl&0xfffffc)+4; // make sure the symbol length is divisible by 4
+		byte[] rq=new byte[sl+rl+((rl>0xfffff0)?12:8)];
+		int ic;
+		for(ic=0;ic<symn.length;ic++) rq[ic+4]=symn[ic];
+		while(ic<sl) { rq[ic+4]=0; ic++; }; // pad with 0
+		RTalk.setHdr(RTalk.DT_STRING,sl,rq,0);
+		RTalk.setHdr(RTalk.DT_SEXP,rl,rq,sl+4);
+		r.getBinaryRepresentation(rq,sl+((rl>0xfffff0)?12:8));
+		RPacket rp=rt.request(RTalk.CMD_setSEXP,rq);
+		if (rp!=null && rp.isOk()) return;
+		throw new RserveException(this,"assign failed",rp);
+	} catch (REXPMismatchException me) {
+	    throw new RserveException(this, "Error creating binary representation: "+me.getMessage(), me);
+	}
+}
+
+    /** open a file on the Rserve for reading
+        @param fn file name. should not contain any path delimiters, since Rserve may restrict the access to local working directory.
+        @return input stream to be used for reading. Note that the stream is read-once only, there is no support for seek or rewind. */
+    public RFileInputStream openFile(String fn) throws IOException {
+		return new RFileInputStream(rt,fn);
+    }
+
+    /** create a file on the Rserve for writing
+        @param fn file name. should not contain any path delimiters, since Rserve may restrict the access to local working directory.
+        @return output stream to be used for writinging. Note that the stream is write-once only, there is no support for seek or rewind. */
+    public RFileOutputStream createFile(String fn) throws IOException {
+        return new RFileOutputStream(rt,fn);
+    }
+
+    /** remove a file on the Rserve
+        @param fn file name. should not contain any path delimiters, since Rserve may restrict the access to local working directory. */
+    public void removeFile(String fn) throws RserveException {
+		if (!connected || rt==null)
+			throw new RserveException(this,"Not connected");
+		RPacket rp=rt.request(RTalk.CMD_removeFile,fn);
+		if (rp!=null && rp.isOk()) return;
+        throw new RserveException(this,"removeFile failed",rp);
+    }
+
+    /** shutdown remote Rserve. Note that some Rserves cannot be shut down from the client side. */
+    public void shutdown() throws RserveException {
+		if (!connected || rt==null)
+			throw new RserveException(this,"Not connected");
+
+		RPacket rp=rt.request(RTalk.CMD_shutdown);
+		if (rp!=null && rp.isOk()) return;
+        throw new RserveException(this,"shutdown failed",rp);
+    }
+
+    /** Sets send buffer size of the Rserve (in bytes) for the current connection. All responses send by Rserve are stored in the send buffer before transmitting. This means that any objects you want to get from the Rserve need to fit into that buffer. By default the size of the send buffer is 2MB. If you need to receive larger objects from Rserve, you will need to use this function to enlarge the buffer. In order to save memory, you can also reduce the buffer size once it's not used anymore. Currently the buffer size is only limited by the memory available and/or 1GB (whichever is smaller). Current Rserve implementations won't go below buffer sizes of 32kb though. If the specified buffer size results in 'out of memory' on the server, the corresponding error is sent and the connection is terminated.<br>
+        <i>Note:</i> This command may go away in future versions of Rserve which will use dynamic send buffer allocation.
+        @param sbs send buffer size (in bytes) min=32k, max=1GB
+     */
+    public void setSendBufferSize(long sbs) throws RserveException {
+        if (!connected || rt==null)
+			throw new RserveException(this,"Not connected");
+
+        RPacket rp=rt.request(RTalk.CMD_setBufferSize,(int)sbs);
+        if (rp!=null && rp.isOk()) return;
+        throw new RserveException(this,"setSendBufferSize failed",rp);        
+    }
+
+    /** set string encoding for this session. It is strongly
+     * recommended to make sure the encoding is always set to UTF-8
+     * because that is the only encoding supported by this Java
+     * client. It can be done either by uisng the
+     * <code>encoding</code> option in the server or by calling
+     * setStringEncoding("utf8") at the beginning of a session (but
+     * after login).
+     @param enc name of the encoding as defined by Rserve - as of
+     Rserve version 0.5-3 valid values are "utf8", "latin1" and
+     "native" (case-sensitive)
+     @since Rserve 0.5-3
+    */
+    public void setStringEncoding(String enc) throws RserveException {
+        if (!connected || rt==null)
+			throw new RserveException(this,"Not connected");
+	RPacket rp = rt.request(RTalk.CMD_setEncoding, enc);
+	if (rp != null && rp.isOk()) return;
+	throw new RserveException(this,"setStringEncoding failed", rp);
+    }
+
+    /** login using supplied user/pwd. Note that login must be the first
+	command if used
+	@param user username
+	@param pwd password */
+    public void login(String user, String pwd) throws RserveException {
+		if (!authReq) return;
+		if (!connected || rt==null)
+			throw new RserveException(this,"Not connected");
+		if (authType==AT_crypt) {
+			if (Key==null) Key="rs";
+			RPacket rp=rt.request(RTalk.CMD_login,user+"\n"+jcrypt.crypt(Key,pwd));
+			if (rp!=null && rp.isOk()) return;
+			try { s.close(); } catch(Exception e) {};
+			is=null; os=null; s=null; connected=false;
+            throw new RserveException(this,"login failed",rp);
+		}
+		RPacket rp=rt.request(RTalk.CMD_login,user+"\n"+pwd);
+		if (rp!=null && rp.isOk()) return;
+		try {s.close();} catch (Exception e) {};
+		is=null; os=null; s=null; connected=false;
+        throw new RserveException(this,"login failed",rp);
+    }
+
+    
+    /** detaches the session and closes the connection (requires Rserve 0.4+). The session can be only resumed by calling @link{RSession.attach} */
+	public RSession detach() throws RserveException {
+		if (!connected || rt==null)
+            throw new RserveException(this,"Not connected");
+		RPacket rp=rt.request(RTalk.CMD_detachSession);
+		if (rp==null || !rp.isOk())
+			throw new RserveException(this,"Cannot detach",rp);
+		RSession s = new RSession(this, rp);
+		close();
+		return s;
+    }
+
+    /** check connection state. Note that currently this state is not checked on-the-spot,
+	that is if connection went down by an outside event this is not reflected by
+	the flag
+	@return <code>true</code> if this connection is alive */
+    public boolean isConnected() { return connected; }
+    
+    /** check authentication requirement sent by server
+	@return <code>true</code> is server requires authentication. In such case first
+	command after connecting must be {@link #login}. */
+    public boolean needLogin() { return authReq; }
+    
+    /** get last error string
+	@return last error string */
+    public String getLastError() { return lastError; }
+	
+    /** evaluates the given command in the master server process asynchronously (control command). Note that control commands are always asynchronous, i.e., the expression is enqueued for evaluation in the master process and the method returns before the expression is evaluated (in non-parallel builds the client has to close the connection before the expression can be evaluated). There is no way to check for errors and control commands should be sent with utmost care as they can abort the server process. The evaluation has no immediate effect on the client session.
+     *  @param cmd command/expression string 
+     *  @since Rserve 0.6-0 */
+    public void serverEval(String cmd) throws RserveException {
+	if (!connected || rt == null)
+	    throw new RserveException(this, "Not connected");
+	RPacket rp = rt.request(RTalk.CMD_ctrlEval, cmd+"\n");
+	if (rp != null && rp.isOk()) return;
+	throw new RserveException(this,"serverEval failed",rp);
+    }
+    
+    /** sources the given file (the path must be local to the server!) in the master server process asynchronously (control command). See {@link #serverEval()} for details on control commands.
+     *  @param serverFile path to a file on the server (it is recommended to always use full paths, because the server process has a different working directory than the client child process!).
+     *  @since Rserve 0.6-0 */
+    public void serverSource(String serverFile) throws RserveException {
+	if (!connected || rt == null)
+	    throw new RserveException(this, "Not connected");
+	RPacket rp = rt.request(RTalk.CMD_ctrlSource, serverFile);
+	if (rp != null && rp.isOk()) return;
+	throw new RserveException(this,"serverSource failed",rp);
+    }
+    
+    /** attempt to shut down the server process cleanly. Note that there is a fundamental difference between the {@link shutdown()} method and this method: <code>serverShutdown()</code> is a proper control command and thus fully authentication controllable, whereas {@link shutdown()} is a client-side command sent to the client child process and thus relying on the ability of the client to signal the server process which may be disabled. Therefore <code>serverShutdown()</code> is preferred and more reliable for Rserve 0.6-0 and higher.
+     *  @since Rserve 0.6-0 */
+    public void serverShutdown() throws RserveException {
+	if (!connected || rt == null)
+	    throw new RserveException(this, "Not connected");
+	RPacket rp = rt.request(RTalk.CMD_ctrlShutdown);
+	if (rp != null && rp.isOk()) return;
+	throw new RserveException(this,"serverShutdown failed",rp);
+    }
+    
+//========= REngine interface API
+
+public REXP parse(String text, boolean resolve) throws REngineException {
+	throw new REngineException(this, "Rserve doesn't support separate parsing step.");
+}
+
+public REXP eval(REXP what, REXP where, boolean resolve) throws REngineException {
+	if (!connected || rt==null)
+		throw new RserveException(this, "Not connected");
+	if (where != null)
+		throw new REngineException(this, "Rserve doesn't support environments other than .GlobalEnv");
+	try {
+		REXPFactory r = new REXPFactory(what);
+		int rl = r.getBinaryLength();
+		byte[] rq = new byte[rl + ((rl > 0xfffff0) ? 8 : 4)];
+		RTalk.setHdr(RTalk.DT_SEXP, rl, rq, 0);
+		r.getBinaryRepresentation(rq, ((rl > 0xfffff0) ? 8 : 4));
+		RPacket rp = rt.request(resolve ? RTalk.CMD_eval : RTalk.CMD_voidEval, rq);
+		if (rp != null && rp.isOk())
+			return parseEvalResponse(rp);
+		throw new RserveException(this,"eval failed", rp);
+	} catch (REXPMismatchException me) {
+		throw new RserveException(this, "Error creating binary representation: " + me.getMessage(), me);
+	}
+}
+
+public REXP parseAndEval(String text, REXP where, boolean resolve) throws REngineException {
+	if (where!=null) throw new REngineException(this, "Rserve doesn't support environments other than .GlobalEnv");
+	try {
+		return eval(text);
+	} catch (RserveException re) {
+	    throw new REngineException(this, re.getMessage(), re);
+	}
+}
+
+/** assign into an environment
+@param symbol symbol name
+@param value value to assign
+@param env environment to assign to */
+public void assign(String symbol, REXP value, REXP env) throws REngineException {
+	if (env!=null) throw new REngineException(this, "Rserve doesn't support environments other than .GlobalEnv");
+	try {
+		assign(symbol, value);
+	} catch (RserveException re) {
+	    throw new REngineException(this, re.getMessage(), re);
+	}
+}
+
+/** get a value from an environment
+@param symbol symbol name
+@param env environment
+@param resolve resolve the resulting REXP or just return a reference		
+@return value */
+public REXP get(String symbol, REXP env, boolean resolve) throws REngineException {
+	if (!resolve) throw new REngineException(this, "Rserve doesn't support references");
+	try {
+		return eval(new REXPSymbol(symbol), env, true);
+	} catch (RserveException re) {
+		throw new REngineException(this, re.getMessage());
+	}
+}
+
+/** fetch the contents of the given reference. The resulting REXP may never be REXPReference.
+@param ref reference to resolve
+@return resolved reference */
+public REXP resolveReference(REXP ref) throws REngineException {
+	throw new REngineException(this, "Rserve doesn't support references");
+}
+	
+	public REXP createReference(REXP ref) throws REngineException {
+		throw new REngineException(this, "Rserve doesn't support references");
+	}
+	public void finalizeReference(REXP ref) throws REngineException {
+		throw new REngineException(this, "Rserve doesn't support references");
+	}
+	
+public REXP getParentEnvironment(REXP env, boolean resolve) throws REngineException {
+	throw new REngineException(this, "Rserve doesn't support environments other than .GlobalEnv");
+}
+
+public REXP newEnvironment(REXP parent, boolean resolve) throws REngineException {
+	throw new REngineException(this, "Rserve doesn't support environments other than .GlobalEnv");
+}
+
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/RFileInputStream.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/RFileInputStream.java
new file mode 100644
index 0000000000000000000000000000000000000000..fc971c7bd61e097f6b93a1323f600f19689b4549
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/RFileInputStream.java
@@ -0,0 +1,87 @@
+package org.rosuda.REngine.Rserve;
+
+// JRclient library - client interface to Rserve, see http://www.rosuda.org/Rserve/
+// Copyright (C) 2004 Simon Urbanek
+// --- for licensing information see LICENSE file in the original JRclient distribution ---
+
+import java.io.*;
+import org.rosuda.REngine.*;
+import org.rosuda.REngine.Rserve.protocol.*;
+
+/** <b>RFileInputStream</b> is an {@link InputStream} to transfer files
+    from <b>Rserve</b> server to the client. It is used very much like
+    a {@link FileInputStream}. Currently mark and seek is not supported.
+    The current implementation is also "one-shot" only, that means the file
+    can be read only once.
+    @version $Id$
+*/
+public class RFileInputStream extends InputStream {
+    /** RTalk class to use for communication with the Rserve */
+    RTalk rt;
+    /** set to <code>true</code> when {@link #close} was called.
+	Any subsequent read requests on closed stream  result in an 
+	{@link IOException} or error result */
+    boolean closed;
+    /** set to <code>true</code> once EOF is reached - or more specifically
+	the first time remore fread returns OK and 0 bytes */
+    boolean eof;
+
+    /** tries to open file on the R server, using specified {@link RTalk} object
+	and filename. Be aware that the filename has to be specified in host
+	format (which is usually unix). In general you should not use directories
+	since Rserve provides an own directory for every connection. Future Rserve
+	servers may even strip all directory navigation characters for security
+	purposes. Therefore only filenames without path specification are considered
+	valid, the behavior in respect to absolute paths in filenames is undefined. */
+    RFileInputStream(RTalk rti, String fn) throws IOException {
+	rt=rti;
+	RPacket rp=rt.request(RTalk.CMD_openFile,fn);
+	if (rp==null || !rp.isOk())
+	    throw new IOException((rp==null)?"Connection to Rserve failed":("Request return code: "+rp.getStat()));
+	closed=false; eof=false;
+    }
+
+    /** reads one byte from the file. This function should be avoided, since
+	{@link RFileInputStream} provides no buffering. This means that each
+	call to this function leads to a complete packet exchange between
+	the server and the client. Use {@link #read(byte[],int,int)} instead
+	whenever possible. In fact this function calls <code>#read(b,0,1)</code>.
+	@return -1 on any failure, or the acquired byte (0..255) on success */
+    public int read() throws IOException {
+	byte[] b=new byte[1];
+	if (read(b,0,1)<1) return -1;
+	return b[0];
+    }
+
+    /** Reads specified number of bytes (or less) from the remote file.
+	@param b buffer to store the read bytes
+	@param off offset where to strat filling the buffer
+	@param len maximal number of bytes to read
+	@return number of bytes read or -1 if EOF reached
+    */
+    public int read(byte[] b, int off, int len) throws IOException {
+	if (closed) throw new IOException("File is not open");
+	if (eof) return -1;
+	RPacket rp=rt.request(RTalk.CMD_readFile,len);
+	if (rp==null || !rp.isOk())
+	    throw new IOException((rp==null)?"Connection to Rserve failed":("Request return code: "+rp.getStat()));
+	byte[] rd=rp.getCont();
+	if (rd==null) {
+	    eof=true;
+	    return -1;
+	};
+	int i=0;
+	while(i<rd.length) { b[off+i]=rd[i]; i++; };
+	return rd.length;
+    }
+
+    /** close stream - is not related to the actual RConnection, calling
+	close does not close the RConnection
+    */
+    public void close() throws IOException {
+	RPacket rp=rt.request(RTalk.CMD_closeFile,(byte[])null);
+	if (rp==null || !rp.isOk())
+	    throw new IOException((rp==null)?"Connection to Rserve failed":("Request return code: "+rp.getStat()));
+	closed=true;
+    }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/RFileOutputStream.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/RFileOutputStream.java
new file mode 100644
index 0000000000000000000000000000000000000000..b8cfefdaed7524da2ba49f08f506796a89eacbbf
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/RFileOutputStream.java
@@ -0,0 +1,97 @@
+// JRclient library - client interface to Rserve, see http://www.rosuda.org/Rserve/
+// Copyright (C) 2003 Simon Urbanek
+// --- for licensing information see LICENSE file in the original JRclient distribution ---
+//
+//  RFileOutputStream.java
+//
+//  Created by Simon Urbanek on Wed Oct 22 2003.
+//
+
+package org.rosuda.REngine.Rserve;
+
+import java.io.*;
+import org.rosuda.REngine.*;
+import org.rosuda.REngine.Rserve.protocol.*;
+
+/** <b>RFileOutputStream</b> is an {@link OutputStream} to transfer files
+from the client to <b>Rserve</b> server. It is used very much like
+a {@link FileOutputStream}. Currently mark and seek is not supported.
+The current implementation is also "one-shot" only, that means the file
+can be written only once.
+@version $Id$
+*/
+
+public class RFileOutputStream extends OutputStream {
+    /** RTalk class to use for communication with the Rserve */
+    RTalk rt;
+    /** set to <code>true</code> when {@link #close} was called.
+    Any subsequent read requests on closed stream  result in an
+{@link IOException} or error result */
+    boolean closed;
+
+    /** tries to create a file on the R server, using specified {@link RTalk} object
+        and filename. Be aware that the filename has to be specified in host
+        format (which is usually unix). In general you should not use directories
+        since Rserve provides an own directory for every connection. Future Rserve
+        servers may even strip all directory navigation characters for security
+        purposes. Therefore only filenames without path specification are considered
+        valid, the behavior in respect to absolute paths in filenames is undefined.
+        @param rti RTalk object for communication with Rserve
+        @param fb filename of the file to create (existing file will be overwritten)
+        */
+    RFileOutputStream(RTalk rti, String fn) throws IOException {
+        rt=rti;
+        RPacket rp=rt.request(RTalk.CMD_createFile,fn);
+        if (rp==null || !rp.isOk())
+            throw new IOException((rp==null)?"Connection to Rserve failed":("Request return code: "+rp.getStat()));
+        closed=false;
+    }
+
+    /** writes one byte to the file. This function should be avoided, since
+    {@link RFileOutputStream} provides no buffering. This means that each
+        call to this function leads to a complete packet exchange between
+        the server and the client. Use {@link #write(byte[])} instead
+        whenever possible. In fact this function calls <code>write(b,0,1)</code>.
+        @param b byte to write
+        */
+    public void write(int b) throws IOException {
+        byte[] ba=new byte[1];
+        write(ba,0,1);
+    }
+
+    /** writes the content of b into the file. This methods is equivalent to calling <code>write(b,0,b.length)</code>.
+        @param b content to write
+        */
+    public void write(byte b[]) throws IOException {
+        write(b,0,b.length);
+    }
+
+    /** Writes specified number of bytes to the remote file.
+        @param b buffer containing the bytes to write
+        @param off offset where to start
+        @param len number of bytes to write
+        */
+    public void write(byte[] b, int off, int len) throws IOException {
+        if (closed) throw new IOException("File is not open");
+        if (len<0) len=0;
+        boolean isLarge=(len>0xfffff0);
+        byte[] hdr=RTalk.newHdr(RTalk.DT_BYTESTREAM,len);
+        RPacket rp=rt.request(RTalk.CMD_writeFile,hdr,b,off,len);
+        if (rp==null || !rp.isOk())
+            throw new IOException((rp==null)?"Connection to Rserve failed":("Request return code: "+rp.getStat()));
+    }
+
+    /** close stream - is not related to the actual RConnection, calling
+        close does not close the RConnection.
+        */
+    public void close() throws IOException {
+        RPacket rp=rt.request(RTalk.CMD_closeFile,(byte[])null);
+        if (rp==null || !rp.isOk())
+            throw new IOException((rp==null)?"Connection to Rserve failed":("Request return code: "+rp.getStat()));
+        closed=true;
+    }
+
+    /** currently (Rserve 0.3) there is no way to force flush on the remote side, hence this function is noop. Future versions of Rserve may support this feature though. At any rate, it is safe to call it. */
+    public void flush() {
+    }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/RSession.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/RSession.java
new file mode 100644
index 0000000000000000000000000000000000000000..dd3e86abb3c3a513ca2d823b324d1f71f6d43cb9
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/RSession.java
@@ -0,0 +1,40 @@
+package org.rosuda.REngine.Rserve;
+
+import org.rosuda.REngine.Rserve.protocol.RPacket;
+import org.rosuda.REngine.Rserve.protocol.RTalk;
+
+public class RSession implements java.io.Serializable {
+    // serial version UID should only change if method signatures change
+    // significantly enough that previous versions cannot be used with
+    // current versions
+    private static final long serialVersionUID = -7048099825974875604l;
+
+    String host;
+    int port;
+    byte[] key;
+
+    transient RPacket attachPacket=null; // response on session attach
+    int rsrvVersion;
+
+    protected RSession() {
+        // default no-args constructor for serialization
+    }
+
+    RSession(RConnection c, RPacket p) throws RserveException {
+	this.host=c.host;
+	this.rsrvVersion=c.rsrvVersion;
+	byte[] ct = p.getCont();
+	if (ct==null || ct.length!=32+3*4)
+	    throw new RserveException(c, "Invalid response to session detach request.");
+	this.port = RTalk.getInt(ct, 4);
+	this.key=new byte[32];
+	System.arraycopy(ct, 12, this.key, 0, 32);
+    }
+
+    /** attach/resume this session */
+    public RConnection attach() throws RserveException {
+	RConnection c = new RConnection(this);
+	attachPacket = c.rt.request(-1);
+	return c;
+    }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/RserveException.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/RserveException.java
new file mode 100644
index 0000000000000000000000000000000000000000..cbe3df007905c33a8629f71c5903f1fc134ca8b1
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/RserveException.java
@@ -0,0 +1,77 @@
+// JRclient library - client interface to Rserve, see http://www.rosuda.org/Rserve/
+// Copyright (C) 2004 Simon Urbanek
+// --- for licensing information see LICENSE file in the original JRclient distribution ---
+//
+//  RserveException.java
+//
+//  Created by Simon Urbanek on Mon Aug 18 2003.
+//
+//  $Id$
+//
+
+package org.rosuda.REngine.Rserve;
+
+import org.rosuda.REngine.Rserve.protocol.RPacket;
+import org.rosuda.REngine.Rserve.protocol.RTalk;
+import org.rosuda.REngine.REngineException;
+
+public class RserveException extends REngineException {
+    protected String err;
+    protected int reqReturnCode;
+
+    public String getRequestErrorDescription() {
+		return getRequestErrorDescription(reqReturnCode);
+	}
+	
+    public String getRequestErrorDescription(int code) {
+        switch(code) {
+            case 0: return "no error";
+            case 2: return "R parser: input incomplete";
+            case 3: return "R parser: syntax error";
+            case RTalk.ERR_auth_failed: return "authorization failed";
+            case RTalk.ERR_conn_broken: return "connection broken";
+            case RTalk.ERR_inv_cmd: return "invalid command";
+            case RTalk.ERR_inv_par: return "invalid parameter";
+            case RTalk.ERR_IOerror: return "I/O error on the server";
+            case RTalk.ERR_not_open: return "connection is not open";
+            case RTalk.ERR_access_denied: return "access denied (local to the server)";
+            case RTalk.ERR_unsupported_cmd: return "unsupported command";
+            case RTalk.ERR_unknown_cmd: return "unknown command";
+            case RTalk.ERR_data_overflow: return "data overflow, incoming data too big";
+            case RTalk.ERR_object_too_big: return "evaluation successful, but returned object is too big to transport";
+            case RTalk.ERR_out_of_mem: return "FATAL: Rserve ran out of memory, closing connection";
+			case RTalk.ERR_session_busy: return "session is busy";
+			case RTalk.ERR_detach_failed: return "session detach failed";
+		case RTalk.ERR_ctrl_closed: return "control pipe to master process is closed/broken";
+        }
+        return "error code: "+code;
+    }
+
+    public String getMessage() {
+        return super.getMessage() + ((reqReturnCode != -1) ? ", request status: " + getRequestErrorDescription() : "");
+    }
+    
+    public RserveException(RConnection c, String msg) {
+        this(c,msg,-1);
+    }
+
+    public RserveException(RConnection c, String msg, Throwable cause) {
+        super(c, msg, cause);
+	reqReturnCode = -1;
+	if (c != null) c.lastError = getMessage();
+    }
+
+    public RserveException(RConnection c, String msg, int requestReturnCode) {
+        super(c, msg);
+        reqReturnCode = requestReturnCode;
+	if (c != null) c.lastError = getMessage();
+    }
+
+    public RserveException(RConnection c, String msg, RPacket p) {
+	this(c, msg, (p == null) ? -1 : p.getStat());
+    }
+	
+    public int getRequestReturnCode() {
+        return reqReturnCode;
+    }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/StartRserve.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/StartRserve.java
new file mode 100644
index 0000000000000000000000000000000000000000..7b2e97df1559f934123160ec3b62d5cd9eb6dfa8
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/StartRserve.java
@@ -0,0 +1,203 @@
+package org.rosuda.REngine.Rserve;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+
+/**
+ * helper class that consumes output of a process. In addition, it filters output
+ * of the REG command on Windows to look for InstallPath registry entry which
+ * specifies the location of R.
+ */
+class StreamHog extends Thread {
+
+  InputStream is;
+  boolean capture;
+  String installPath;
+
+  StreamHog(InputStream is, boolean capture) {
+    this.is = is;
+    this.capture = capture;
+    start();
+  }
+
+  public String getInstallPath() {
+    return installPath;
+  }
+
+  public void run() {
+    try {
+      BufferedReader br = new BufferedReader(new InputStreamReader(is));
+      String line = null;
+      while ((line = br.readLine()) != null) {
+        if (capture) { // we are supposed to capture the output from REG command
+          int i = line.indexOf("InstallPath");
+          if (i >= 0) {
+            String s = line.substring(i + 11).trim();
+            int j = s.indexOf("REG_SZ");
+            if (j >= 0) {
+              s = s.substring(j + 6).trim();
+            }
+            installPath = s;
+            System.out.println("StartRserve: R InstallPath = " + s);
+          }
+        } else {
+          System.out.println("StartRserve: Rserve>" + line);
+        }
+      }
+    } catch (IOException e) {
+      e.printStackTrace();
+    }
+  }
+}
+
+/**
+ * simple class that start Rserve locally if it's not running already - see
+ * mainly <code>checkLocalRserve</code> method. It spits out quite some
+ * debugging outout of the console, so feel free to modify it for your
+ * application if desired.<p>
+ * <i>Important:</i> All applications should shutdown every Rserve that they
+ * started! Never leave Rserve running if you started it after your application
+ * quits since it may pose a security risk. Inform the user if you started an
+ * Rserve instance.
+ */
+public class StartRserve {
+
+  /**
+   * shortcut to
+   * <code>launchRserve(cmd, "--no-save --slave", "--no-save --slave", false)</code>
+   */
+  public static boolean launchRserve(String cmd) {
+    return launchRserve(cmd, "--no-save --slave", "--no-save --slave", false);
+  }
+
+  /**
+   * attempt to start Rserve. Note: parameters are <b>not</b> quoted, so avoid
+   * using any quotes in arguments
+   *
+   * @param cmd command necessary to start R
+   * @param rargs arguments are are to be passed to R
+   * @param rsrvargs arguments to be passed to Rserve
+   * @return <code>true</code> if Rserve is running or was successfully started,
+   * <code>false</code> otherwise.
+   */
+  public static boolean launchRserve(String cmd, String rargs, String rsrvargs, boolean debug) {
+    try {
+      Process p;
+      boolean isWindows = false;
+      String osname = System.getProperty("os.name");
+      if (osname != null && osname.length() >= 7 && osname.substring(0, 7).equals("Windows")) {
+        isWindows = true; /* Windows startup */
+
+        p = Runtime.getRuntime().exec("\"" + cmd + "\" -e \"library(Rserve);Rserve(" + (debug ? "TRUE" : "FALSE") + ",args='" + rsrvargs + "')\" " + rargs);
+      } else /* unix startup */ {
+        p = Runtime.getRuntime().exec(new String[]{
+          "/bin/sh", "-c",
+          "echo 'library(Rserve);Rserve(" + (debug ? "TRUE" : "FALSE") + ",args=\"" + rsrvargs + "\")'|" + cmd + " " + rargs
+        });
+      }
+      System.out.println("StartRserve: waiting for Rserve to start ... (" + p + ")");
+      // we need to fetch the output - some platforms will die if you don't ...
+      StreamHog errorHog = new StreamHog(p.getErrorStream(), false);
+      StreamHog outputHog = new StreamHog(p.getInputStream(), false);
+      if (!isWindows) /* on Windows the process will never return, so we cannot wait */ {
+        p.waitFor();
+      }
+      System.out.println("StartRserve: call terminated, let us try to connect ...");
+    } catch (Exception x) {
+      System.out.println("StartRserve: failed to start Rserve process with " + x.getMessage());
+      return false;
+    }
+    int attempts = 5; /* try up to 5 times before giving up. We can be conservative here, because at this point the process execution itself was successful and the start up is usually asynchronous */
+
+    while (attempts > 0) {
+      try {
+        RConnection c = new RConnection();
+        c.close();
+        return true;
+      } catch (Exception e2) {
+        System.out.println("StartRserve: Try failed with: " + e2.getMessage());
+      }
+      /* a safety sleep just in case the start up is delayed or asynchronous */
+      try {
+        Thread.sleep(500);
+      } catch (InterruptedException ix) {
+      };
+      attempts--;
+    }
+    return false;
+  }
+
+  /**
+   * checks whether Rserve is running and if that's not the case it attempts to
+   * start it using the defaults for the platform where it is run on. This
+   * method is meant to be set-and-forget and cover most default setups. For
+   * special setups you may get more control over R with
+   * <<code>launchRserve</code> instead.
+   */
+  public static boolean checkLocalRserve() {
+    if (isRserveRunning()) {
+      return true;
+    }
+    String osname = System.getProperty("os.name");
+    if (osname != null && osname.length() >= 7 && osname.substring(0, 7).equals("Windows")) {
+      System.out.println("StartRserve: Windows: query registry to find where R is installed ...");
+      String installPath = null;
+      try {
+        Process rp = Runtime.getRuntime().exec("reg query HKLM\\Software\\R-core\\R");
+        StreamHog regHog = new StreamHog(rp.getInputStream(), true);
+        rp.waitFor();
+        regHog.join();
+        installPath = regHog.getInstallPath();
+      } catch (Exception rge) {
+        System.out.println("ERROR: unable to run REG to find the location of R: " + rge);
+        return false;
+      }
+      if (installPath == null) {
+        System.out.println("ERROR: canot find path to R. Make sure reg is available and R was installed with registry settings.");
+        return false;
+      }
+      return launchRserve(installPath + "\\bin\\R.exe");
+    }
+    return (launchRserve("R")
+            || /* try some common unix locations of R */ ((new File("/Library/Frameworks/R.framework/Resources/bin/R")).exists() && launchRserve("/Library/Frameworks/R.framework/Resources/bin/R"))
+            || ((new File("/usr/local/lib/R/bin/R")).exists() && launchRserve("/usr/local/lib/R/bin/R"))
+            || ((new File("/usr/lib/R/bin/R")).exists() && launchRserve("/usr/lib/R/bin/R"))
+            || ((new File("/usr/local/bin/R")).exists() && launchRserve("/usr/local/bin/R"))
+            || ((new File("/sw/bin/R")).exists() && launchRserve("/sw/bin/R"))
+            || ((new File("/usr/common/bin/R")).exists() && launchRserve("/usr/common/bin/R"))
+            || ((new File("/opt/bin/R")).exists() && launchRserve("/opt/bin/R")));
+  }
+
+  /**
+   * check whether Rserve is currently running (on local machine and default
+   * port).
+   *
+   * @return <code>true</code> if local Rserve instance is running,
+   * <code>false</code> otherwise
+   */
+  public static boolean isRserveRunning() {
+    try {
+      RConnection c = new RConnection();
+      c.close();
+      return true;
+    } catch (Exception e) {
+      System.out.println("StartRserve: first connect try failed with: " + e.getMessage());
+    }
+    return false;
+  }
+
+  /**
+   * just a demo main method which starts Rserve and shuts it down again
+   */
+  public static void main(String[] args) {
+    System.out.println("result=" + checkLocalRserve());
+    try {
+      RConnection c = new RConnection();
+      c.shutdown();
+    } catch (Exception x) {
+    };
+  }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/mkmvn.sh b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/mkmvn.sh
new file mode 100755
index 0000000000000000000000000000000000000000..6501046804320cf10ff5f21337680a285f0dace7
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/mkmvn.sh
@@ -0,0 +1,9 @@
+#!/bin/sh
+
+BASE="$1"
+if [ -z "$BASE" ]; then BASE="`pwd`"; fi
+
+rm -rf "$BASE/src/main"
+mkdir -p "$BASE/src/main/java/org/rosuda/REngine/Rserve/protocol"
+(cd "$BASE/src/main/java/org/rosuda/REngine/Rserve" && ln -s ../../../../../../../*.java .) && \
+(cd "$BASE/src/main/java/org/rosuda/REngine/Rserve/protocol" && ln -s ../../../../../../../../protocol/*.java .)
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/package-info.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/package-info.java
new file mode 100644
index 0000000000000000000000000000000000000000..4f8b9876524b359449af7f73c0af11ae2c8358bc
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * REngine-based interface to <a href="http://www.rforge.net/Rserve/">Rserve</a>
+ */
+package org.rosuda.REngine.Rserve ;
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/pom.xml b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/pom.xml
new file mode 100644
index 0000000000000000000000000000000000000000..4dc1a1640da0f48fc415d8a61e60404607db5644
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/pom.xml
@@ -0,0 +1,174 @@
+<?xml version="1.0"?>
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+  <modelVersion>4.0.0</modelVersion>
+  
+  <groupId>org.rosuda.REngine</groupId>
+  <artifactId>Rserve</artifactId>
+  <name>Rserve client back-end for REngine</name>
+  <description>Rserve client back-end implementation for REngine to access R from Java via Rserve.</description>
+  <version>1.8.2-SNAPSHOT</version>
+
+  <url>http://github.com/s-u/REngine</url>
+
+  <properties>
+    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+  </properties>
+
+  <licenses>
+    <license>
+      <name>LGPL v2.1</name>
+      <url>https://www.gnu.org/licenses/lgpl-2.1.txt</url>
+    </license>
+  </licenses>
+
+  <developers>
+    <developer>
+      <name>Simon Urbanek</name>
+      <email>simon.urbanek@R-project.org</email>
+    </developer>
+  </developers>
+
+  <scm>
+    <connection>scm:git:https://github.com/s-u/REngine.git</connection>
+    <developerConnection>scm:git:git@github.com:s-u/REngine.git</developerConnection>
+    <url>https://github.com/s-u/REngine/tree/master/Rserve</url>
+  </scm>
+
+  <dependencies>
+    <dependency>
+      <groupId>org.rosuda.REngine</groupId>
+      <artifactId>REngine</artifactId>
+      <version>2.1.1-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>junit</groupId>
+      <artifactId>junit</artifactId>
+      <version>4.12</version>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.slf4j</groupId>
+      <artifactId>slf4j-api</artifactId>
+      <version>1.7.5</version>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.slf4j</groupId>
+      <artifactId>slf4j-simple</artifactId>
+      <version>1.7.5</version>
+      <scope>test</scope>
+    </dependency>
+  </dependencies>
+
+  <build>
+    <plugins>
+      <plugin>
+	<artifactId>exec-maven-plugin</artifactId>
+	<groupId>org.codehaus.mojo</groupId>
+	<version>1.3.2</version>
+	<executions>
+	  <execution>
+	    <id>create mvn structure</id>
+	    <phase>generate-sources</phase>
+	    <goals>
+              <goal>exec</goal>
+	    </goals>
+	    <configuration>
+              <executable>${basedir}/mkmvn.sh</executable>
+	    </configuration>
+	  </execution>
+	</executions>
+      </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-compiler-plugin</artifactId>
+        <version>3.2</version>
+        <executions>
+          <execution>
+            <id>java-1.4-compile</id>
+            <phase>compile</phase>
+            <goals>
+              <goal>compile</goal>
+            </goals>
+            <configuration>
+              <source>1.4</source>
+              <target>1.4</target>
+            </configuration>
+          </execution>
+          <execution>
+            <id>java-1.5-compile</id>
+            <phase>process-test-sources</phase>
+            <goals>
+              <goal>testCompile</goal>
+            </goals>
+            <configuration>
+              <source>1.5</source>
+              <target>1.5</target>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+    </plugins>
+  </build>
+
+  <profiles>
+    <profile>
+      <id>release</id>
+      <build>
+        <plugins>
+	  <plugin>
+	    <groupId>org.apache.maven.plugins</groupId>
+	    <artifactId>maven-gpg-plugin</artifactId>
+	    <version>1.6</version>
+	    <executions>
+              <execution>
+		<id>sign-artifacts</id>
+		<phase>verify</phase>
+		<goals>
+		  <goal>sign</goal>
+		</goals>
+              </execution>
+	    </executions>
+	  </plugin>
+	  <plugin>
+            <groupId>org.apache.maven.plugins</groupId>
+            <artifactId>maven-javadoc-plugin</artifactId>
+            <version>2.10.2</version>
+	    <executions>
+	      <execution>
+		<id>attach-javadocs</id>
+		<goals>
+		  <goal>jar</goal>
+		</goals>
+	      </execution>
+	    </executions>
+	  </plugin>
+	  <plugin>
+	    <groupId>org.apache.maven.plugins</groupId>
+	    <artifactId>maven-source-plugin</artifactId>
+	    <version>2.4</version>
+	    <executions>
+	      <execution>
+		<id>attach-sources</id>
+		<goals>
+		  <goal>jar-no-fork</goal>
+		</goals>
+	      </execution>
+	    </executions>
+	  </plugin>
+        </plugins>
+      </build>
+    </profile>
+  </profiles>
+  
+  <distributionManagement>
+    <snapshotRepository>
+      <id>ossrh</id>
+      <url>https://oss.sonatype.org/content/repositories/snapshots</url>
+    </snapshotRepository>
+    <repository>
+      <id>ossrh</id>
+      <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
+    </repository>
+  </distributionManagement>
+</project>
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/protocol/REXPFactory.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/protocol/REXPFactory.java
new file mode 100644
index 0000000000000000000000000000000000000000..0011caf1971f1c92cc5088856a6857936fc01cd0
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/protocol/REXPFactory.java
@@ -0,0 +1,707 @@
+package org.rosuda.REngine.Rserve.protocol;
+
+// JRclient library - client interface to Rserve, see http://www.rosuda.org/Rserve/
+// Copyright (C) 2004-8 Simon Urbanek
+// --- for licensing information see LICENSE file in the original JRclient distribution ---
+
+import java.util.*;
+
+import org.rosuda.REngine.*;
+import org.rosuda.REngine.Rserve.*;
+
+/** representation of R-eXpressions in Java
+
+    @version $Id$
+*/
+public class REXPFactory {
+    /** xpression type: NULL */
+    public static final int XT_NULL=0;
+    /** xpression type: integer */
+    public static final int XT_INT=1;
+    /** xpression type: double */
+    public static final int XT_DOUBLE=2;
+    /** xpression type: String */
+    public static final int XT_STR=3;
+    /** xpression type: language construct (currently content is same as list) */
+    public static final int XT_LANG=4;
+    /** xpression type: symbol (content is symbol name: String) */
+    public static final int XT_SYM=5;
+    /** xpression type: RBool */    
+    public static final int XT_BOOL=6;
+    /** xpression type: S4 object
+	@since Rserve 0.5 */
+    public static final int XT_S4=7;
+    /** xpression type: generic vector (RList) */
+    public static final int XT_VECTOR=16;
+    /** xpression type: dotted-pair list (RList) */
+    public static final int XT_LIST=17;
+    /** xpression type: closure (there is no java class for that type (yet?). currently the body of the closure is stored in the content part of the REXP. Please note that this may change in the future!) */
+    public static final int XT_CLOS=18;
+    /** xpression type: symbol name
+	@since Rserve 0.5 */
+    public static final int XT_SYMNAME=19;
+    /** xpression type: dotted-pair list (w/o tags)
+	@since Rserve 0.5 */
+    public static final int XT_LIST_NOTAG=20;
+    /** xpression type: dotted-pair list (w tags)
+	@since Rserve 0.5 */
+    public static final int XT_LIST_TAG=21;
+    /** xpression type: language list (w/o tags)
+	@since Rserve 0.5 */
+    public static final int XT_LANG_NOTAG=22;
+    /** xpression type: language list (w tags)
+	@since Rserve 0.5 */
+    public static final int XT_LANG_TAG=23;
+    /** xpression type: expression vector */
+    public static final int XT_VECTOR_EXP=26;
+    /** xpression type: string vector */
+    public static final int XT_VECTOR_STR=27;
+    /** xpression type: int[] */
+    public static final int XT_ARRAY_INT=32;
+    /** xpression type: double[] */
+    public static final int XT_ARRAY_DOUBLE=33;
+    /** xpression type: String[] (currently not used, Vector is used instead) */
+    public static final int XT_ARRAY_STR=34;
+    /** internal use only! this constant should never appear in a REXP */
+    public static final int XT_ARRAY_BOOL_UA=35;
+    /** xpression type: RBool[] */
+    public static final int XT_ARRAY_BOOL=36;
+    /** xpression type: raw (byte[])
+	@since Rserve 0.4-? */
+    public static final int XT_RAW=37;
+    /** xpression type: Complex[]
+	@since Rserve 0.5 */
+    public static final int XT_ARRAY_CPLX=38;
+    /** xpression type: unknown; no assumptions can be made about the content */
+    public static final int XT_UNKNOWN=48;
+
+    /** xpression type: RFactor; this XT is internally generated (ergo is does not come from Rsrv.h) to support RFactor class which is built from XT_ARRAY_INT */
+    public static final int XT_FACTOR=127; 
+
+	/** used for transport only - has attribute */
+	private static final int XT_HAS_ATTR=128;
+	   
+	int type;
+	REXPFactory attr;
+	REXP cont;
+	RList rootList;
+	
+    public REXP getREXP() { return cont; }
+    public REXPList getAttr() { return (attr==null)?null:(REXPList)attr.cont; }
+	
+	public REXPFactory() {
+	}
+	
+	public REXPFactory(REXP r) throws REXPMismatchException {
+		if (r == null) r=new REXPNull();
+		REXPList a = r._attr();
+		cont = r;
+		if (a != null) attr = new REXPFactory(a);
+		if (r instanceof REXPNull) {
+			type=XT_NULL;
+		} else if (r instanceof REXPList) {
+			RList l = r.asList();
+			type = l.isNamed()?XT_LIST_TAG:XT_LIST_NOTAG;
+			if (r instanceof REXPLanguage)
+				type = (type==XT_LIST_TAG)?XT_LANG_TAG:XT_LANG_NOTAG;
+		} else if (r instanceof REXPGenericVector) {
+			type = XT_VECTOR; // FIXME: may have to adjust names attr
+		} else if (r instanceof REXPS4) {
+			type = XT_S4;
+		} else if (r instanceof REXPInteger) { // this includes factor - FIXME: do we need speacial handling?
+			type = XT_ARRAY_INT;
+		} else if (r instanceof REXPDouble) {
+			type = XT_ARRAY_DOUBLE;
+		} else if (r instanceof REXPString) {
+			type = XT_ARRAY_STR;
+		} else if (r instanceof REXPSymbol) {
+			type = XT_SYMNAME;
+		} else if (r instanceof REXPRaw) {
+			type = XT_RAW;
+		} else if (r instanceof REXPLogical) {
+			type = XT_ARRAY_BOOL;
+		} else {
+			// throw new REXPMismatchException(r, "decode");
+			System.err.println("*** REXPFactory unable to interpret "+r);
+		}
+	}
+
+    /** parses byte buffer for binary representation of xpressions - read one xpression slot (descends recursively for aggregated xpressions such as lists, vectors etc.)
+		@param buf buffer containing the binary representation
+		@param o offset in the buffer to start at
+        @return position just behind the parsed xpression. Can be use for successive calls to {@link #parseREXP} if more than one expression is stored in the binary array. */
+    public int parseREXP(byte[] buf, int o) throws REXPMismatchException {
+		int xl = RTalk.getLen(buf,o);
+		boolean hasAtt = ((buf[o]&128)!=0);
+        boolean isLong = ((buf[o]&64)!=0);
+		int xt = (int)(buf[o]&63);
+        //System.out.println("parseREXP: type="+xt+", len="+xl+", hasAtt="+hasAtt+", isLong="+isLong);
+        if (isLong) o+=4;
+        o+=4;
+		int eox=o+xl;
+	
+		type=xt; attr=new REXPFactory(); cont=null;
+		if (hasAtt) o = attr.parseREXP(buf, o);
+		if (xt==XT_NULL) {
+			cont = new REXPNull(getAttr());
+			return o;
+		}
+		if (xt==XT_DOUBLE) {
+			long lr = RTalk.getLong(buf,o);
+			double[] d = new double[] { Double.longBitsToDouble(lr) };
+			o+=8;
+			if (o!=eox) {
+				System.err.println("Warning: double SEXP size mismatch\n");
+				o=eox;
+			}
+			cont = new REXPDouble(d, getAttr());
+			return o;
+		}
+		if (xt==XT_ARRAY_DOUBLE) {
+			int as=(eox-o)/8,i=0;
+			double[] d=new double[as];
+			while (o<eox) {
+				d[i]=Double.longBitsToDouble(RTalk.getLong(buf,o));
+				o+=8;
+				i++;
+			}
+			if (o!=eox) {
+				System.err.println("Warning: double array SEXP size mismatch\n");
+				o=eox;
+			}
+			cont = new REXPDouble(d, getAttr());
+			return o;
+		}
+		if (xt==XT_BOOL) {
+			byte b[] = new byte[] { buf[o] };
+			if (b[0] != 0 && b[0] != 1) b[0] = REXPLogical.NA;
+			cont = new REXPLogical(b, getAttr());
+			o++;
+			if (o!=eox) {
+                if (eox!=o+3) // o+3 could happen if the result was aligned (1 byte data + 3 bytes padding)
+                    System.err.println("Warning: bool SEXP size mismatch\n");
+				o=eox;
+			}
+			return o;
+		}
+		if (xt==XT_ARRAY_BOOL_UA) {
+			int as=(eox-o), i=0;
+			byte[] d=new byte[as];
+			System.arraycopy(buf,o,d,0,eox-o);
+			o = eox;
+			for (int j = 0; j < d.length; j++) if (d[j] != 0 && d[j] != 1) d[j] = REXPLogical.NA;
+			cont = new REXPLogical(d, getAttr());
+			return o;
+		}
+        if (xt==XT_ARRAY_BOOL) {
+            int as=RTalk.getInt(buf,o);
+            o+=4;
+            byte[] d=new byte[as];
+			System.arraycopy(buf,o,d,0,as);
+			for (int j = 0; j < d.length; j++) if (d[j] != 0 && d[j] != 1) d[j] = REXPLogical.NA;
+			o = eox;
+			cont = new REXPLogical(d, getAttr());
+            return o;
+        }
+        if (xt==XT_INT) {
+			int i[] = new int[] { RTalk.getInt(buf,o) };
+			cont = new REXPInteger(i, getAttr());
+			o+=4;
+			if (o!=eox) {
+				System.err.println("Warning: int SEXP size mismatch\n");
+				o=eox;
+			}
+			return o;
+		}
+		if (xt==XT_ARRAY_INT) {
+			int as=(eox-o)/4,i=0;
+			int[] d=new int[as];
+			while (o<eox) {
+				d[i]=RTalk.getInt(buf,o);
+				o+=4;
+				i++;
+			}
+			if (o!=eox) {
+				System.err.println("Warning: int array SEXP size mismatch\n");
+				o=eox;
+			}
+			cont = null;
+			// hack for lists - special lists attached to int are factors
+			try {
+			    if (getAttr()!=null) {
+					REXP ca = getAttr().asList().at("class");
+					REXP ls = getAttr().asList().at("levels");
+					if (ca != null && ls != null && ca.asString().equals("factor")) {
+						// R uses 1-based index, Java uses 0-based one
+						cont = new REXPFactor(d, ls.asStrings(), getAttr());
+						xt = XT_FACTOR;
+					}
+			    }
+			} catch (Exception e) {
+			}
+			if (cont == null) cont = new REXPInteger(d, getAttr());
+			return o;
+		}
+        if (xt==XT_RAW) {
+            int as=RTalk.getInt(buf,o);
+            o+=4;
+            byte[] d=new byte[as];
+			System.arraycopy(buf,o,d,0,as);
+			o = eox;
+			cont = new REXPRaw(d, getAttr());
+            return o;
+        }
+		if (xt==XT_LIST_NOTAG || xt==XT_LIST_TAG ||
+			xt==XT_LANG_NOTAG || xt==XT_LANG_TAG) {
+			REXPFactory lc = new REXPFactory();
+			REXPFactory nf = new REXPFactory();
+			RList l = new RList();
+			while (o<eox) {
+				String name = null;
+				o = lc.parseREXP(buf, o);
+				if (xt==XT_LIST_TAG || xt==XT_LANG_TAG) {
+					o = nf.parseREXP(buf, o);
+					if (nf.cont.isSymbol() || nf.cont.isString()) name = nf.cont.asString();
+				}
+				if (name==null) l.add(lc.cont);
+				else l.put(name, lc.cont);
+			}
+			cont = (xt==XT_LANG_NOTAG || xt==XT_LANG_TAG)?
+				new REXPLanguage(l, getAttr()):
+				new REXPList(l, getAttr());
+			if (o!=eox) {
+				System.err.println("Warning: int list SEXP size mismatch\n");
+				o=eox;
+			}
+			return o;
+		}
+		if (xt==XT_LIST || xt==XT_LANG) { //old-style lists, for comaptibility with older Rserve versions - rather inefficient since we have to convert the recusively stored structures into a flat structure
+			boolean isRoot = false;
+			if (rootList == null) {
+				rootList = new RList();
+				isRoot = true;
+			}
+			REXPFactory headf = new REXPFactory();
+			REXPFactory tagf = new REXPFactory();
+			o = headf.parseREXP(buf, o);
+			int elIndex = rootList.size();
+			rootList.add(headf.cont);
+			//System.out.println("HEAD="+headf.cont);
+			o = parseREXP(buf, o); // we use ourselves recursively for the body
+			if (o < eox) {
+				o = tagf.parseREXP(buf, o);
+				//System.out.println("TAG="+tagf.cont);
+				if (tagf.cont != null && (tagf.cont.isString() || tagf.cont.isSymbol()))
+					rootList.setKeyAt(elIndex, tagf.cont.asString());
+			}
+			if (isRoot) {
+				cont = (xt==XT_LIST)?
+				new REXPList(rootList, getAttr()):
+				new REXPLanguage(rootList, getAttr());
+				rootList = null;
+				//System.out.println("result="+cont);
+			}
+			return o;
+		}
+		if (xt==XT_VECTOR || xt==XT_VECTOR_EXP) {
+			Vector v=new Vector(); //FIXME: could we use RList?
+			while(o<eox) {
+				REXPFactory xx=new REXPFactory();
+				o = xx.parseREXP(buf,o);
+				v.addElement(xx.cont);
+			}
+			if (o!=eox) {
+				System.err.println("Warning: int vector SEXP size mismatch\n");
+				o=eox;
+			}
+			// fixup for lists since they're stored as attributes of vectors
+			if (getAttr()!=null && getAttr().asList().at("names") != null) {
+				REXP nam = getAttr().asList().at("names");
+				String names[] = null;
+				if (nam.isString()) names = nam.asStrings();
+				else if (nam.isVector()) { // names could be a vector if supplied by old Rserve
+					RList l = nam.asList();
+					Object oa[] = l.toArray();
+					names = new String[oa.length];
+					for(int i = 0; i < oa.length; i++) names[i] = ((REXP)oa[i]).asString();
+				}
+				RList l = new RList(v, names);
+				cont = (xt==XT_VECTOR_EXP)?
+					new REXPExpressionVector(l, getAttr()):
+					new REXPGenericVector(l, getAttr());
+			} else
+				cont = (xt==XT_VECTOR_EXP)?
+					new REXPExpressionVector(new RList(v), getAttr()):
+					new REXPGenericVector(new RList(v), getAttr());
+			return o;
+		}
+		if (xt==XT_ARRAY_STR) {
+			int c = 0, i = o;
+			/* count the entries */
+			while (i < eox) if (buf[i++] == 0) c++;
+			String s[] = new String[c];
+			if (c > 0) {
+				c = 0; i = o;
+				while (o < eox) {
+					if (buf[o] == 0) {
+						try {
+							if (buf[i] == -1) { /* if the first byte is 0xff (-1 in signed char) then it either needs to be skipped (doubling) or there is an NA value */
+								if (buf[i + 1] == 0)
+									s[c] = null; /* NA */
+								else
+									s[c] = new String(buf, i + 1, o - i - 1, RConnection.transferCharset);
+							} else
+								s[c] = new String(buf, i, o - i, RConnection.transferCharset);
+						} catch (java.io.UnsupportedEncodingException ex) {
+							s[c]="";
+						}
+						c++;
+						i = o + 1;
+					}
+					o++;
+				}
+			}
+			cont = new REXPString(s, getAttr());
+			return o;
+		}
+		if (xt==XT_VECTOR_STR) {
+			Vector v=new Vector();
+			while(o<eox) {
+				REXPFactory xx=new REXPFactory();
+				o = xx.parseREXP(buf,o);
+				v.addElement(xx.cont.asString());
+			}
+			if (o!=eox) {
+				System.err.println("Warning: int vector SEXP size mismatch\n");
+				o=eox;
+			}
+			String sa[] = new String[v.size()];
+			int i = 0; while (i < sa.length) { sa[i]=(String)v.get(i); i++; }
+			cont = new REXPString(sa, getAttr());
+			return o;
+		}
+		if (xt==XT_STR||xt==XT_SYMNAME) {
+			int i = o;
+			while (buf[i]!=0 && i<eox) i++;
+			try {
+				if (xt==XT_STR)
+					cont = new REXPString(new String[] { new String(buf, o, i-o, RConnection.transferCharset) }, getAttr());
+				else
+					cont = new REXPSymbol(new String(buf, o, i-o, RConnection.transferCharset));					
+			} catch(Exception e) {
+				System.err.println("unable to convert string\n");
+				cont = null;
+			}
+			o = eox;
+			return o;
+		}
+		if (xt==XT_SYM) {
+			REXPFactory sym = new REXPFactory();
+			o = sym.parseREXP(buf, o); // PRINTNAME that's all we will use
+			cont = new REXPSymbol(sym.getREXP().asString()); // content of a symbol is its printname string (so far)
+			o=eox;
+			return o;
+		}
+		
+		if (xt==XT_CLOS) {
+			/*
+			REXP form=new REXP();
+			REXP body=new REXP();
+			o=parseREXP(form,buf,o);
+			o=parseREXP(body,buf,o);
+			if (o!=eox) {
+				System.err.println("Warning: closure SEXP size mismatch\n");
+				o=eox;
+			}
+			x.cont=body;
+			 */
+			o=eox;
+			return o;
+		}
+		
+		if (xt==XT_UNKNOWN) {
+			cont = new REXPUnknown(RTalk.getInt(buf,o), getAttr());
+			o=eox;
+			return o;
+		}
+		
+		if (xt==XT_S4) {
+			cont = new REXPS4(getAttr());
+			o=eox;
+			return o;
+		}
+		
+		cont = null;
+		o = eox;
+		System.err.println("unhandled type: "+xt);
+		return o;
+    }
+
+    /** Calculates the length of the binary representation of the REXP including all headers. This is the amount of memory necessary to store the REXP via {@link #getBinaryRepresentation}.
+        <p>Please note that currently only XT_[ARRAY_]INT, XT_[ARRAY_]DOUBLE and XT_[ARRAY_]STR are supported! All other types will return 4 which is the size of the header.
+        @return length of the REXP including headers (4 or 8 bytes)*/
+    public int getBinaryLength() throws REXPMismatchException {
+		int l=0;
+		int rxt = type;
+		if (type==XT_LIST || type==XT_LIST_TAG || type==XT_LIST_NOTAG)
+			rxt=(cont.asList()!=null && cont.asList().isNamed())?XT_LIST_TAG:XT_LIST_NOTAG;
+		//System.out.print("len["+xtName(type)+"/"+xtName(rxt)+"] ");
+		if (type==XT_VECTOR_STR) rxt=XT_ARRAY_STR; // VECTOR_STR is broken right now
+		
+		/*
+		if (type==XT_VECTOR && cont.asList()!=null && cont.asList().isNamed())
+			setAttribute("names",new REXPString(cont.asList().keys()));
+		 */
+		
+		boolean hasAttr = false;
+		REXPList a = getAttr();
+		RList al = null;
+		if (a!=null) al = a.asList();
+		if (al != null && al.size()>0) hasAttr=true;
+		if (hasAttr)
+			l+=attr.getBinaryLength();
+		switch (rxt) {
+			case XT_NULL:
+			case XT_S4:
+				break;
+			case XT_INT: l+=4; break;
+			case XT_DOUBLE: l+=8; break;
+			case XT_RAW: l+=4 + cont.asBytes().length; if ((l&3)>0) l=l-(l&3)+4; break;
+			case XT_STR:
+			case XT_SYMNAME:
+				l+=(cont==null)?1:(cont.asString().length()+1);
+				if ((l&3)>0) l=l-(l&3)+4;
+					break;
+			case XT_ARRAY_INT: l+=cont.asIntegers().length*4; break;
+			case XT_ARRAY_DOUBLE: l+=cont.asDoubles().length*8; break;
+			case XT_ARRAY_CPLX: l+=cont.asDoubles().length*8; break;
+			case XT_ARRAY_BOOL: l += cont.asBytes().length + 4; if ((l & 3) > 0) l = l - (l & 3) + 4; break;
+			case XT_LIST_TAG:
+			case XT_LIST_NOTAG:
+			case XT_LANG_TAG:
+			case XT_LANG_NOTAG:
+			case XT_LIST:
+			case XT_VECTOR:
+			{
+				final RList lst = cont.asList();
+				int i=0;
+				while (i<lst.size()) {
+					REXP x = lst.at(i);
+					l += (x==null)?4:(new REXPFactory(x).getBinaryLength());
+					if (rxt==XT_LIST_TAG) {
+						int pl=l;
+						String s = lst.keyAt(i);
+						l+=4; // header for a symbol
+						l+=(s==null)?1:(s.length()+1);
+						if ((l&3)>0) l=l-(l&3)+4;
+						// System.out.println("TAG length: "+(l-pl));
+					}
+					i++;
+				}
+				if ((l&3)>0) l=l-(l&3)+4;
+				break;
+			}
+			case XT_ARRAY_STR:
+			{
+				String sa[] = cont.asStrings();
+				int i=0;
+				while (i < sa.length) {
+					if (sa[i] != null) {
+						try {
+							byte b[] = sa[i].getBytes(RConnection.transferCharset);
+							if (b.length > 0) {
+								if (b[0] == -1) l++;
+								l += b.length;
+							}
+							b = null;
+						} catch (java.io.UnsupportedEncodingException uex) {
+							// FIXME: we should so something ... so far we hope noone's gonna mess with the encoding
+						}
+					} else l++; // NA = -1
+					l++;
+					i++;
+				}
+				if ((l&3)>0) l=l-(l&3)+4;
+				break;
+			}
+		} // switch
+        if (l>0xfffff0) l+=4; // large data need 4 more bytes
+							  // System.out.println("len:"+(l+4)+" "+xtName(rxt)+"/"+xtName(type)+" "+cont);
+		return l+4; // add the header
+    }
+
+    /** Stores the REXP in its binary (ready-to-send) representation including header into a buffer and returns the index of the byte behind the REXP.
+        <p>Please note that currently only XT_[ARRAY_]INT, XT_[ARRAY_]DOUBLE and XT_[ARRAY_]STR are supported! All other types will be stored as SEXP of the length 0 without any contents.
+        @param buf buffer to store the REXP binary into
+        @param off offset of the first byte where to store the REXP
+        @return the offset of the first byte behind the stored REXP */
+    public int getBinaryRepresentation(byte[] buf, int off) throws REXPMismatchException {
+		int myl=getBinaryLength();
+        boolean isLarge=(myl>0xfffff0);
+		boolean hasAttr = false;
+		final REXPList a = getAttr();
+		RList al = null;
+		if (a != null) al = a.asList();
+		if (al != null && al.size()>0) hasAttr=true;
+		int rxt=type, ooff=off;
+		if (type==XT_VECTOR_STR) rxt=XT_ARRAY_STR; // VECTOR_STR is broken right now
+		if (type==XT_LIST || type==XT_LIST_TAG || type==XT_LIST_NOTAG)
+			rxt=(cont.asList()!=null && cont.asList().isNamed())?XT_LIST_TAG:XT_LIST_NOTAG;
+		// System.out.println("@"+off+": "+xtName(rxt)+"/"+xtName(type)+" "+cont+" ("+myl+"/"+buf.length+") att="+hasAttr);
+        RTalk.setHdr(rxt|(hasAttr?XT_HAS_ATTR:0),myl-(isLarge?8:4),buf,off);
+        off+=(isLarge?8:4);
+		if (hasAttr) off=attr.getBinaryRepresentation(buf, off);
+		switch (rxt) {
+			case XT_S4:
+			case XT_NULL:
+				break;
+			case XT_INT: RTalk.setInt(cont.asInteger(),buf,off); break;
+			case XT_DOUBLE: RTalk.setLong(Double.doubleToRawLongBits(cont.asDouble()),buf,off); break;
+			case XT_ARRAY_INT:
+			{
+				int ia[]=cont.asIntegers();
+				int i=0, io=off;
+				while(i<ia.length) {
+					RTalk.setInt(ia[i++],buf,io); io+=4;
+				}
+				break;
+			}
+			case XT_ARRAY_BOOL:
+			{
+				byte ba[] = cont.asBytes();
+				int io = off;
+				RTalk.setInt(ba.length, buf, io);
+				io += 4;
+				if (ba.length > 0) {
+					for(int i =0; i < ba.length; i++)
+						buf[io++] = (byte) ( (ba[i] == REXPLogical.NA) ? 2 : ((ba[i] == REXPLogical.FALSE) ? 0 : 1) );
+					while ((io & 3) != 0) buf[io++] = 3;
+				}
+				break;
+			}
+			case XT_ARRAY_DOUBLE:
+			{
+				double da[]=cont.asDoubles();
+				int i=0, io=off;
+				while(i<da.length) {
+					RTalk.setLong(Double.doubleToRawLongBits(da[i++]),buf,io); io+=8;
+				}
+				break;
+			}
+			case XT_RAW:
+			{
+				byte by[] = cont.asBytes();
+				RTalk.setInt(by.length, buf, off); off+=4;
+				System.arraycopy(by, 0, buf, off, by.length);
+				break;
+			}
+			case XT_ARRAY_STR:
+			{
+				String sa[] = cont.asStrings();
+				int i = 0, io = off;
+				while (i < sa.length) {
+					if (sa[i] != null) {
+						try {
+							byte b[] = sa[i].getBytes(RConnection.transferCharset);
+							if (b.length > 0) {
+								if (b[0] == -1) /* if the first entry happens to be -1 then we need to double it so it doesn't get confused with NAs */
+									buf[io++] = -1;
+								System.arraycopy(b, 0, buf, io, b.length);
+								io += b.length;
+							}
+							b = null;
+						} catch (java.io.UnsupportedEncodingException uex) {
+							// FIXME: we should so something ... so far we hope noone's gonna mess with the encoding
+						}
+					} else
+						buf[io++] = -1; /* NAs are stored as 0xff (-1 in signed bytes) */
+					buf[io++] = 0;
+					i++;
+				}
+				i = io - off;
+				while ((i & 3) != 0) { buf[io++] = 1; i++; } // padding if necessary..
+				break;
+			}
+			case XT_LIST_TAG:
+			case XT_LIST_NOTAG:
+			case XT_LANG_TAG:
+			case XT_LANG_NOTAG:
+			case XT_LIST:
+			case XT_VECTOR:
+			case XT_VECTOR_EXP:
+			{
+				int io = off;
+				final RList lst = cont.asList();
+				if (lst != null) {
+					int i=0;
+					while (i<lst.size()) {
+						REXP x = lst.at(i);
+						if (x == null) x=new REXPNull();
+						io = new REXPFactory(x).getBinaryRepresentation(buf, io);
+						if (rxt == XT_LIST_TAG || rxt == XT_LANG_TAG)
+							io = new REXPFactory(new REXPSymbol(lst.keyAt(i))).getBinaryRepresentation(buf, io);
+						i++;
+					}
+				}
+				// System.out.println("io="+io+", expected: "+(ooff+myl));
+				break;
+			}
+	    
+			case XT_SYMNAME:
+			case XT_STR:
+				getStringBinaryRepresentation(buf, off, cont.asString());
+				break;
+		}
+		return ooff+myl;
+    }
+
+    public static int getStringBinaryRepresentation(byte[] buf, int off, String s) {
+		if (s==null) s="";
+		int io=off;
+		try {
+			byte b[]=s.getBytes(RConnection.transferCharset);
+			// System.out.println("<str> @"+off+", len "+b.length+" (cont "+buf.length+") \""+s+"\"");
+			System.arraycopy(b,0,buf,io,b.length);
+			io+=b.length;
+			b=null;
+		} catch (java.io.UnsupportedEncodingException uex) {
+			// FIXME: we should so something ... so far we hope noone's gonna mess with the encoding
+		}
+		buf[io++]=0;
+		while ((io&3)!=0) buf[io++]=0; // padding if necessary..
+		return io;
+    }
+
+    /** returns human-readable name of the xpression type as string. Arrays are denoted by a trailing asterisk (*).
+	@param xt xpression type
+	@return name of the xpression type */
+    public static String xtName(int xt) {
+		if (xt==XT_NULL) return "NULL";
+		if (xt==XT_INT) return "INT";
+		if (xt==XT_STR) return "STRING";
+		if (xt==XT_DOUBLE) return "REAL";
+		if (xt==XT_BOOL) return "BOOL";
+		if (xt==XT_ARRAY_INT) return "INT*";
+		if (xt==XT_ARRAY_STR) return "STRING*";
+		if (xt==XT_ARRAY_DOUBLE) return "REAL*";
+		if (xt==XT_ARRAY_BOOL) return "BOOL*";
+		if (xt==XT_ARRAY_CPLX) return "COMPLEX*";
+		if (xt==XT_SYM) return "SYMBOL";
+		if (xt==XT_SYMNAME) return "SYMNAME";
+		if (xt==XT_LANG) return "LANG";
+		if (xt==XT_LIST) return "LIST";
+		if (xt==XT_LIST_TAG) return "LIST+T";
+		if (xt==XT_LIST_NOTAG) return "LIST/T";
+		if (xt==XT_LANG_TAG) return "LANG+T";
+		if (xt==XT_LANG_NOTAG) return "LANG/T";
+		if (xt==XT_CLOS) return "CLOS";
+		if (xt==XT_RAW) return "RAW";
+		if (xt==XT_S4) return "S4";
+		if (xt==XT_VECTOR) return "VECTOR";
+		if (xt==XT_VECTOR_STR) return "STRING[]";
+		if (xt==XT_VECTOR_EXP) return "EXPR[]";
+		if (xt==XT_FACTOR) return "FACTOR";
+		if (xt==XT_UNKNOWN) return "UNKNOWN";
+		return "<unknown "+xt+">";
+    }	
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/protocol/RPacket.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/protocol/RPacket.java
new file mode 100644
index 0000000000000000000000000000000000000000..db19bff4564f223287a3189bc2139ce4929be0a5
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/protocol/RPacket.java
@@ -0,0 +1,42 @@
+package org.rosuda.REngine.Rserve.protocol;
+
+// JRclient library - client interface to Rserve, see http://www.rosuda.org/Rserve/
+// Copyright (C) 2004 Simon Urbanek
+// --- for licensing information see LICENSE file in the original JRclient distribution ---
+
+/** small class encapsulating packets from/to Rserv
+    @version $Id$
+*/
+public class RPacket {
+    int cmd;
+    byte[] cont;
+
+    /** construct new packet
+	@param Rcmd command
+	@param Rcont content */
+    public RPacket(int Rcmd, byte[] Rcont) {
+	cmd=Rcmd; cont=Rcont;
+    }
+    
+    /** get command
+        @return command */
+    public int getCmd() { return cmd; }
+    
+    /** check last response for RESP_OK
+	@return <code>true</code> if last response was OK */
+    public boolean isOk() { return ((cmd&15)==1); }
+    
+    /** check last response for RESP_ERR
+	@return <code>true</code> if last response was ERROR */
+    public boolean isError() { return ((cmd&15)==2); }
+    
+    /** get status code of last response
+	@return status code returned on last response */
+    public int getStat() { return ((cmd>>24)&127); }
+
+    /** get content
+	@return inner package content */
+    public byte[] getCont() { return cont; }
+
+    public String toString() { return "RPacket[cmd="+cmd+",len="+((cont==null)?"<null>":(""+cont.length))+"]"; }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/protocol/RTalk.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/protocol/RTalk.java
new file mode 100644
index 0000000000000000000000000000000000000000..b723c2c355791658c8b1a8f05aaae3c493720e3c
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/protocol/RTalk.java
@@ -0,0 +1,271 @@
+package org.rosuda.REngine.Rserve.protocol;
+
+// JRclient library - client interface to Rserve, see http://www.rosuda.org/Rserve/
+// Copyright (C) 2004 Simon Urbanek
+// --- for licensing information see LICENSE file in the original JRclient distribution ---
+
+import java.util.*;
+import java.io.*;
+import java.net.*;
+
+import org.rosuda.REngine.Rserve.RConnection;
+
+/** This class encapsulates the QAP1 protocol used by Rserv.
+    it is independent of the underying protocol(s), therefore RTalk
+    can be used over any transport layer
+    <p>
+    The current implementation supports long (0.3+/0102) data format only
+    up to 32-bit and only for incoming packets.
+    <p>
+    @version $Id$
+*/
+public class RTalk {
+    public static final int DT_INT=1;
+    public static final int DT_CHAR=2;
+    public static final int DT_DOUBLE=3;
+    public static final int DT_STRING=4;
+    public static final int DT_BYTESTREAM=5;
+    public static final int DT_SEXP=10;
+    public static final int DT_ARRAY=11;
+
+    /** this is a flag saying that the contents is large (>0xfffff0) and hence uses 56-bit length field */
+    public static final int DT_LARGE=64;
+
+    public static final int CMD_login=0x001;
+    public static final int CMD_voidEval=0x002;
+    public static final int CMD_eval=0x003;
+    public static final int CMD_shutdown=0x004;
+    public static final int CMD_openFile=0x010;
+    public static final int CMD_createFile=0x011;
+    public static final int CMD_closeFile=0x012;
+    public static final int CMD_readFile=0x013;
+    public static final int CMD_writeFile=0x014;
+    public static final int CMD_removeFile=0x015;
+    public static final int CMD_setSEXP=0x020;
+    public static final int CMD_assignSEXP=0x021;
+    
+    public static final int CMD_setBufferSize=0x081;
+    public static final int CMD_setEncoding=0x082;
+
+    public static final int CMD_detachSession=0x030;
+    public static final int CMD_detachedVoidEval=0x031;
+    public static final int CMD_attachSession=0x032;
+
+    // control commands since 0.6-0
+    public static final int CMD_ctrlEval=0x42;
+    public static final int CMD_ctrlSource=0x45;
+    public static final int CMD_ctrlShutdown=0x44; 
+    
+    // errors as returned by Rserve
+    public static final int ERR_auth_failed=0x41;
+    public static final int ERR_conn_broken=0x42;
+    public static final int ERR_inv_cmd=0x43;
+    public static final int ERR_inv_par=0x44;
+    public static final int ERR_Rerror=0x45;
+    public static final int ERR_IOerror=0x46;
+    public static final int ERR_not_open=0x47;
+    public static final int ERR_access_denied=0x48;
+    public static final int ERR_unsupported_cmd=0x49;
+    public static final int ERR_unknown_cmd=0x4a;
+    public static final int ERR_data_overflow=0x4b;
+    public static final int ERR_object_too_big=0x4c;
+    public static final int ERR_out_of_mem=0x4d;
+    public static final int ERR_ctrl_closed=0x4e;
+    public static final int ERR_session_busy=0x50;
+    public static final int ERR_detach_failed=0x51;
+   
+    InputStream is;
+    OutputStream os;
+    
+    /** constructor; parameters specify the streams
+	@param sis socket input stream
+	@param sos socket output stream */
+
+    public RTalk(InputStream sis, OutputStream sos) {
+	is=sis; os=sos;
+    }
+
+    /** writes bit-wise int to a byte buffer at specified position in Intel-endian form
+	@param v value to be written
+	@param buf buffer
+	@param o offset in the buffer to start at. An int takes always 4 bytes */
+    public static void setInt(int v, byte[] buf, int o) {
+	buf[o]=(byte)(v&255); o++;
+	buf[o]=(byte)((v&0xff00)>>8); o++;
+	buf[o]=(byte)((v&0xff0000)>>16); o++;
+	buf[o]=(byte)((v&0xff000000)>>24);
+    }
+
+    /** writes cmd/resp/type byte + 3/7 bytes len into a byte buffer at specified offset.
+	@param ty type/cmd/resp byte
+	@param len length
+	@param buf buffer
+	@param o offset
+        @return offset in buf just after the header. Please note that since Rserve 0.3 the header can be either 4 or 8 bytes long, depending on the len parameter.
+        */
+    public static int setHdr(int ty, int len, byte[] buf, int o) {
+        buf[o]=(byte)((ty&255)|((len>0xfffff0)?DT_LARGE:0)); o++;
+	buf[o]=(byte)(len&255); o++;
+	buf[o]=(byte)((len&0xff00)>>8); o++;
+	buf[o]=(byte)((len&0xff0000)>>16); o++;
+        if (len>0xfffff0) { // for large data we need to set the next 4 bytes as well
+            buf[o]=(byte)((len&0xff000000)>>24); o++;
+            buf[o]=0; o++; // since len is int, we get 32-bits only
+            buf[o]=0; o++;
+            buf[o]=0; o++;
+        }
+        return o;
+    }
+
+    /** creates a new header according to the type and length of the parameter
+        @param ty type/cmd/resp byte
+        @param len length */        
+    public static byte[] newHdr(int ty, int len) {
+        byte[] hdr=new byte[(len>0xfffff0)?8:4];
+        setHdr(ty,len,hdr,0);
+        return hdr;
+    }
+    
+    /** converts bit-wise stored int in Intel-endian form into Java int
+	@param buf buffer containg the representation
+	@param o offset where to start (4 bytes will be used)
+	@return the int value. no bounds checking is done so you need to
+	        make sure that the buffer is big enough */
+    public static int getInt(byte[] buf, int o) {
+	return ((buf[o]&255)|((buf[o+1]&255)<<8)|((buf[o+2]&255)<<16)|((buf[o+3]&255)<<24));
+    }
+
+    /** converts bit-wise stored length from a header. "long" format is supported up to 32-bit
+	@param buf buffer
+	@param o offset of the header (length is at o+1)
+	@return length */
+    public static int getLen(byte[] buf, int o) {
+
+        return
+        ((buf[o]&64)>0)? // "long" format; still - we support 32-bit only
+        ((buf[o+1]&255)|((buf[o+2]&255)<<8)|((buf[o+3]&255)<<16)|((buf[o+4]&255)<<24))
+        :
+        ((buf[o+1]&255)|((buf[o+2]&255)<<8)|((buf[o+3]&255)<<16));
+    }
+
+    /** converts bit-wise Intel-endian format into long
+	@param buf buffer
+	@param o offset (8 bytes will be used)
+	@return long value */
+    public static long getLong(byte[] buf, int o) {
+	long low=((long)getInt(buf,o))&0xffffffffL;
+	long hi=((long)getInt(buf,o+4))&0xffffffffL;
+	hi<<=32; hi|=low;
+	return hi;
+    }
+
+    public static void setLong(long l, byte[] buf, int o) {
+	setInt((int)(l&0xffffffffL),buf,o);
+	setInt((int)(l>>32),buf,o+4);
+    }
+
+    /** sends a request with no attached parameters
+	@param cmd command
+	@return returned packet or <code>null</code> if something went wrong */
+    public RPacket request(int cmd) {
+        byte[] d = new byte[0];
+        return request(cmd,d);
+    }
+
+    /** sends a request with attached parameters
+        @param cmd command
+        @param cont contents - parameters
+        @return returned packet or <code>null</code> if something went wrong */
+    public RPacket request(int cmd, byte[] cont) {
+        return request(cmd,null,cont,0,(cont==null)?0:cont.length);
+    }
+
+    /** sends a request with attached prefix and  parameters. Both prefix and cont can be <code>null</code>. Effectively <code>request(a,b,null)</code> and <code>request(a,null,b)</code> are equivalent.
+	@param cmd command - a special command of -1 prevents request from sending anything
+        @param prefix - this content is sent *before* cont. It is provided to save memory copy operations where a small header precedes a large data chunk (usually prefix conatins the parameter header and cont contains the actual data).
+        @param cont contents
+        @param offset offset in cont where to start sending (if <0 then 0 is assumed, if >cont.length then no cont is sent)
+        @param len number of bytes in cont to send (it is clipped to the length of cont if necessary)
+	@return returned packet or <code>null</code> if something went wrong */
+    public RPacket request(int cmd, byte[] prefix, byte[] cont, int offset, int len) {
+        if (cont!=null) {
+            if (offset>=cont.length) { cont=null; len=0; }
+            else if (len>cont.length-offset) len=cont.length-offset;
+        }
+        if (offset<0) offset=0;
+        if (len<0) len=0;
+        int contlen=(cont==null)?0:len;
+        if (prefix!=null && prefix.length>0) contlen+=prefix.length;
+	byte[] hdr=new byte[16];
+	setInt(cmd,hdr,0);
+	setInt(contlen,hdr,4);
+	for(int i=8;i<16;i++) hdr[i]=0;
+	try {
+	    if (cmd!=-1) {
+		os.write(hdr);
+		if (prefix!=null && prefix.length>0)
+		    os.write(prefix);
+		if (cont!=null && cont.length>0)
+		    os.write(cont,offset,len);
+	    }
+
+	    byte[] ih=new byte[16];
+	    if (is.read(ih)!=16)
+		return null;
+	    int rep=getInt(ih,0);
+	    int rl =getInt(ih,4);
+	    if (rl>0) {
+		byte[] ct=new byte[rl];
+                int n=0;
+                while (n<rl) {
+                    int rd=is.read(ct,n,rl-n);
+                    n+=rd;
+                }
+		return new RPacket(rep,ct);
+	    }
+	    return new RPacket(rep,null);
+	} catch(Exception e) {
+	    e.printStackTrace();
+	    return null;
+	}
+    }
+
+    /** sends a request with one string parameter attached
+	@param cmd command
+	@param par parameter - length and DT_STRING will be prepended
+	@return returned packet or <code>null</code> if something went wrong */
+    public RPacket request(int cmd, String par) {
+	try {
+            byte[] b=par.getBytes(RConnection.transferCharset);
+            int sl=b.length+1;
+            if ((sl&3)>0) sl=(sl&0xfffffc)+4; // make sure the length is divisible by 4
+	    byte[] rq=new byte[sl+5];
+            int i;
+	    for(i=0;i<b.length;i++)
+                rq[i+4]=b[i];
+            while (i<sl) { // pad with 0
+                rq[i+4]=0; i++;
+            };
+	    setHdr(DT_STRING,sl,rq,0);
+	    return request(cmd,rq);
+	} catch (Exception e) {
+	    e.printStackTrace();
+	}
+	return null;
+    }
+
+    /** sends a request with one string parameter attached
+        @param cmd command
+        @param par parameter of the type DT_INT
+        @return returned packet or <code>null</code> if something went wrong */
+    public RPacket request(int cmd, int par) {
+	try {
+	    byte[] rq=new byte[8];
+	    setInt(par,rq,4);
+	    setHdr(DT_INT,4,rq,0);
+	    return request(cmd,rq);
+	} catch (Exception e) {
+	};
+	return null;
+    }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/protocol/jcrypt.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/protocol/jcrypt.java
new file mode 100644
index 0000000000000000000000000000000000000000..e815318458c465f395d91e7d24b92c62218aa67b
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/protocol/jcrypt.java
@@ -0,0 +1,617 @@
+package org.rosuda.REngine.Rserve.protocol;
+
+/****************************************************************************
+ * jcrypt.java
+ *
+ * Java-based implementation of the unix crypt command
+ *
+ * Based upon C source code written by Eric Young, eay@psych.uq.oz.au
+ *
+ ****************************************************************************/
+
+public class jcrypt
+{
+   private static final int ITERATIONS = 16;
+
+   private static final int con_salt[] =
+   {
+      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
+      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
+      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
+      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
+      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
+      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 
+      0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 
+      0x0A, 0x0B, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 
+      0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 
+      0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 
+      0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 
+      0x23, 0x24, 0x25, 0x20, 0x21, 0x22, 0x23, 0x24, 
+      0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 
+      0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 
+      0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 
+      0x3D, 0x3E, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 
+   };
+
+   private static final boolean shifts2[] =
+   {
+      false, false, true, true, true, true, true, true,
+      false, true,  true, true, true, true, true, false
+   };
+
+   private static final int skb[][] =
+   {
+      {
+         /* for C bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
+         0x00000000, 0x00000010, 0x20000000, 0x20000010, 
+         0x00010000, 0x00010010, 0x20010000, 0x20010010, 
+         0x00000800, 0x00000810, 0x20000800, 0x20000810, 
+         0x00010800, 0x00010810, 0x20010800, 0x20010810, 
+         0x00000020, 0x00000030, 0x20000020, 0x20000030, 
+         0x00010020, 0x00010030, 0x20010020, 0x20010030, 
+         0x00000820, 0x00000830, 0x20000820, 0x20000830, 
+         0x00010820, 0x00010830, 0x20010820, 0x20010830, 
+         0x00080000, 0x00080010, 0x20080000, 0x20080010, 
+         0x00090000, 0x00090010, 0x20090000, 0x20090010, 
+         0x00080800, 0x00080810, 0x20080800, 0x20080810, 
+         0x00090800, 0x00090810, 0x20090800, 0x20090810, 
+         0x00080020, 0x00080030, 0x20080020, 0x20080030, 
+         0x00090020, 0x00090030, 0x20090020, 0x20090030, 
+         0x00080820, 0x00080830, 0x20080820, 0x20080830, 
+         0x00090820, 0x00090830, 0x20090820, 0x20090830, 
+      },
+      {
+         /* for C bits (numbered as per FIPS 46) 7 8 10 11 12 13 */
+         0x00000000, 0x02000000, 0x00002000, 0x02002000, 
+         0x00200000, 0x02200000, 0x00202000, 0x02202000, 
+         0x00000004, 0x02000004, 0x00002004, 0x02002004, 
+         0x00200004, 0x02200004, 0x00202004, 0x02202004, 
+         0x00000400, 0x02000400, 0x00002400, 0x02002400, 
+         0x00200400, 0x02200400, 0x00202400, 0x02202400, 
+         0x00000404, 0x02000404, 0x00002404, 0x02002404, 
+         0x00200404, 0x02200404, 0x00202404, 0x02202404, 
+         0x10000000, 0x12000000, 0x10002000, 0x12002000, 
+         0x10200000, 0x12200000, 0x10202000, 0x12202000, 
+         0x10000004, 0x12000004, 0x10002004, 0x12002004, 
+         0x10200004, 0x12200004, 0x10202004, 0x12202004, 
+         0x10000400, 0x12000400, 0x10002400, 0x12002400, 
+         0x10200400, 0x12200400, 0x10202400, 0x12202400, 
+         0x10000404, 0x12000404, 0x10002404, 0x12002404, 
+         0x10200404, 0x12200404, 0x10202404, 0x12202404, 
+      },
+      {
+         /* for C bits (numbered as per FIPS 46) 14 15 16 17 19 20 */
+         0x00000000, 0x00000001, 0x00040000, 0x00040001, 
+         0x01000000, 0x01000001, 0x01040000, 0x01040001, 
+         0x00000002, 0x00000003, 0x00040002, 0x00040003, 
+         0x01000002, 0x01000003, 0x01040002, 0x01040003, 
+         0x00000200, 0x00000201, 0x00040200, 0x00040201, 
+         0x01000200, 0x01000201, 0x01040200, 0x01040201, 
+         0x00000202, 0x00000203, 0x00040202, 0x00040203, 
+         0x01000202, 0x01000203, 0x01040202, 0x01040203, 
+         0x08000000, 0x08000001, 0x08040000, 0x08040001, 
+         0x09000000, 0x09000001, 0x09040000, 0x09040001, 
+         0x08000002, 0x08000003, 0x08040002, 0x08040003, 
+         0x09000002, 0x09000003, 0x09040002, 0x09040003, 
+         0x08000200, 0x08000201, 0x08040200, 0x08040201, 
+         0x09000200, 0x09000201, 0x09040200, 0x09040201, 
+         0x08000202, 0x08000203, 0x08040202, 0x08040203, 
+         0x09000202, 0x09000203, 0x09040202, 0x09040203, 
+      },
+      {
+         /* for C bits (numbered as per FIPS 46) 21 23 24 26 27 28 */
+         0x00000000, 0x00100000, 0x00000100, 0x00100100, 
+         0x00000008, 0x00100008, 0x00000108, 0x00100108, 
+         0x00001000, 0x00101000, 0x00001100, 0x00101100, 
+         0x00001008, 0x00101008, 0x00001108, 0x00101108, 
+         0x04000000, 0x04100000, 0x04000100, 0x04100100, 
+         0x04000008, 0x04100008, 0x04000108, 0x04100108, 
+         0x04001000, 0x04101000, 0x04001100, 0x04101100, 
+         0x04001008, 0x04101008, 0x04001108, 0x04101108, 
+         0x00020000, 0x00120000, 0x00020100, 0x00120100, 
+         0x00020008, 0x00120008, 0x00020108, 0x00120108, 
+         0x00021000, 0x00121000, 0x00021100, 0x00121100, 
+         0x00021008, 0x00121008, 0x00021108, 0x00121108, 
+         0x04020000, 0x04120000, 0x04020100, 0x04120100, 
+         0x04020008, 0x04120008, 0x04020108, 0x04120108, 
+         0x04021000, 0x04121000, 0x04021100, 0x04121100, 
+         0x04021008, 0x04121008, 0x04021108, 0x04121108, 
+      },
+      {
+         /* for D bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
+         0x00000000, 0x10000000, 0x00010000, 0x10010000, 
+         0x00000004, 0x10000004, 0x00010004, 0x10010004, 
+         0x20000000, 0x30000000, 0x20010000, 0x30010000, 
+         0x20000004, 0x30000004, 0x20010004, 0x30010004, 
+         0x00100000, 0x10100000, 0x00110000, 0x10110000, 
+         0x00100004, 0x10100004, 0x00110004, 0x10110004, 
+         0x20100000, 0x30100000, 0x20110000, 0x30110000, 
+         0x20100004, 0x30100004, 0x20110004, 0x30110004, 
+         0x00001000, 0x10001000, 0x00011000, 0x10011000, 
+         0x00001004, 0x10001004, 0x00011004, 0x10011004, 
+         0x20001000, 0x30001000, 0x20011000, 0x30011000, 
+         0x20001004, 0x30001004, 0x20011004, 0x30011004, 
+         0x00101000, 0x10101000, 0x00111000, 0x10111000, 
+         0x00101004, 0x10101004, 0x00111004, 0x10111004, 
+         0x20101000, 0x30101000, 0x20111000, 0x30111000, 
+         0x20101004, 0x30101004, 0x20111004, 0x30111004, 
+      },
+      {
+         /* for D bits (numbered as per FIPS 46) 8 9 11 12 13 14 */
+         0x00000000, 0x08000000, 0x00000008, 0x08000008, 
+         0x00000400, 0x08000400, 0x00000408, 0x08000408, 
+         0x00020000, 0x08020000, 0x00020008, 0x08020008, 
+         0x00020400, 0x08020400, 0x00020408, 0x08020408, 
+         0x00000001, 0x08000001, 0x00000009, 0x08000009, 
+         0x00000401, 0x08000401, 0x00000409, 0x08000409, 
+         0x00020001, 0x08020001, 0x00020009, 0x08020009, 
+         0x00020401, 0x08020401, 0x00020409, 0x08020409, 
+         0x02000000, 0x0A000000, 0x02000008, 0x0A000008, 
+         0x02000400, 0x0A000400, 0x02000408, 0x0A000408, 
+         0x02020000, 0x0A020000, 0x02020008, 0x0A020008, 
+         0x02020400, 0x0A020400, 0x02020408, 0x0A020408, 
+         0x02000001, 0x0A000001, 0x02000009, 0x0A000009, 
+         0x02000401, 0x0A000401, 0x02000409, 0x0A000409, 
+         0x02020001, 0x0A020001, 0x02020009, 0x0A020009, 
+         0x02020401, 0x0A020401, 0x02020409, 0x0A020409, 
+      },
+      {
+         /* for D bits (numbered as per FIPS 46) 16 17 18 19 20 21 */
+         0x00000000, 0x00000100, 0x00080000, 0x00080100, 
+         0x01000000, 0x01000100, 0x01080000, 0x01080100, 
+         0x00000010, 0x00000110, 0x00080010, 0x00080110, 
+         0x01000010, 0x01000110, 0x01080010, 0x01080110, 
+         0x00200000, 0x00200100, 0x00280000, 0x00280100, 
+         0x01200000, 0x01200100, 0x01280000, 0x01280100, 
+         0x00200010, 0x00200110, 0x00280010, 0x00280110, 
+         0x01200010, 0x01200110, 0x01280010, 0x01280110, 
+         0x00000200, 0x00000300, 0x00080200, 0x00080300, 
+         0x01000200, 0x01000300, 0x01080200, 0x01080300, 
+         0x00000210, 0x00000310, 0x00080210, 0x00080310, 
+         0x01000210, 0x01000310, 0x01080210, 0x01080310, 
+         0x00200200, 0x00200300, 0x00280200, 0x00280300, 
+         0x01200200, 0x01200300, 0x01280200, 0x01280300, 
+         0x00200210, 0x00200310, 0x00280210, 0x00280310, 
+         0x01200210, 0x01200310, 0x01280210, 0x01280310, 
+      },
+      {
+         /* for D bits (numbered as per FIPS 46) 22 23 24 25 27 28 */
+         0x00000000, 0x04000000, 0x00040000, 0x04040000, 
+         0x00000002, 0x04000002, 0x00040002, 0x04040002, 
+         0x00002000, 0x04002000, 0x00042000, 0x04042000, 
+         0x00002002, 0x04002002, 0x00042002, 0x04042002, 
+         0x00000020, 0x04000020, 0x00040020, 0x04040020, 
+         0x00000022, 0x04000022, 0x00040022, 0x04040022, 
+         0x00002020, 0x04002020, 0x00042020, 0x04042020, 
+         0x00002022, 0x04002022, 0x00042022, 0x04042022, 
+         0x00000800, 0x04000800, 0x00040800, 0x04040800, 
+         0x00000802, 0x04000802, 0x00040802, 0x04040802, 
+         0x00002800, 0x04002800, 0x00042800, 0x04042800, 
+         0x00002802, 0x04002802, 0x00042802, 0x04042802, 
+         0x00000820, 0x04000820, 0x00040820, 0x04040820, 
+         0x00000822, 0x04000822, 0x00040822, 0x04040822, 
+         0x00002820, 0x04002820, 0x00042820, 0x04042820, 
+         0x00002822, 0x04002822, 0x00042822, 0x04042822, 
+      },
+   };
+
+   private static final int SPtrans[][] =
+   {
+      {
+         /* nibble 0 */
+         0x00820200, 0x00020000, 0x80800000, 0x80820200,
+         0x00800000, 0x80020200, 0x80020000, 0x80800000,
+         0x80020200, 0x00820200, 0x00820000, 0x80000200,
+         0x80800200, 0x00800000, 0x00000000, 0x80020000,
+         0x00020000, 0x80000000, 0x00800200, 0x00020200,
+         0x80820200, 0x00820000, 0x80000200, 0x00800200,
+         0x80000000, 0x00000200, 0x00020200, 0x80820000,
+         0x00000200, 0x80800200, 0x80820000, 0x00000000,
+         0x00000000, 0x80820200, 0x00800200, 0x80020000,
+         0x00820200, 0x00020000, 0x80000200, 0x00800200,
+         0x80820000, 0x00000200, 0x00020200, 0x80800000,
+         0x80020200, 0x80000000, 0x80800000, 0x00820000,
+         0x80820200, 0x00020200, 0x00820000, 0x80800200,
+         0x00800000, 0x80000200, 0x80020000, 0x00000000,
+         0x00020000, 0x00800000, 0x80800200, 0x00820200,
+         0x80000000, 0x80820000, 0x00000200, 0x80020200,
+      },
+      {
+         /* nibble 1 */
+         0x10042004, 0x00000000, 0x00042000, 0x10040000,
+         0x10000004, 0x00002004, 0x10002000, 0x00042000,
+         0x00002000, 0x10040004, 0x00000004, 0x10002000,
+         0x00040004, 0x10042000, 0x10040000, 0x00000004,
+         0x00040000, 0x10002004, 0x10040004, 0x00002000,
+         0x00042004, 0x10000000, 0x00000000, 0x00040004,
+         0x10002004, 0x00042004, 0x10042000, 0x10000004,
+         0x10000000, 0x00040000, 0x00002004, 0x10042004,
+         0x00040004, 0x10042000, 0x10002000, 0x00042004,
+         0x10042004, 0x00040004, 0x10000004, 0x00000000,
+         0x10000000, 0x00002004, 0x00040000, 0x10040004,
+         0x00002000, 0x10000000, 0x00042004, 0x10002004,
+         0x10042000, 0x00002000, 0x00000000, 0x10000004,
+         0x00000004, 0x10042004, 0x00042000, 0x10040000,
+         0x10040004, 0x00040000, 0x00002004, 0x10002000,
+         0x10002004, 0x00000004, 0x10040000, 0x00042000,
+      },
+      {
+         /* nibble 2 */
+         0x41000000, 0x01010040, 0x00000040, 0x41000040,
+         0x40010000, 0x01000000, 0x41000040, 0x00010040,
+         0x01000040, 0x00010000, 0x01010000, 0x40000000,
+         0x41010040, 0x40000040, 0x40000000, 0x41010000,
+         0x00000000, 0x40010000, 0x01010040, 0x00000040,
+         0x40000040, 0x41010040, 0x00010000, 0x41000000,
+         0x41010000, 0x01000040, 0x40010040, 0x01010000,
+         0x00010040, 0x00000000, 0x01000000, 0x40010040,
+         0x01010040, 0x00000040, 0x40000000, 0x00010000,
+         0x40000040, 0x40010000, 0x01010000, 0x41000040,
+         0x00000000, 0x01010040, 0x00010040, 0x41010000,
+         0x40010000, 0x01000000, 0x41010040, 0x40000000,
+         0x40010040, 0x41000000, 0x01000000, 0x41010040,
+         0x00010000, 0x01000040, 0x41000040, 0x00010040,
+         0x01000040, 0x00000000, 0x41010000, 0x40000040,
+         0x41000000, 0x40010040, 0x00000040, 0x01010000,
+      },
+      {
+         /* nibble 3 */
+         0x00100402, 0x04000400, 0x00000002, 0x04100402,
+         0x00000000, 0x04100000, 0x04000402, 0x00100002,
+         0x04100400, 0x04000002, 0x04000000, 0x00000402,
+         0x04000002, 0x00100402, 0x00100000, 0x04000000,
+         0x04100002, 0x00100400, 0x00000400, 0x00000002,
+         0x00100400, 0x04000402, 0x04100000, 0x00000400,
+         0x00000402, 0x00000000, 0x00100002, 0x04100400,
+         0x04000400, 0x04100002, 0x04100402, 0x00100000,
+         0x04100002, 0x00000402, 0x00100000, 0x04000002,
+         0x00100400, 0x04000400, 0x00000002, 0x04100000,
+         0x04000402, 0x00000000, 0x00000400, 0x00100002,
+         0x00000000, 0x04100002, 0x04100400, 0x00000400,
+         0x04000000, 0x04100402, 0x00100402, 0x00100000,
+         0x04100402, 0x00000002, 0x04000400, 0x00100402,
+         0x00100002, 0x00100400, 0x04100000, 0x04000402,
+         0x00000402, 0x04000000, 0x04000002, 0x04100400,
+      },
+      {
+         /* nibble 4 */
+         0x02000000, 0x00004000, 0x00000100, 0x02004108,
+         0x02004008, 0x02000100, 0x00004108, 0x02004000,
+         0x00004000, 0x00000008, 0x02000008, 0x00004100,
+         0x02000108, 0x02004008, 0x02004100, 0x00000000,
+         0x00004100, 0x02000000, 0x00004008, 0x00000108,
+         0x02000100, 0x00004108, 0x00000000, 0x02000008,
+         0x00000008, 0x02000108, 0x02004108, 0x00004008,
+         0x02004000, 0x00000100, 0x00000108, 0x02004100,
+         0x02004100, 0x02000108, 0x00004008, 0x02004000,
+         0x00004000, 0x00000008, 0x02000008, 0x02000100,
+         0x02000000, 0x00004100, 0x02004108, 0x00000000,
+         0x00004108, 0x02000000, 0x00000100, 0x00004008,
+         0x02000108, 0x00000100, 0x00000000, 0x02004108,
+         0x02004008, 0x02004100, 0x00000108, 0x00004000,
+         0x00004100, 0x02004008, 0x02000100, 0x00000108,
+         0x00000008, 0x00004108, 0x02004000, 0x02000008,
+      },
+      {
+         /* nibble 5 */
+         0x20000010, 0x00080010, 0x00000000, 0x20080800,
+         0x00080010, 0x00000800, 0x20000810, 0x00080000,
+         0x00000810, 0x20080810, 0x00080800, 0x20000000,
+         0x20000800, 0x20000010, 0x20080000, 0x00080810,
+         0x00080000, 0x20000810, 0x20080010, 0x00000000,
+         0x00000800, 0x00000010, 0x20080800, 0x20080010,
+         0x20080810, 0x20080000, 0x20000000, 0x00000810,
+         0x00000010, 0x00080800, 0x00080810, 0x20000800,
+         0x00000810, 0x20000000, 0x20000800, 0x00080810,
+         0x20080800, 0x00080010, 0x00000000, 0x20000800,
+         0x20000000, 0x00000800, 0x20080010, 0x00080000,
+         0x00080010, 0x20080810, 0x00080800, 0x00000010,
+         0x20080810, 0x00080800, 0x00080000, 0x20000810,
+         0x20000010, 0x20080000, 0x00080810, 0x00000000,
+         0x00000800, 0x20000010, 0x20000810, 0x20080800,
+         0x20080000, 0x00000810, 0x00000010, 0x20080010,
+      },
+      {
+         /* nibble 6 */
+         0x00001000, 0x00000080, 0x00400080, 0x00400001,
+         0x00401081, 0x00001001, 0x00001080, 0x00000000,
+         0x00400000, 0x00400081, 0x00000081, 0x00401000,
+         0x00000001, 0x00401080, 0x00401000, 0x00000081,
+         0x00400081, 0x00001000, 0x00001001, 0x00401081,
+         0x00000000, 0x00400080, 0x00400001, 0x00001080,
+         0x00401001, 0x00001081, 0x00401080, 0x00000001,
+         0x00001081, 0x00401001, 0x00000080, 0x00400000,
+         0x00001081, 0x00401000, 0x00401001, 0x00000081,
+         0x00001000, 0x00000080, 0x00400000, 0x00401001,
+         0x00400081, 0x00001081, 0x00001080, 0x00000000,
+         0x00000080, 0x00400001, 0x00000001, 0x00400080,
+         0x00000000, 0x00400081, 0x00400080, 0x00001080,
+         0x00000081, 0x00001000, 0x00401081, 0x00400000,
+         0x00401080, 0x00000001, 0x00001001, 0x00401081,
+         0x00400001, 0x00401080, 0x00401000, 0x00001001,
+      },
+      {
+         /* nibble 7 */
+         0x08200020, 0x08208000, 0x00008020, 0x00000000,
+         0x08008000, 0x00200020, 0x08200000, 0x08208020,
+         0x00000020, 0x08000000, 0x00208000, 0x00008020,
+         0x00208020, 0x08008020, 0x08000020, 0x08200000,
+         0x00008000, 0x00208020, 0x00200020, 0x08008000,
+         0x08208020, 0x08000020, 0x00000000, 0x00208000,
+         0x08000000, 0x00200000, 0x08008020, 0x08200020,
+         0x00200000, 0x00008000, 0x08208000, 0x00000020,
+         0x00200000, 0x00008000, 0x08000020, 0x08208020,
+         0x00008020, 0x08000000, 0x00000000, 0x00208000,
+         0x08200020, 0x08008020, 0x08008000, 0x00200020,
+         0x08208000, 0x00000020, 0x00200020, 0x08008000,
+         0x08208020, 0x00200000, 0x08200000, 0x08000020,
+         0x00208000, 0x00008020, 0x08008020, 0x08200000,
+         0x00000020, 0x08208000, 0x00208020, 0x00000000,
+         0x08000000, 0x08200020, 0x00008000, 0x00208020
+      }
+   };
+
+   private static final int cov_2char[] =
+   {
+      0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 
+      0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 
+      0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 
+      0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 
+      0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x61, 0x62, 
+      0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 
+      0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 
+      0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A
+   };
+
+   private static final int byteToUnsigned(byte b)
+   {
+      int value = (int)b;
+
+      return(value >= 0 ? value : value + 256);
+   }
+
+   private static int fourBytesToInt(byte b[], int offset)
+   {
+      int value;
+
+      value  =  byteToUnsigned(b[offset++]);
+      value |= (byteToUnsigned(b[offset++]) <<  8);
+      value |= (byteToUnsigned(b[offset++]) << 16);
+      value |= (byteToUnsigned(b[offset++]) << 24);
+
+      return(value);
+   }
+
+   private static final void intToFourBytes(int iValue, byte b[], int offset)
+   {
+      b[offset++] = (byte)((iValue)        & 0xff);
+      b[offset++] = (byte)((iValue >>> 8 ) & 0xff);
+      b[offset++] = (byte)((iValue >>> 16) & 0xff);
+      b[offset++] = (byte)((iValue >>> 24) & 0xff);
+   }
+
+   private static final void PERM_OP(int a, int b, int n, int m, int results[])
+   {
+      int t;
+
+      t = ((a >>> n) ^ b) & m;
+      a ^= t << n;
+      b ^= t;
+
+      results[0] = a;
+      results[1] = b;
+   }
+
+   private static final int HPERM_OP(int a, int n, int m)
+   {
+      int t;
+
+      t = ((a << (16 - n)) ^ a) & m;
+      a = a ^ t ^ (t >>> (16 - n));
+
+      return(a);
+   }
+
+   private static int [] des_set_key(byte key[])
+   {
+      int schedule[] = new int[ITERATIONS * 2];
+
+      int c = fourBytesToInt(key, 0);
+      int d = fourBytesToInt(key, 4);
+
+      int results[] = new int[2];
+
+      PERM_OP(d, c, 4, 0x0f0f0f0f, results);
+      d = results[0]; c = results[1];
+
+      c = HPERM_OP(c, -2, 0xcccc0000);
+      d = HPERM_OP(d, -2, 0xcccc0000);
+
+      PERM_OP(d, c, 1, 0x55555555, results);
+      d = results[0]; c = results[1];
+
+      PERM_OP(c, d, 8, 0x00ff00ff, results);
+      c = results[0]; d = results[1];
+
+      PERM_OP(d, c, 1, 0x55555555, results);
+      d = results[0]; c = results[1];
+
+      d = (((d & 0x000000ff) <<  16) |  (d & 0x0000ff00)     |
+           ((d & 0x00ff0000) >>> 16) | ((c & 0xf0000000) >>> 4));
+      c &= 0x0fffffff;
+
+      int s, t;
+      int j = 0;
+
+      for(int i = 0; i < ITERATIONS; i ++)
+      {
+         if(shifts2[i])
+         {
+            c = (c >>> 2) | (c << 26);
+            d = (d >>> 2) | (d << 26);
+         }
+         else
+         {
+            c = (c >>> 1) | (c << 27);
+            d = (d >>> 1) | (d << 27);
+         }
+
+         c &= 0x0fffffff;
+         d &= 0x0fffffff;
+
+         s = skb[0][ (c       ) & 0x3f                       ]|
+             skb[1][((c >>>  6) & 0x03) | ((c >>>  7) & 0x3c)]|
+             skb[2][((c >>> 13) & 0x0f) | ((c >>> 14) & 0x30)]|
+             skb[3][((c >>> 20) & 0x01) | ((c >>> 21) & 0x06) |
+                                          ((c >>> 22) & 0x38)];
+
+         t = skb[4][ (d     )  & 0x3f                       ]|
+             skb[5][((d >>> 7) & 0x03) | ((d >>>  8) & 0x3c)]|
+             skb[6][ (d >>>15) & 0x3f                       ]|
+             skb[7][((d >>>21) & 0x0f) | ((d >>> 22) & 0x30)];
+
+         schedule[j++] = ((t <<  16) | (s & 0x0000ffff)) & 0xffffffff;
+         s             = ((s >>> 16) | (t & 0xffff0000));
+
+         s             = (s << 4) | (s >>> 28);
+         schedule[j++] = s & 0xffffffff;
+      }
+      return(schedule);
+   }
+
+   private static final int D_ENCRYPT
+   (
+      int L, int R, int S, int E0, int E1, int s[]
+   )
+   {
+      int t, u, v;
+
+      v = R ^ (R >>> 16);
+      u = v & E0;
+      v = v & E1;
+      u = (u ^ (u << 16)) ^ R ^ s[S];
+      t = (v ^ (v << 16)) ^ R ^ s[S + 1];
+      t = (t >>> 4) | (t << 28);
+
+      L ^= SPtrans[1][(t       ) & 0x3f] |
+           SPtrans[3][(t >>>  8) & 0x3f] |
+           SPtrans[5][(t >>> 16) & 0x3f] |
+           SPtrans[7][(t >>> 24) & 0x3f] |
+           SPtrans[0][(u       ) & 0x3f] |
+           SPtrans[2][(u >>>  8) & 0x3f] |
+           SPtrans[4][(u >>> 16) & 0x3f] |
+           SPtrans[6][(u >>> 24) & 0x3f];
+
+      return(L);
+   }
+
+   private static final int [] body(int schedule[], int Eswap0, int Eswap1)
+   {
+      int left = 0;
+      int right = 0;
+      int t     = 0;
+
+      for(int j = 0; j < 25; j ++)
+      {
+         for(int i = 0; i < ITERATIONS * 2; i += 4)
+         {
+            left  = D_ENCRYPT(left,  right, i,     Eswap0, Eswap1, schedule);
+            right = D_ENCRYPT(right, left,  i + 2, Eswap0, Eswap1, schedule);
+         }
+         t     = left; 
+         left  = right; 
+         right = t;
+      }
+
+      t = right;
+
+      right = (left >>> 1) | (left << 31);
+      left  = (t    >>> 1) | (t    << 31);
+
+      left  &= 0xffffffff;
+      right &= 0xffffffff;
+
+      int results[] = new int[2];
+
+      PERM_OP(right, left, 1, 0x55555555, results); 
+      right = results[0]; left = results[1];
+
+      PERM_OP(left, right, 8, 0x00ff00ff, results); 
+      left = results[0]; right = results[1];
+
+      PERM_OP(right, left, 2, 0x33333333, results); 
+      right = results[0]; left = results[1];
+
+      PERM_OP(left, right, 16, 0x0000ffff, results);
+      left = results[0]; right = results[1];
+
+      PERM_OP(right, left, 4, 0x0f0f0f0f, results);
+      right = results[0]; left = results[1];
+
+      int out[] = new int[2];
+
+      out[0] = left; out[1] = right;
+
+      return(out);
+   }
+
+   public static final String crypt(String salt, String original)
+   {
+      while(salt.length() < 2)
+         salt += "A";
+
+      StringBuffer buffer = new StringBuffer("             ");
+
+      char charZero = salt.charAt(0);
+      char charOne  = salt.charAt(1);
+
+      buffer.setCharAt(0, charZero);
+      buffer.setCharAt(1, charOne);
+
+      int Eswap0 = con_salt[(int)charZero];
+      int Eswap1 = con_salt[(int)charOne] << 4;
+ 
+      byte key[] = new byte[8];
+
+      for(int i = 0; i < key.length; i ++)
+         key[i] = (byte)0;
+
+      for(int i = 0; i < key.length && i < original.length(); i ++)
+      {
+         int iChar = (int)original.charAt(i);
+
+         key[i] = (byte)(iChar << 1);
+      }
+
+      int schedule[] = des_set_key(key);
+      int out[]      = body(schedule, Eswap0, Eswap1);
+
+      byte b[] = new byte[9];
+
+      intToFourBytes(out[0], b, 0);
+      intToFourBytes(out[1], b, 4);
+      b[8] = 0;
+
+      for(int i = 2, y = 0, u = 0x80; i < 13; i ++)
+      {
+         for(int j = 0, c = 0; j < 6; j ++)
+         {
+            c <<= 1;
+
+            if(((int)b[y] & u) != 0)
+               c |= 1;
+
+            u >>>= 1;
+
+            if(u == 0)
+            {
+               y++;
+               u = 0x80;
+            }
+            buffer.setCharAt(i, (char)cov_2char[c]);
+         }
+      }
+      return(buffer.toString());
+   }
+}
+   
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/src/test/java/org/rosuda/rserve/RserveTest.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/src/test/java/org/rosuda/rserve/RserveTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..652274b763085b1500d2e35ddebfa7fe6f3ef255
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/src/test/java/org/rosuda/rserve/RserveTest.java
@@ -0,0 +1,428 @@
+package org.rosuda.REngine.Rserve;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Assume;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.fail;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.rosuda.REngine.REXP;
+import org.rosuda.REngine.REXPDouble;
+import org.rosuda.REngine.REXPFactor;
+import org.rosuda.REngine.REXPGenericVector;
+import org.rosuda.REngine.REXPInteger;
+import org.rosuda.REngine.REXPList;
+import org.rosuda.REngine.REXPLogical;
+import org.rosuda.REngine.REXPMismatchException;
+import org.rosuda.REngine.REXPRaw;
+import org.rosuda.REngine.REXPString;
+import org.rosuda.REngine.REngine;
+import org.rosuda.REngine.REngineException;
+import org.rosuda.REngine.RFactor;
+import org.rosuda.REngine.RList;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ *
+ * @author cemmersb
+ */
+public class RserveTest {
+
+  /**
+   * Provides some detailed output on test execution.
+   */
+  private static final Logger LOGGER = LoggerFactory.getLogger(RserveTest.class);
+  /**
+   * Connection object to establish communication to Rserve.
+   */
+  private RConnection connection = null;
+  /**
+   * Backend agnostic object providing an abstraction to RConnection.
+   */
+  private REngine engine = null;
+
+  @BeforeClass
+  static public void startUpRserve() throws RserveException {
+      if (!org.rosuda.REngine.Rserve.StartRserve.checkLocalRserve())
+	  fail("cannot start local Rserve for tests");
+  }
+
+  @Before
+  public void createConnection() throws RserveException {
+      connection = new RConnection();
+      engine = (REngine) connection;
+  }
+
+  @Test
+  public void versionStringTest() throws RserveException, REXPMismatchException {
+    final String versionString = connection.eval("R.version$version.string").asString();
+    LOGGER.debug(versionString);
+    assertNotNull(versionString);
+    assertTrue(versionString.contains("R version"));
+  }
+
+  @Test
+  public void stringAndListRetrievalTest() throws RserveException, REXPMismatchException {
+    final RList list = connection.eval("{d=data.frame(\"huhu\",c(11:20)); lapply(d,as.character)}").asList();
+    LOGGER.debug(list.toString());
+    assertNotNull(list);
+    for (Object object : list) {
+      if (object instanceof REXPString) {
+        REXPString rexpString = (REXPString) object;
+        // Check if 10 elements have been received within the REXPString object
+        assertNotNull(rexpString);
+        assertEquals(10, rexpString.length());
+        // Check the value of the objects
+        if (object.equals(list.firstElement())) {
+          String[] value = rexpString.asStrings();
+          for (String string : value) {
+            assertNotNull(string);
+            assertEquals("huhu", string);
+          }
+        } else if (object.equals(list.lastElement())) {
+          String[] numbers = rexpString.asStrings();
+          for (String string : numbers) {
+            assertNotNull(string);
+            assertTrue(11 <= Integer.parseInt(string)
+                    && Integer.parseInt(string) <= 20);
+          }
+        } else {
+          // Fail if there are more than first and last element as result
+          fail("There are more elements than expected within the RList object.");
+        }
+      } else {
+        // Fail if the response is other than REXPString
+        fail("Could not find object of instance REXPString.");
+      }
+    }
+  }
+
+  @Test
+  public void doubleVectorNaNaNSupportTest() throws REngineException, REXPMismatchException {
+    final double r_na = REXPDouble.NA;
+    double x[] = {1.0, 0.5, r_na, Double.NaN, 3.5};
+    connection.assign("x", x);
+
+    // Check of Na/NaN can be assigned and retrieved
+    final String nas = connection.eval("paste(capture.output(print(x)),collapse='\\n')").asString();
+    assertNotNull(nas);
+    assertEquals("[1] 1.0 0.5  NA NaN 3.5", nas);
+
+    // Check of Na/NaN can be pulled
+    final REXP rexp = connection.eval("c(2.2, NA_real_, NaN)");
+    assertNotNull(rexp);
+    assertTrue(rexp.isNumeric());
+    assertFalse(rexp.isInteger());
+
+    // Check if NA/NaN can be pulled
+    final boolean nal[] = rexp.isNA();
+    assertNotNull(nal);
+    assertTrue(nal.length == 3);
+    assertFalse(nal[0]);
+    assertTrue(nal[1]);
+    assertFalse(nal[2]);
+
+    // Check of NA/NAN can be pulled
+    x = rexp.asDoubles();
+    assertNotNull(x);
+    assertTrue(x.length == 3);
+    assertTrue(Double.isNaN(x[2]));
+    assertFalse(REXPDouble.isNA(x[2]));
+    assertTrue(REXPDouble.isNA(x[1]));
+  }
+
+  @Test
+  public void assignListsAndVectorsTest() throws RserveException, REXPMismatchException, REngineException {
+    // Initialize REXP container
+    final REXPInteger rexpInteger = new REXPInteger(new int[]{0, 1, 2, 3});
+    final REXPDouble rexpDouble = new REXPDouble(new double[]{0.5, 1.2, 2.3, 3.0});
+    // Assign REXP container to RList
+    final RList list = new RList();
+    list.put("a", rexpInteger);
+    list.put("b", rexpDouble);
+    // Variables to assign List, Vector and DataFrame
+    final String[] vars = {"x", "y", "z"};
+    // Assign all three varaiables
+    connection.assign(vars[0], new REXPList(list));
+    connection.assign(vars[1], new REXPGenericVector(list));
+    connection.assign(vars[2], REXP.createDataFrame(list));
+    // Evaluate result for all assignments
+    for (String var : vars) {
+      checkListAndVectorsRexpResult(var, list, rexpInteger, rexpDouble);
+    }
+  }
+
+  private void checkListAndVectorsRexpResult(String var, RList list,
+          REXPInteger rexpInteger, REXPDouble rexpDouble) throws REXPMismatchException, REngineException {
+    REXP rexp = connection.parseAndEval("x");
+    assertNotNull(rexp);
+    assertEquals(list.names, rexp.asList().names);
+    try {
+      REXPInteger a = (REXPInteger) rexp.asList().get("a");
+      REXPDouble b = (REXPDouble) rexp.asList().get("b");
+      // Check of the result for a corresponds to rexpInteger length
+      assertTrue(a.length() == rexpInteger.length());
+      assertTrue(b.length() == rexpDouble.length());
+      // Iterate and check values
+      for (int i = 0; i < rexpInteger.length(); i++) {
+        assertEquals(rexpInteger.asIntegers()[i], a.asIntegers()[i]);
+      }
+    } catch (ClassCastException exception) {
+      LOGGER.error(exception.getMessage());
+      fail("Could not cast object to the required type.");
+    }
+  }
+
+  @Test
+  public void logicalsSupportTest() throws RserveException, REngineException, REXPMismatchException {
+    final REXPLogical rexpLogical = new REXPLogical(new boolean[]{true, false, true});
+    connection.assign("b", rexpLogical);
+
+    REXP rexp = connection.parseAndEval("b");
+    assertNotNull(rexp);
+    assertTrue(rexp.isLogical());
+    assertEquals(rexpLogical.length(), rexp.length());
+    try {
+      final boolean[] result = ((REXPLogical) rexp).isTRUE();
+      assertTrue(result[0]);
+      assertFalse(result[1]);
+      assertTrue(result[2]);
+    } catch (ClassCastException exception) {
+      LOGGER.error(exception.getMessage());
+      fail("Could not cast REXP to REPLogical.");
+    }
+
+    rexp = connection.parseAndEval("c(TRUE,FALSE,NA)");
+    assertNotNull(rexp);
+    assertTrue(rexp.isLogical());
+    assertEquals(rexpLogical.length(), rexp.length());
+    // Check result values of rexp.isTRUE()
+    boolean result1[] = ((REXPLogical) rexp).isTRUE();
+    assertTrue(result1[0]);
+    assertFalse(result1[1]);
+    assertFalse(result1[2]);
+    // Check result values of rexp.isFALSE()
+    boolean result2[] = ((REXPLogical) rexp).isFALSE();
+    assertFalse(result2[0]);
+    assertTrue(result2[1]);
+    assertFalse(result2[2]);
+    // Check result values of rexp.isNA()
+    boolean result3[] = ((REXPLogical) rexp).isNA();
+    assertFalse(result3[0]);
+    assertFalse(result3[1]);
+    assertTrue(result3[2]);
+  }
+
+  @Test
+  public void s3ObjectFunctionalityTest() throws REngineException, REXPMismatchException {
+    final REXPInteger rexpInteger = new REXPInteger(new int[]{0, 1, 2, 3});
+    final REXPDouble rexpDouble = new REXPDouble(new double[]{0.5, 1.2, 2.3, 3.0});
+
+    final RList list = new RList();
+    list.put("a", rexpInteger);
+    list.put("b", rexpDouble);
+
+    connection.assign("z", REXP.createDataFrame(list));
+
+    final REXP rexp = connection.parseAndEval("z[2,2]");
+    assertNotNull(rexp);
+    assertTrue(rexp.length() == 1);
+    assertTrue(rexp.asDouble() == 1.2);
+  }
+
+  @Test
+  public void dataFramePassThroughTest() throws REngineException, REXPMismatchException {
+    final REXP dataFrame = connection.parseAndEval("{data(iris); iris}");
+    connection.assign("df", dataFrame);
+
+    final REXP rexp = connection.eval("identical(df, iris)");
+    assertNotNull(rexp);
+    assertTrue(rexp.isLogical());
+    assertTrue(rexp.length() == 1);
+    assertTrue(((REXPLogical) rexp).isTRUE()[0]);
+  }
+
+  @Test
+  public void factorSupportTest() throws REngineException, REXPMismatchException {
+    REXP factor = connection.parseAndEval("factor(paste('F',as.integer(runif(20)*5),sep=''))");
+    assertNotNull(factor);
+    assertTrue(factor.isFactor());
+
+    factor = connection.parseAndEval("factor('foo')");
+    assertNotNull(factor);
+    assertTrue(factor.isFactor());
+    assertEquals("foo", factor.asFactor().at(0));
+
+    connection.assign("f", new REXPFactor(new RFactor(new String[]{"foo", "bar", "foo", "foo", null, "bar"})));
+    factor = connection.parseAndEval("f");
+    assertNotNull(factor);
+    assertTrue(factor.isFactor());
+
+    factor = connection.parseAndEval("as.factor(c(1,'a','b',1,'b'))");
+    assertNotNull(factor);
+    assertTrue(factor.isFactor());
+  }
+
+  @Test
+  public void lowessTest() throws RserveException, REXPMismatchException, REngineException {
+    final double x[] = connection.eval("rnorm(100)").asDoubles();
+    final double y[] = connection.eval("rnorm(100)").asDoubles();
+    connection.assign("x", x);
+    connection.assign("y", y);
+
+    final RList list = connection.parseAndEval("lowess(x,y)").asList();
+    assertNotNull(list);
+    assertEquals(x.length, list.at("x").asDoubles().length);
+    assertEquals(y.length, list.at("y").asDoubles().length);
+  }
+
+  @Test
+  public void multiLineExpressionTest() throws RserveException, REXPMismatchException {
+    final REXP rexp = connection.eval("{ a=1:10\nb=11:20\nmean(b-a) }\n");
+    assertNotNull(rexp);
+    assertEquals(10, rexp.asInteger());
+  }
+
+  @Test
+  public void matrixTest() throws REngineException, REXPMismatchException {
+    final int m = 100;
+    final int n = 100;
+    // Initialize matrix and assign to R environment
+    final double[] matrix = new double[m * n];
+    int counter = 0;
+    while (counter < m * n) {
+      matrix[counter++] = counter / 100;
+    }
+    connection.assign("m1", matrix);
+    connection.voidEval("m1 <- matrix(m1," + m + "," + n + ")");
+    // Initialize second matrix and assign to R environment
+    double[][] matrix2 = new double[m][n];
+    for (int i = 0; i < m; i++) {
+      for (int j = 0; j < n; j++) {
+        matrix2[i][j] = matrix[i + j * m];
+      }
+    }
+    connection.assign("m2", REXP.createDoubleMatrix(matrix2));
+    // Evaluate result
+    final REXP rexp = connection.eval("identical(m1,m2)");
+    assertNotNull(rexp);
+    assertTrue(rexp.asInteger() == 1);
+  }
+
+  @Test
+  public void rawVectorSerializationTest() throws RserveException, REXPMismatchException {
+    final byte[] bytes = connection.eval("serialize(ls, NULL, ascii=FALSE)").asBytes();
+    assertNotNull(bytes);
+
+    connection.assign("r", new REXPRaw(bytes));
+    String[] result = connection.eval("unserialize(r)()").asStrings();
+    assertNotNull(result);
+    assertEquals("r", result[0]);
+  }
+
+  @Test
+  public void vectorNAHandlingTest() throws REngineException, REXPMismatchException {
+    engine.assign("s", new String[]{"foo", "", null, "NA"});
+    final int nas[] = engine.parseAndEval("is.na(s)").asIntegers();
+    assertNotNull(nas);
+    assertEquals(4, nas.length);
+    assertEquals(REXPLogical.FALSE, nas[0]);
+    assertEquals(REXPLogical.FALSE, nas[1]);
+    assertEquals(REXPLogical.TRUE, nas[2]);
+    assertEquals(REXPLogical.FALSE, nas[3]);
+
+    final String[] result = engine.parseAndEval("c('foo', '', NA, 'NA')").asStrings();
+    assertNotNull(result);
+    assertEquals(4, result.length);
+    assertNotNull(result[0]);
+    assertNotNull(result[1]);
+    assertEquals("", result[1]);
+    assertNull(result[2]);
+    assertNotNull(result[3]);
+
+    final REXP rexp = engine.parseAndEval("identical(s, c('foo', '', NA, 'NA'))");
+    assertNotNull(rexp);
+    assertEquals(REXPLogical.TRUE, rexp.asInteger());
+
+    boolean na[] = engine.parseAndEval("s").isNA();
+    assertNotNull(na);
+    assertEquals(4, na.length);
+    assertFalse(na[0]);
+    assertFalse(na[1]);
+    assertTrue(na[2]);
+    assertFalse(na[3]);
+  }
+
+  @Test
+  public void encodingSupportTest() throws RserveException, REngineException, REXPMismatchException {
+    // hiragana (literally, in hiragana ;))
+    final String testString = "ひらがな";
+    connection.setStringEncoding("utf8");
+    connection.assign("s", testString);
+
+    final REXP rexp = connection.parseAndEval("nchar(s)");
+    assertNotNull(rexp);
+    assertTrue(rexp.isInteger());
+    assertEquals(4, rexp.asInteger());
+  }
+
+  @Test
+  public void controlCommandTest() throws RserveException, REXPMismatchException {
+      final String key = "rn" + Math.random();
+      boolean hasCtrl = true;
+      try {
+	  connection.serverEval("xXx<-'" + key + "'");
+      } catch (RserveException re) {
+	  // we expect ERR_ctrl_closed if CTRL is disabled, so we take that as OK
+	  if (re.getRequestReturnCode() == org.rosuda.REngine.Rserve.protocol.RTalk.ERR_ctrl_closed)
+	      hasCtrl = false;
+	  else // anything else is a fail
+	      fail("serverEval failed with "+ re);
+      }
+
+      Assume.assumeTrue(hasCtrl);
+      
+      // Reconnect
+      connection.close();
+      engine = (REngine) (connection = new RConnection());
+      
+      final REXP rexp = connection.eval("xXx");
+      assertNotNull(rexp);
+      assertTrue(rexp.isString());
+      assertEquals(1, rexp.length());
+      assertEquals(key, rexp.asString());
+  }
+
+  @After
+  public void closeConnection() {
+      engine.close();
+  }
+    
+  @AfterClass
+  public static void tearDownRserve() {
+      try {
+	  // connect so we can control
+	  RConnection connection = new RConnection();
+
+	  // first use CTRL - it will fail in most cases (sinnce CTRL is likely not enabled)
+	  // but is the most reliable
+	  try {
+	      connection.serverShutdown();
+	  } catch (RserveException e1) { }
+	  // this will work on older Rserve versions, may not work on new ones
+	  try {
+	      connection.shutdown();
+	  } catch (RserveException e2) { }
+	  // finally, close the connection
+	  connection.close();
+      } catch (REngineException e3) { } // if this fails, that's ok - nothing to shutdown
+  }
+
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/test/Makefile b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/test/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..85df81f29cd8e196d457cab4ee5378627e558fe1
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/test/Makefile
@@ -0,0 +1,38 @@
+JAVA=java
+JAVAC=javac
+JFLAGS+=-encoding utf8 -source 1.6 -target 1.6
+
+all: test PlotDemo.class StartRserve.class
+
+../Rserve.jar: ../../REngine.jar
+	$(MAKE) -C .. Rserve.jar
+
+../../REngine.jar:
+	$(MAKE) -C ../.. REngine.jar
+
+test: test.class ../Rserve.jar ../../REngine.jar
+	$(JAVA) -cp ../Rserve.jar:../../REngine.jar:. test
+
+test.class: test.java ../Rserve.jar ../../REngine.jar
+	$(JAVAC) $(JFLAGS) -d . -cp ../Rserve.jar:../../REngine.jar:. test.java
+
+PlotDemo.class: PlotDemo.java ../Rserve.jar ../../REngine.jar
+	$(JAVAC) $(JFLAGS) -d . -cp ../Rserve.jar:../../REngine.jar:. $<
+
+PlotDemo: PlotDemo.class ../Rserve.jar ../../REngine.jar
+	$(JAVA) -cp ../Rserve.jar:../../REngine.jar:. $@
+
+jt: jt.class ../Rserve.jar ../../REngine.jar
+	$(JAVA) -cp ../Rserve.jar:../../REngine.jar:. $@
+
+jt.class: jt.java ../Rserve.jar ../../REngine.jar
+	$(JAVAC) $(JFLAGS) -d . -cp ../Rserve.jar:../../REngine.jar:. jt.java
+
+StartRserve.class: StartRserve.java ../Rserve.jar ../../REngine.jar
+	$(JAVAC) $(JFLAGS) -d . -cp ../Rserve.jar:../../REngine.jar:. StartRserve.java
+
+clean:
+	rm -rf org *~ *.class
+
+.PHONY: test all clean
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/test/PlotDemo.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/test/PlotDemo.java
new file mode 100644
index 0000000000000000000000000000000000000000..ffb5bd8716dbf6ed6297d03ddd9c1e17eea7f994
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/test/PlotDemo.java
@@ -0,0 +1,92 @@
+//
+// PlotDemo demo - REngine and graphics
+//
+// $Id$
+//
+
+import java.io.*;
+import java.util.*;
+import java.awt.*;
+import java.awt.event.*;
+
+import org.rosuda.REngine.*;
+import org.rosuda.REngine.Rserve.*;
+
+/** A demonstration of the use of Rserver and graphics devices to create graphics in R, pull them into Java and display them. It is a really simple demo. */
+public class PlotDemo extends Canvas {
+    public static void main(String args[]) {
+		try {
+			String device = "jpeg"; // device we'll call (this would work with pretty much any bitmap device)
+			
+			// connect to Rserve (if the user specified a server at the command line, use it, otherwise connect locally)
+			RConnection c = new RConnection((args.length>0)?args[0]:"127.0.0.1");
+
+			// if Cairo is installed, we can get much nicer graphics, so try to load it
+			if (c.parseAndEval("suppressWarnings(require('Cairo',quietly=TRUE))").asInteger()>0)
+				device="CairoJPEG"; // great, we can use Cairo device
+			else
+				System.out.println("(consider installing Cairo package for better bitmap output)");
+			
+            // we are careful here - not all R binaries support jpeg
+            // so we rather capture any failures
+            REXP xp = c.parseAndEval("try("+device+"('test.jpg',quality=90))");
+            
+            if (xp.inherits("try-error")) { // if the result is of the class try-error then there was a problem
+                System.err.println("Can't open "+device+" graphics device:\n"+xp.asString());
+                // this is analogous to 'warnings', but for us it's sufficient to get just the 1st warning
+                REXP w = c.eval("if (exists('last.warning') && length(last.warning)>0) names(last.warning)[1] else 0");
+                if (w.isString()) System.err.println(w.asString());
+                return;
+            }
+                 
+            // ok, so the device should be fine - let's plot - replace this by any plotting code you desire ...
+            c.parseAndEval("data(iris); attach(iris); plot(Sepal.Length, Petal.Length, col=unclass(Species)); dev.off()");
+            
+			// There is no I/O API in REngine because it's actually more efficient to use R for this
+			// we limit the file size to 1MB which should be sufficient and we delete the file as well
+			xp = c.parseAndEval("r=readBin('test.jpg','raw',1024*1024); unlink('test.jpg'); r");
+			
+            // now this is pretty boring AWT stuff - create an image from the data and display it ...
+            Image img = Toolkit.getDefaultToolkit().createImage(xp.asBytes());
+            
+            Frame f = new Frame("Test image");
+            f.add(new PlotDemo(img));
+            f.addWindowListener(new WindowAdapter() { // just so we can close the window
+                public void windowClosing(WindowEvent e) { System.exit(0); }
+            });
+            f.pack();
+            f.setVisible(true);
+
+			// close RConnection, we're done
+			c.close();
+        } catch (RserveException rse) { // RserveException (transport layer - e.g. Rserve is not running)
+            System.out.println(rse);
+        } catch (REXPMismatchException mme) { // REXP mismatch exception (we got something we didn't think we get)
+            System.out.println(mme);
+            mme.printStackTrace();
+        } catch(Exception e) { // something else
+            System.out.println("Something went wrong, but it's not the Rserve: "
+							   +e.getMessage());
+            e.printStackTrace();
+        }
+    }
+	
+    Image img;
+
+    public PlotDemo(Image img) {
+        this.img=img;
+        MediaTracker mediaTracker = new MediaTracker(this);
+        mediaTracker.addImage(img, 0);
+        try {
+            mediaTracker.waitForID(0);
+        } catch (InterruptedException ie) {
+            System.err.println(ie);
+            System.exit(1);
+        }
+        setSize(img.getWidth(null), img.getHeight(null));
+    }
+	
+    public void paint(Graphics g) {
+        g.drawImage(img, 0, 0, null);
+    }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/test/StartRserve.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/test/StartRserve.java
new file mode 100644
index 0000000000000000000000000000000000000000..253ae04f21f7bde8ebf2952e84e817e47b221b49
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/test/StartRserve.java
@@ -0,0 +1,154 @@
+import java.io.*;
+import java.util.*;
+import org.rosuda.REngine.Rserve.RConnection;
+
+/** helper class that consumes output of a process. In addition, it filter output of the REG command on Windows to look for InstallPath registry entry which specifies the location of R. */
+class StreamHog extends Thread {
+	InputStream is;
+	boolean capture;
+	String installPath;
+	StreamHog(InputStream is, boolean capture) {
+		this.is = is;
+		this.capture = capture;
+		start();
+	}
+	public String getInstallPath() {
+		return installPath;
+	}
+	public void run()
+	{
+		try {
+			BufferedReader br = new BufferedReader(new InputStreamReader(is));
+			String line = null;
+			while ( (line = br.readLine()) != null) {
+				if (capture) { // we are supposed to capture the output from REG command
+					int i = line.indexOf("InstallPath");
+					if (i >= 0) {
+						String s = line.substring(i + 11).trim();
+						int j = s.indexOf("REG_SZ");
+						if (j >= 0)
+							s = s.substring(j + 6).trim();
+						installPath = s;
+						System.out.println("R InstallPath = "+s);
+					}
+				} else 
+					System.out.println("Rserve>" + line);
+			}
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+	}
+}
+
+/** simple class that start Rserve locally if it's not running already - see mainly <code>checkLocalRserve</code> method. It spits out quite some debugging outout of the console, so feel free to modify it for your application if desired.<p>
+ <i>Important:</i> All applications should shutdown every Rserve that they started! Never leave Rserve running if you started it after your application quits since it may pose a security risk. Inform the user if you started an Rserve instance.
+ */
+public class StartRserve {
+	/** shortcut to <code>launchRserve(cmd, "--no-save --slave", "--no-save --slave", false)</code> */
+	public static boolean launchRserve(String cmd) { return launchRserve(cmd, "--no-save --slave","--no-save --slave",false); }
+	
+	/** attempt to start Rserve. Note: parameters are <b>not</b> quoted, so avoid using any quotes in arguments
+	 @param cmd command necessary to start R
+	 @param rargs arguments are are to be passed to R
+	 @param rsrvargs arguments to be passed to Rserve
+	 @return <code>true</code> if Rserve is running or was successfully started, <code>false</code> otherwise.
+	 */
+	public static boolean launchRserve(String cmd, String rargs, String rsrvargs, boolean debug) {
+		try {
+			Process p;
+			boolean isWindows = false;
+			String osname = System.getProperty("os.name");
+			if (osname != null && osname.length() >= 7 && osname.substring(0,7).equals("Windows")) {
+				isWindows = true; /* Windows startup */
+				p = Runtime.getRuntime().exec("\""+cmd+"\" -e \"library(Rserve);Rserve("+(debug?"TRUE":"FALSE")+",args='"+rsrvargs+"')\" "+rargs);
+			} else /* unix startup */
+				p = Runtime.getRuntime().exec(new String[] {
+							      "/bin/sh", "-c",
+							      "echo 'library(Rserve);Rserve("+(debug?"TRUE":"FALSE")+",args=\""+rsrvargs+"\")'|"+cmd+" "+rargs
+							      });
+			System.out.println("waiting for Rserve to start ... ("+p+")");
+			// we need to fetch the output - some platforms will die if you don't ...
+			StreamHog errorHog = new StreamHog(p.getErrorStream(), false);
+			StreamHog outputHog = new StreamHog(p.getInputStream(), false);
+			if (!isWindows) /* on Windows the process will never return, so we cannot wait */
+				p.waitFor();
+			System.out.println("call terminated, let us try to connect ...");
+		} catch (Exception x) {
+			System.out.println("failed to start Rserve process with "+x.getMessage());
+			return false;
+		}
+		int attempts = 5; /* try up to 5 times before giving up. We can be conservative here, because at this point the process execution itself was successful and the start up is usually asynchronous */
+		while (attempts > 0) {
+			try {
+				RConnection c = new RConnection();
+				System.out.println("Rserve is running.");
+				c.close();
+				return true;
+			} catch (Exception e2) {
+				System.out.println("Try failed with: "+e2.getMessage());
+			}
+			/* a safety sleep just in case the start up is delayed or asynchronous */
+			try { Thread.sleep(500); } catch (InterruptedException ix) { };
+			attempts--;
+		}
+		return false;
+	}
+
+	/** checks whether Rserve is running and if that's not the case it attempts to start it using the defaults for the platform where it is run on. This method is meant to be set-and-forget and cover most default setups. For special setups you may get more control over R with <<code>launchRserve</code> instead. */
+	public static boolean checkLocalRserve() {
+		if (isRserveRunning()) return true;
+		String osname = System.getProperty("os.name");
+		if (osname != null && osname.length() >= 7 && osname.substring(0,7).equals("Windows")) {
+			System.out.println("Windows: query registry to find where R is installed ...");
+			String installPath = null;
+			try {
+				Process rp = Runtime.getRuntime().exec("reg query HKLM\\Software\\R-core\\R");
+				StreamHog regHog = new StreamHog(rp.getInputStream(), true);
+				rp.waitFor();
+				regHog.join();
+				installPath = regHog.getInstallPath();
+			} catch (Exception rge) {
+				System.out.println("ERROR: unable to run REG to find the location of R: "+rge);
+				return false;
+			}
+			if (installPath == null) {
+				System.out.println("ERROR: canot find path to R. Make sure reg is available and R was installed with registry settings.");
+				return false;
+			}
+			return launchRserve(installPath+"\\bin\\R.exe");
+		}
+		return (launchRserve("R") || /* try some common unix locations of R */
+			((new File("/Library/Frameworks/R.framework/Resources/bin/R")).exists() && launchRserve("/Library/Frameworks/R.framework/Resources/bin/R")) ||
+			((new File("/usr/local/lib/R/bin/R")).exists() && launchRserve("/usr/local/lib/R/bin/R")) ||
+			((new File("/usr/lib/R/bin/R")).exists() && launchRserve("/usr/lib/R/bin/R")) ||
+			((new File("/usr/local/bin/R")).exists() && launchRserve("/usr/local/bin/R")) ||
+			((new File("/sw/bin/R")).exists() && launchRserve("/sw/bin/R")) ||
+			((new File("/usr/common/bin/R")).exists() && launchRserve("/usr/common/bin/R")) ||
+			((new File("/opt/bin/R")).exists() && launchRserve("/opt/bin/R"))
+			);
+	}
+	
+	/** check whether Rserve is currently running (on local machine and default port).
+	 @return <code>true</code> if local Rserve instance is running, <code>false</code> otherwise
+	 */
+	public static boolean isRserveRunning() {
+		try {
+			RConnection c = new RConnection();
+			System.out.println("Rserve is running.");
+			c.close();
+			return true;
+		} catch (Exception e) {
+			System.out.println("First connect try failed with: "+e.getMessage());
+		}
+		return false;
+	}
+	
+	/** just a demo main method which starts Rserve and shuts it down again */
+	public static void main(String[] args) {
+		System.out.println("result="+checkLocalRserve());
+		try {
+			RConnection c=new RConnection();
+			c.shutdown();
+		} catch (Exception x) {};
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/test/jt.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/test/jt.java
new file mode 100644
index 0000000000000000000000000000000000000000..4b02c02158511a0492e1119c76ce22a72bc32173
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/test/jt.java
@@ -0,0 +1,35 @@
+import java.io.*;
+import org.rosuda.REngine.*;
+import org.rosuda.REngine.Rserve.*;
+
+public class jt {
+    public static void main(String[] args) {
+		try {
+			RConnection c = new RConnection((args.length>0)?args[0]:"127.0.0.1");
+			
+			BufferedReader ir=new BufferedReader(new InputStreamReader(System.in));
+            String s=null;
+            System.out.print("> ");
+            while ((s=ir.readLine()).length() > 0) {
+				if (s.equals("shutdown")) {
+                    System.out.println("Sending shutdown request");
+                    c.shutdown();
+                    System.out.println("Shutdown successful. Quitting console.");
+                    return;
+                } else {
+					REXP rx = c.parseAndEval(s);
+					System.out.println("result(debug): "+rx.toDebugString());
+				}
+                System.out.print("> ");
+			}
+			
+		} catch (RserveException rse) {
+			System.out.println(rse);
+/*		} catch (REXPMismatchException mme) {
+			System.out.println(mme);
+			mme.printStackTrace(); */
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+    }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/test/test.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/test/test.java
new file mode 100644
index 0000000000000000000000000000000000000000..6c76e6f15dcfe1c25dcefdb4b409f46ff75749ff
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/Rserve/test/test.java
@@ -0,0 +1,285 @@
+import org.rosuda.REngine.*;
+import org.rosuda.REngine.Rserve.*;
+
+class TestException extends Exception {
+    public TestException(String msg) { super(msg); }
+}
+
+public class test {
+    public static void main(String[] args) {
+	try {
+	    RConnection c = new RConnection();
+	    // REngine is the backend-agnostic API -- using eng instead of c makes sure that we don't use Rserve extensions inadvertently
+	    REngine eng = (REngine) c;
+
+	    System.out.println(">>" + c.eval("R.version$version.string").asString() + "<<");
+
+		{
+			System.out.println("* Test string and list retrieval");
+			RList l = c.eval("{d=data.frame(\"huhu\",c(11:20)); lapply(d,as.character)}").asList();
+			int cols = l.size();
+			int rows = l.at(0).length();
+			String[][] s = new String[cols][];
+			for (int i=0; i<cols; i++) s[i]=l.at(i).asStrings();
+			System.out.println("PASSED");
+		}
+		
+	    {
+		System.out.println("* Test NA/NaN support in double vectors...");
+		double R_NA = REXPDouble.NA;
+		double x[] = { 1.0, 0.5, R_NA, Double.NaN, 3.5 };
+		c.assign("x",x);
+		String nas = c.eval("paste(capture.output(print(x)),collapse='\\n')").asString();
+		System.out.println(nas);
+		if (!nas.equals("[1] 1.0 0.5  NA NaN 3.5"))
+		    throw new TestException("NA/NaN assign+retrieve test failed");
+		REXP rx = c.eval("c(2.2, NA_real_, NaN)");
+		if (rx == null || !rx.isNumeric() || rx.isInteger())
+		    throw new TestException("NA/NaN pull test failed (invalid result)");
+		boolean nal[] = rx.isNA();
+		if (nal.length != 3 || nal[0] || !nal[1] || nal[2])
+		    throw new TestException("NS/NAN pull test: NA pull failed");
+		x = rx.asDoubles();
+		if (x.length != 3 || !Double.isNaN(x[2]) || REXPDouble.isNA(x[2]) || !REXPDouble.isNA(x[1]))
+		    throw new TestException("NS/NAN pull test: NA/NaN pull failed");		    
+		System.out.println("PASSED");
+	    }
+		
+	    {
+			System.out.println("* Test assigning of lists and vectors ...");
+			RList l = new RList();
+			l.put("a",new REXPInteger(new int[] { 0,1,2,3}));
+			l.put("b",new REXPDouble(new double[] { 0.5,1.2,2.3,3.0}));
+			System.out.println("  assign x=pairlist");
+			c.assign("x", new REXPList(l));
+			System.out.println("  assign y=vector");
+			c.assign("y", new REXPGenericVector(l));
+			System.out.println("  assign z=data.frame");
+			c.assign("z", REXP.createDataFrame(l));
+			System.out.println("  pull all three back to Java");
+			REXP x = c.parseAndEval("x");
+			System.out.println("  x = "+x);
+			x = c.eval("y");
+			System.out.println("  y = "+x);
+			x = c.eval("z");
+			System.out.println("  z = "+x);
+			System.out.println("PASSED");
+	    }
+		{
+			System.out.println("* Test support for logicals ... ");
+			System.out.println("  assign b={true,false,true}");
+			c.assign("b", new REXPLogical(new boolean[] { true, false, true }));
+			REXP x = c.parseAndEval("b");
+			System.out.println("  " + ((x != null) ? x.toDebugString() : "NULL"));
+			if (!x.isLogical() || x.length() != 3)
+				throw new TestException("boolean array assign+retrieve test failed");
+			boolean q[] = ((REXPLogical)x).isTRUE();
+			if (q[0] != true || q[1] != false || q[2] != true)
+				throw new TestException("boolean array assign+retrieve test failed (value mismatch)");
+			System.out.println("  get c(TRUE,FLASE,NA)");
+			x = c.parseAndEval("c(TRUE,FALSE,NA)");
+			System.out.println("  " + ((x != null) ? x.toDebugString() : "NULL"));
+			if (!x.isLogical() || x.length() != 3)
+				throw new TestException("boolean array NA test failed");
+			boolean q1[] = ((REXPLogical)x).isTRUE();
+			boolean q2[] = ((REXPLogical)x).isFALSE();
+			boolean q3[] = ((REXPLogical)x).isNA();
+			if (q1[0] != true || q1[1] != false || q1[2] != false ||
+				q2[0] != false || q2[1] != true || q2[2] != false ||
+				q3[0] != false || q3[1] != false || q3[2] != true)
+				throw new TestException("boolean array NA test failed (value mismatch)");
+		}
+
+		{ // regression: object bit was not set for Java-side generated objects before 0.5-3
+			System.out.println("* Testing functionality of assembled S3 objects ...");
+			// we have already assigned the data.frame in previous test, so we jsut re-use it
+			REXP x = c.parseAndEval("z[2,2]");
+			System.out.println("  z[2,2] = " + x);
+			if (x == null || x.length() != 1 || x.asDouble() != 1.2)
+				throw new TestException("S3 object bit regression test failed");
+			System.out.println("PASSED");
+		}
+		
+		{ // this test does a pull and push of a data frame. It will fail when the S3 test above failed.
+			System.out.println("* Testing pass-though capability for data.frames ...");
+			REXP df = c.parseAndEval("{data(iris); iris}");
+			c.assign("df", df);
+			REXP x = c.eval("identical(df, iris)");
+			System.out.println("  identical(df, iris) = "+x);
+			if (x == null || !x.isLogical() || x.length() != 1 || !((REXPLogical)x).isTrue()[0])
+				throw new TestException("Pass-through test for a data.frame failed");
+			System.out.println("PASSED");
+		}
+		
+            { // factors
+                System.out.println("* Test support of factors");
+                REXP f = c.parseAndEval("factor(paste('F',as.integer(runif(20)*5),sep=''))");
+				System.out.println("  f="+f);
+                System.out.println("  isFactor: "+f.isFactor()+", asFactor: "+f.asFactor());
+                if (!f.isFactor() || f.asFactor() == null) throw new TestException("factor test failed");
+                System.out.println("  singe-level factor used to degenerate:");
+                f = c.parseAndEval("factor('foo')");
+                System.out.println("  isFactor: "+f.isFactor()+", asFactor: "+f.asFactor());
+                if (!f.isFactor() || f.asFactor() == null) throw new TestException("single factor test failed (not a factor)");
+				if (!f.asFactor().at(0).equals("foo")) throw new TestException("single factor test failed (wrong value)");
+                System.out.println("  test factors with null elements contents:");
+				c.assign("f", new REXPFactor(new RFactor(new String[] { "foo", "bar", "foo", "foo", null, "bar" })));
+				f = c.parseAndEval("f");
+                if (!f.isFactor() || f.asFactor() == null) throw new TestException("factor assign-eval test failed (not a factor)");
+				System.out.println("  f = "+f.asFactor());
+				f = c.parseAndEval("as.factor(c(1,'a','b',1,'b'))");
+				System.out.println("  f = "+f);
+                if (!f.isFactor() || f.asFactor() == null) throw new TestException("factor test failed (not a factor)");
+				System.out.println("PASSED");
+            }
+
+
+	    {
+			System.out.println("* Lowess test");
+			double x[] = c.eval("rnorm(100)").asDoubles();
+			double y[] = c.eval("rnorm(100)").asDoubles();
+			c.assign("x", x);
+			c.assign("y", y);
+			RList l = c.parseAndEval("lowess(x,y)").asList();
+			System.out.println("  "+l);
+			x = l.at("x").asDoubles();
+			y = l.at("y").asDoubles();
+			System.out.println("PASSED");
+		}
+
+	    {
+			// multi-line expressions
+			System.out.println("* Test multi-line expressions");
+			if (c.eval("{ a=1:10\nb=11:20\nmean(b-a) }\n").asInteger()!=10)
+				throw new TestException("multi-line test failed.");
+			System.out.println("PASSED");
+	    }
+		{
+		    System.out.println("* Matrix tests\n  matrix: create a matrix");
+		    int m = 100, n = 100;
+		    double[] mat=new double[m * n];
+		    { int i=0; while (i < m * n) mat[i++] = i / 100; }
+		    System.out.println("  matrix: assign/retrieve a matrix");
+		    c.assign("m", mat);
+		    c.voidEval("m<-matrix(m,"+m+","+n+")");
+		    System.out.println("  matrix: use createDoubleMatrix");
+		    double[][] A = new double[m][n];
+		    for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) A[i][j] = mat[i + j * m];
+		    c.assign("m2", REXP.createDoubleMatrix(A));
+		    if (c.eval("identical(m ,m2)").asInteger() != 1)
+			throw new TestException("matrix test failed: createDoubleMatrix result is not the same as direct assign");
+		    System.out.println("matrix: cross-product");
+		    double[][] mr = c.parseAndEval("crossprod(m,m)").asDoubleMatrix();
+		    System.out.println("PASSED");
+		}
+		
+		{
+			System.out.println("* Test serialization and raw vectors");
+			byte[] b = c.eval("serialize(ls, NULL, ascii=FALSE)").asBytes();
+			System.out.println("  serialized ls is "+b.length+" bytes long");
+			c.assign("r", new REXPRaw(b));
+			String[] s = c.eval("unserialize(r)()").asStrings();
+			System.out.println("  we have "+s.length+" items in the workspace");
+			System.out.println("PASSED");
+		}
+		
+		{ /* NAs in character vectors are mapped to null references in String[] and vice versa. Only Rserve 0.6-2 and later support NAa in character vectors. */
+		  /* repression test: assigning empty string '' has failed in previous versions of RserveEngine */
+			System.out.println("* Test handling of NAs in character vectors ('foo', '', NA, 'NA')");
+			System.out.print("  push String[] with NAs: ");
+			eng.assign("s", new String[] { "foo", "", null, "NA" });
+			int nas[] = eng.parseAndEval("is.na(s)").asIntegers();
+			for (int i = 0; i < nas.length; i++) System.out.print(nas[i] + " ");
+			if (nas.length != 4 || nas[0] != REXPLogical.FALSE || nas[1] != REXPLogical.FALSE || nas[2] != REXPLogical.TRUE || nas[3] != REXPLogical.FALSE)
+				throw new TestException("assigning null Strings as NAs and '' has failed");
+			System.out.println(" - OK");
+			System.out.print("  pull String[] with NAs: ");
+			String s[] = eng.parseAndEval("c('foo', '', NA, 'NA')").asStrings();
+			for (int i = 0; i < s.length; i++) System.out.print("'" + s[i] + "' ");
+			if (s.length != 4 || s[0] == null || s[1] == null || !s[1].equals("") || s[2] != null || s[3] == null)
+				throw new TestException("pulling Strings containin NAs and '' has failed");
+			System.out.println(" - OK");
+			System.out.print("  compare pushed and constructed strings: ");
+			if (eng.parseAndEval("identical(s, c('foo', '', NA, 'NA'))").asInteger() != REXPLogical.TRUE)
+				throw new TestException("comparing Strings with NAs and '' has failed");
+			System.out.println(" - OK");
+			System.out.print("  check isNA() for REXPString:");
+			boolean na[] = eng.parseAndEval("s").isNA();
+			for (int i = 0; i < na.length; i++) System.out.print(" " + na[i]);
+			if (na.length != 4 || na[0] || na[1] || !na[2] || na[3])
+				throw new TestException("isNA() test failed");
+			System.out.println(" - OK");
+			System.out.println("PASSED");
+		}
+		
+		{ // string encoding test (will work with Rserve 0.5-3 and higher only)
+			System.out.println("* Test string encoding support ...");
+			String t = "ひらがな"; // hiragana (literally, in hiragana ;))
+			c.setStringEncoding("utf8");
+			// -- Just in case the console is not UTF-8 don't display it
+			//System.out.println("  unicode text: "+t);
+			c.assign("s", t);
+			REXP x = c.parseAndEval("nchar(s)");
+			System.out.println("  nchar = " + x);
+			if (x == null || !x.isInteger() || x.asInteger() != 4)
+				throw new TestException("UTF-8 encoding string length test failed");
+			// we cannot really test any other encoding ..
+			System.out.println("PASSED");
+		}
+
+		{ // test QAP evals
+			System.out.println("* Test eval without parse (direct calls) ...");
+			System.out.println("  call 1L + 2 as a language construct");
+			REXP x = c.eval(REXP.asCall("+",
+						    new REXPInteger(1),
+						    new REXPDouble(2)), null, true);
+			if (x == null || !x.isNumeric() || x.asDouble() != 3)
+				throw new TestException("evaluating 1L + 2 as a call failed");
+			System.out.println("  call a compound statement and exported symbol");
+			x = c.eval(REXP.asCall("{", new REXP[] {
+						// X <- local vector 1,2,3,4
+						REXP.asCall("<-", new REXPSymbol("X"), new REXPInteger(new int[] { 1, 2, 3, 4 })),
+						// base::length(X)  # convoluted for the sake of testing exported symbols
+						REXP.asCall(REXP.asCall("::", new REXPSymbol("base"), new REXPSymbol("length")),
+							    new REXPSymbol("X"))
+					}), null, true);
+			if (x == null || !x.isInteger() || x.asInteger() != 4)
+				throw new TestException("calling a compound statement failed");
+			// since we did an assignment we mauy as well test the get() method
+			System.out.println("  get from global env");
+			x = c.get("X", null, true);
+			if (x == null || !x.isInteger() || x.length() != 4)
+				throw new TestException("retrieving value created by assignment expression call failed");
+			System.out.println("PASSED");
+		}
+		
+		{ // test control commands (works only when enabled and in Rserve 0.6-0 and higher only) - must be the last test since it closes the connection and shuts down the server
+			System.out.println("* Test control commands (this will fail if control commands are disabled) ...");
+			System.out.println("  server eval");
+			String key = "rn" + Math.random(); // generate a random number to prevent contamination from previous tests
+			c.serverEval("xXx<-'" + key + "'");
+			c.close();
+			c = new RConnection();
+			REXP x = c.eval("xXx");
+			if (x == null || !x.isString() || x.length() != 1 || !x.asString().equals(key))
+				throw new TestException("control eval test failed - assignment was not persistent");
+			c.serverEval("rm(xXx)"); // remove the test variable to not pollute the global workspace
+			System.out.println("  server shutdown");
+			c.serverShutdown();
+			c.close();
+			System.out.println("PASSED");
+		}
+	    
+		} catch (RserveException rse) {
+	    System.out.println(rse);
+	} catch (REXPMismatchException mme) {
+	    System.out.println(mme);
+	    mme.printStackTrace();
+        } catch(TestException te) {
+            System.err.println("** Test failed: "+te.getMessage());
+            te.printStackTrace();
+	} catch (Exception e) {
+	    e.printStackTrace();
+	}
+    }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/mkmvn.sh b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/mkmvn.sh
new file mode 100755
index 0000000000000000000000000000000000000000..9d0e4ed025bcddf62c6c760d5b5949a4c0738089
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/mkmvn.sh
@@ -0,0 +1,8 @@
+#!/bin/sh
+
+BASE="$1"
+if [ -z "$BASE" ]; then BASE="`pwd`"; fi
+
+rm -rf "$BASE/src/main"
+mkdir -p "$BASE/src/main/java/org/rosuda/REngine"
+(cd "$BASE/src/main/java/org/rosuda/REngine" && ln -s ../../../../../../*.java .)
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/package-info.java b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/package-info.java
new file mode 100644
index 0000000000000000000000000000000000000000..66c145c42508a452a889b2324edf2af8b174f8ef
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/package-info.java
@@ -0,0 +1,5 @@
+/**
+ * High level java interface to R
+ */
+package org.rosuda.REngine ;
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/REngine/pom.xml b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/pom.xml
new file mode 100644
index 0000000000000000000000000000000000000000..21da783df5335468a0dfb4d37a314545403baebc
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/REngine/pom.xml
@@ -0,0 +1,137 @@
+<?xml version="1.0"?>
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+  <modelVersion>4.0.0</modelVersion>
+  
+  <groupId>org.rosuda.REngine</groupId>
+  <artifactId>REngine</artifactId>
+  <name>REngine Java interface to R</name>
+  <description>REngine API to access R from Java in a backend-independent way.</description>
+  <version>2.1.1-SNAPSHOT</version>
+
+  <url>http://github.com/s-u/REngine</url>
+
+  <properties>
+    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+  </properties>
+
+  <licenses>
+    <license>
+      <name>LGPL v2.1</name>
+      <url>https://www.gnu.org/licenses/lgpl-2.1.txt</url>
+    </license>
+  </licenses>
+
+  <developers>
+    <developer>
+      <name>Simon Urbanek</name>
+      <email>simon.urbanek@R-project.org</email>
+    </developer>
+  </developers>
+
+  <scm>
+    <connection>scm:git:https://github.com/s-u/REngine.git</connection>
+    <developerConnection>scm:git:git@github.com:s-u/REngine.git</developerConnection>
+    <url>https://github.com/s-u/REngine</url>
+  </scm>
+
+  <dependencies>
+    <dependency>
+      <groupId>junit</groupId>
+      <artifactId>junit</artifactId>
+      <version>3.8.1</version>
+      <scope>test</scope>
+    </dependency>
+  </dependencies>
+
+  <build>
+    <plugins>
+      <plugin>
+	<artifactId>exec-maven-plugin</artifactId>
+	<groupId>org.codehaus.mojo</groupId>
+	<version>1.3.2</version>
+	<executions>
+	  <execution>
+	    <id>create mvn structure</id>
+	    <phase>generate-sources</phase>
+	    <goals>
+              <goal>exec</goal>
+	    </goals>
+	    <configuration>
+              <executable>${basedir}/mkmvn.sh</executable>
+	    </configuration>
+	  </execution>
+	</executions>
+      </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-compiler-plugin</artifactId>
+        <version>3.2</version>
+        <configuration>
+          <source>1.4</source>
+          <target>1.4</target>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
+
+  <profiles>
+    <profile>
+      <id>release</id>
+      <build>
+        <plugins>
+	  <plugin>
+	    <groupId>org.apache.maven.plugins</groupId>
+	    <artifactId>maven-gpg-plugin</artifactId>
+	    <version>1.6</version>
+	    <executions>
+              <execution>
+		<id>sign-artifacts</id>
+		<phase>verify</phase>
+		<goals>
+		  <goal>sign</goal>
+		</goals>
+              </execution>
+	    </executions>
+	  </plugin>
+	  <plugin>
+            <groupId>org.apache.maven.plugins</groupId>
+            <artifactId>maven-javadoc-plugin</artifactId>
+            <version>2.10.2</version>
+	    <executions>
+	      <execution>
+		<id>attach-javadocs</id>
+		<goals>
+		  <goal>jar</goal>
+		</goals>
+	      </execution>
+	    </executions>
+	  </plugin>
+	  <plugin>
+	    <groupId>org.apache.maven.plugins</groupId>
+	    <artifactId>maven-source-plugin</artifactId>
+	    <version>2.4</version>
+	    <executions>
+	      <execution>
+		<id>attach-sources</id>
+		<goals>
+		  <goal>jar-no-fork</goal>
+		</goals>
+	      </execution>
+	    </executions>
+	  </plugin>
+        </plugins>
+      </build>
+    </profile>
+  </profiles>
+  
+  <distributionManagement>
+    <snapshotRepository>
+      <id>ossrh</id>
+      <url>https://oss.sonatype.org/content/repositories/snapshots</url>
+    </snapshotRepository>
+    <repository>
+      <id>ossrh</id>
+      <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
+    </repository>
+  </distributionManagement>
+</project>
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/RFactor.java b/com.oracle.truffle.r.pkgs/rJava/jri/RFactor.java
new file mode 100644
index 0000000000000000000000000000000000000000..a217f8ad425e570d5ed3120473f838e107e42da4
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/RFactor.java
@@ -0,0 +1,96 @@
+package org.rosuda.JRI;
+
+// JRclient library - client interface to Rserve, see http://www.rosuda.org/Rserve/
+// Copyright (C) 2004 Simon Urbanek
+// --- for licensing information see LICENSE file in the original JRclient distribution ---
+
+import java.util.*;
+
+/** representation of a factor variable. In R there is no actual xpression
+    type called "factor", instead it is coded as an int vector with a list
+    attribute. The parser code of REXP converts such constructs directly into
+    the RFactor objects and defines an own XT_FACTOR type 
+    
+    @version $Id: RFactor.java 2909 2008-07-15 15:06:49Z urbanek $
+*/    
+public class RFactor extends Object {
+    /** IDs (content: Integer) each entry corresponds to a case, ID specifies the category */
+    Vector id;
+    /** values (content: String), ergo category names */
+    Vector val;
+
+    /** create a new, empty factor var */
+    public RFactor() { id=new Vector(); val=new Vector(); }
+    
+    /** create a new factor variable, based on the supplied arrays.
+		@param i array of IDs (0..v.length-1)
+		@param v values - category names */		
+    public RFactor(int[] i, String[] v) {
+		this(i, v, 0);
+	}
+
+    /** create a new factor variable, based on the supplied arrays.
+		@param i array of IDs (base .. v.length-1+base)
+		@param v values - cotegory names
+		@param base of the indexing
+		*/
+    RFactor(int[] i, String[] v, int base) {
+		id=new Vector(); val=new Vector();
+		int j;
+		if (i!=null && i.length>0)
+			for(j=0;j<i.length;j++)
+				id.addElement(new Integer(i[j]-base));
+		if (v!=null && v.length>0)
+			for(j=0;j<v.length;j++)
+				val.addElement(v[j]);
+    }
+   
+    /** add a new element (by name)
+	@param v value */
+    public void add(String v) {
+	int i=val.indexOf(v);
+	if (i<0) {
+	    i=val.size();
+	    val.addElement(v);
+	};
+	id.addElement(new Integer(i));
+    }
+
+    /** returns name for a specific ID 
+	@param i ID
+	@return name. may throw exception if out of range */
+    public String at(int i) {
+	if (i < 0 || i >= id.size()) return null;
+	int j = ((Integer)id.elementAt(i)).intValue();
+	/* due to the index shift NA (INT_MIN) will turn into INT_MAX if base is 1 */
+	return (j < 0 || j > 2147483640) ? null : ((String)val.elementAt(j));
+    }
+
+    /** returns the number of caes */
+    public int size() { return id.size(); }
+
+    /** displayable representation of the factor variable */
+    public String toString() {
+	//return "{"+((val==null)?"<null>;":("levels="+val.size()+";"))+((id==null)?"<null>":("cases="+id.size()))+"}";
+	StringBuffer sb=new StringBuffer("{levels=(");
+	if (val==null)
+	    sb.append("null");
+	else
+	    for (int i=0;i<val.size();i++) {
+		sb.append((i>0)?",\"":"\"");
+		sb.append((String)val.elementAt(i));
+		sb.append("\"");
+	    };
+	sb.append("),ids=(");
+	if (id==null)
+	    sb.append("null");
+	else
+	    for (int i=0;i<id.size();i++) {
+		if (i>0) sb.append(",");
+		sb.append((Integer)id.elementAt(i));
+	    };
+	sb.append(")}");
+	return sb.toString();
+    }
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/RList.java b/com.oracle.truffle.r.pkgs/rJava/jri/RList.java
new file mode 100644
index 0000000000000000000000000000000000000000..b35d6c45c06e2d5ee4d46a29e9c8a7ffd1dad491
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/RList.java
@@ -0,0 +1,130 @@
+package org.rosuda.JRI;
+
+// JRclient library - client interface to Rserve, see http://www.rosuda.org/Rserve/
+// Copyright (C) 2004 Simon Urbanek
+// --- for licensing information see LICENSE file in the original JRclient distribution ---
+
+import java.util.*;
+
+/** implementation of R-lists<br>
+    This is rather preliminary and may change in future since it's not really proper.
+    The point is that the parser tries to interpret lists to be of the form entry=value,
+    where entry is stored in the "head" part, and value is stored in the "body" part.
+    Then using {@link #at(String)} it is possible to fetch "body" for a specific "head".
+    The terminology used is partly from hash fields - "keys" are the elements in "head"
+    and values are in "body" (see {@link #keys}).
+    <p>
+    On the other hand, R uses lists to store complex internal structures, which are not
+    parsed according to the structure - in that case "head" and "body" have to be evaluated
+    separately according to their meaning in that context.
+
+    @version $Id: RList.java 2720 2007-03-15 17:35:42Z urbanek $
+*/
+public class RList extends Object {
+    /** xpressions containing head, body and tag. 
+	The terminology is a bit misleading (for historical reasons) - head corresponds to CAR, body to CDR and finally tag is TAG. */
+    public REXP head, body, tag;
+
+	/** cached keys (from TAG) */
+    String[] keys = null;
+	/** cached values(from CAR) */
+	REXP[] values = null;
+	/** flag denoting whether we need to re-fetch the cached values.<p><b.Note:</b> the current assumption is that the contents don't change after first retrieval - there is currently no recursive check! */
+	boolean dirtyCache = true;
+	
+    /** constructs an empty list */
+    public RList() { head=body=tag=null; }
+    
+	/** fake constructor to keep compatibility with Rserve (for now, will be gone soon) */
+	public RList(RVector v) {
+		Vector n = v.getNames();
+		if (n != null) {
+			keys = new String[n.size()];
+			n.copyInto(keys);
+		}
+		values=new REXP[v.size()];
+		v.copyInto(values);
+		dirtyCache=false;
+		// head,tail,tag are all invalid!
+	}	
+
+    /** constructs an initialized list
+	@param h head xpression
+	@param b body xpression */
+    public RList(REXP h, REXP b) { head=h; body=b; tag=null; }
+
+	/** constructs an initialized list
+		@param h head xpression (CAR)
+		@param t tag xpression (TAG)
+		@param b body/tail xpression (CDR)
+		*/
+    public RList(REXP h, REXP t, REXP b) { head=h; body=b; tag=t; }
+	
+    /** get head xpression (CAR)
+	@return head xpression */
+    public REXP getHead() { return head; }
+    
+    /** get body xpression (CDR)
+	@return body xpression */
+    public REXP getBody() { return body; }
+
+    /** get tag xpression
+	@return tag xpression */
+    public REXP getTag() { return tag; }
+
+    /** internal function that updates cached vectors
+        @return <code>true</code> if the conversion was successful */
+    boolean updateVec() {
+		if (!dirtyCache) return true;
+		// we do NOT run it recursively, because in most cases only once instance is asked
+		RList cur = this;
+		int l = 0;
+		while (cur!=null) {
+			l++;
+			REXP bd = cur.getBody();
+			cur = (bd==null)?null:bd.asList();
+		}
+		keys=new String[l];
+		values=new REXP[l];
+		cur = this;
+		l=0;
+		while (cur != null) {
+			REXP x = cur.getTag();
+			if (x!=null) keys[l]=x.asSymbolName();
+			values[l] = cur.getHead();
+			REXP bd = cur.getBody();
+			cur = (bd==null)?null:bd.asList();
+			l++;
+		}
+		dirtyCache=false;
+		return true;
+    }
+
+    /** get xpression given a key
+		@param v key
+		@return xpression which corresponds to the given key or
+		<code>null</code> if list is not standartized or key not found */
+    public REXP at(String v) {
+		if (!updateVec() || keys==null || values==null) return null;
+		int i=0;
+		while (i<keys.length) {
+			if (keys[i].compareTo(v)==0) return values[i];
+			i++;
+		}
+		return null;
+    }
+
+    /** get element at the specified position
+	@param i index
+	@return xpression at the index or <code>null</code> if list is not standartized or
+	        if index out of bounds */
+    public REXP at(int i) {
+		return (!updateVec() || values==null || i<0 || i>=values.length)?null:values[i];
+    }
+
+    /** returns all keys of the list
+	@return array containing all keys or <code>null</code> if list is not standartized */
+    public String[] keys() {
+		return (!updateVec())?null:this.keys;
+    }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/RMainLoopCallbacks.java b/com.oracle.truffle.r.pkgs/rJava/jri/RMainLoopCallbacks.java
new file mode 100644
index 0000000000000000000000000000000000000000..ad4427c348380d6b0165d32bec403d3392c6b176
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/RMainLoopCallbacks.java
@@ -0,0 +1,41 @@
+package org.rosuda.JRI;
+
+/** Interface which must be implmented by any class that wants to pose as the call-back handler for R event loop callbacks. It is legal to return immediately except when user interaction is required: {@link #rReadConsole} and {@link #rChooseFile} are expected to block until the user performs the desired action. */
+public interface RMainLoopCallbacks {
+    /** called when R prints output to the console
+	@param re calling engine
+	@param text text to display in the console
+	@param oType output type (0=regular, 1=error/warning)
+    */
+    public void   rWriteConsole (Rengine re, String text, int oType);
+    /** called when R enters or exits a longer evaluation. It is usually a good idea to signal this state to the user, e.g. by changing the cursor to a "hourglass" and back.
+	@param re calling engine
+	@param which identifies whether R enters (1) or exits (0) the busy state */
+    public void   rBusy         (Rengine re, int which);
+    /** called when R waits for user input. During the duration of this callback it is safe to re-enter R, and very often it is also the only time. The implementation is free to block on this call until the user hits Enter, but in JRI it is a good idea to call {@link Rengine.rniIdle()} occasionally to allow other event handlers (e.g graphics device UIs) to run. Implementations should NEVER return immediately even if there is no input - such behavior will result in a fast cycling event loop which makes the use of R pretty much impossible.
+	@param re calling engine
+	@param prompt prompt to be displayed at the console prior to user's input
+	@param addToHistory flag telling the handler whether the input should be considered for adding to history (!=0) or not (0)
+	@return user's input to be passed to R for evaluation */
+    public String rReadConsole  (Rengine re, String prompt, int addToHistory);
+    /** called when R want to show a warning/error message (not to be confused with messages displayed in the console output)
+	@param re calling engine
+	@param message message to display */
+    public void   rShowMessage  (Rengine re, String message);
+    /** called when R expects the user to choose a file
+	@param re calling engine
+	@param newFile flag determining whether an existing or new file is to be selecteed
+	@return path/name of the selected file */
+    public String rChooseFile   (Rengine re, int newFile);
+    /** called when R requests the console to flush any buffered output
+	@param re calling engine */	
+    public void   rFlushConsole (Rengine re);
+    /** called to save the contents of the history (the implementation is responsible of keeping track of the history)
+	@param re calling engine
+	@param filename name of the history file */
+    public void   rSaveHistory  (Rengine re, String filename);
+    /** called to load the contents of the history
+	@param re calling engine
+	@param filename name of the history file */
+    public void   rLoadHistory  (Rengine re, String filename);
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/RVector.java b/com.oracle.truffle.r.pkgs/rJava/jri/RVector.java
new file mode 100644
index 0000000000000000000000000000000000000000..93092951062629f00736ed0d61f27fa65e9df702
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/RVector.java
@@ -0,0 +1,48 @@
+package org.rosuda.JRI;
+
+import java.util.Vector;
+import java.util.Enumeration;
+
+/** class encapsulating named generic vectors in R - do NOT use add/remove directly as names are not synchronized with the contents. The reason for this implementation is for historical compatibility and it may change in the future.
+<p>
+It is now used in <code>REXP</code> where <code>Vector</code> type was used previously for contents storage.
+@since JRI 0.3
+*/
+public class RVector extends java.util.Vector {
+	Vector names = null;
+	public RVector() { super(); }
+	
+	/** replace the names vector - do NOT use directly!
+		@param nam list of names */
+	public void setNames(String[] nam) {
+		names=new Vector(nam.length);
+		int i=0;
+		while (i<nam.length)
+			names.addElement(nam[i++]);
+	}
+	
+	/** return the vector containg all names
+		@return vector containing all names */
+	public Vector getNames() {
+		return names;
+	}
+
+	/** return contents by name or <code>null</code> if not found
+		@param name key (name)
+		@return contents or <code>null</code> if not found
+		*/
+	public REXP at(String name) {
+		if (names==null) return null;
+		int i=0;
+		for (Enumeration e = names.elements() ; e.hasMoreElements() ;) {
+			String n = (String)e.nextElement();
+			if (n.equals(name)) return (REXP) elementAt(i);
+			i++;
+		}
+		return null;
+	}
+	
+	public REXP at(int i) {
+		return (REXP)elementAt(i);
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/Rengine.java b/com.oracle.truffle.r.pkgs/rJava/jri/Rengine.java
new file mode 100644
index 0000000000000000000000000000000000000000..a84613221ff59bac7ca0fd65be524c174e04a34e
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/Rengine.java
@@ -0,0 +1,790 @@
+package org.rosuda.JRI;
+
+import java.lang.*;
+
+/** Rengine class is the interface between an instance of R and the Java VM. Due to the fact that R has no threading support, you can run only one instance of R withing a multi-threaded application. There are two ways to use R from Java: individual call and full event loop. See the Rengine {@link #Rengine constructor} for details. <p> <u>Important note:</u> All methods starting with <code>rni</code> (R Native Interface) are low-level native methods that should be avoided if a high-level methods exists. They do NOT attempt any synchronization, so it is the duty of the calling program to ensure that the invocation is safe (see {@link #getRsync()} for details). At some point in the future when the high-level API is complete they should become private. However, currently this high-level layer is not complete, so they are available for now.<p>All <code>rni</code> methods use <code>long</code> type to reference <code>SEXP</code>s on R side. Those reference should never be modified or used in arithmetics - the only reason for not using an extra interface class to wrap those references is that <code>rni</code> methods are all <i>native</i> methods and therefore it would be too expensive to handle the unwrapping on the C side.<p><code>jri</code> methods are called internally by R and invoke the corresponding method from the even loop handler. Those methods should usualy not be called directly.
+
+ <p>Since 0.5 a failure to load the JRI naitve library will not be fatal if <code>jri.ignore.ule=yes</code> system preference is set. Rengine will still not work, but that gives a chance to GUI programs to report the error in a more meaningful way (use {@link #jriLoaded} to check the availability of JRI). 
+ */
+public class Rengine extends Thread {
+	/** this flags is set to <code>true</code> if the native code was successfully loaded. If this flag is <code>false</code> then none of the rni methods are available. Previous 
+	 @since API 1.9, JRI 0.5
+	 */
+	public static boolean jriLoaded;
+
+    boolean loopHasLock = false;
+    
+    static {
+        try {
+            System.loadLibrary("jri");
+			jriLoaded = true;
+        } catch (UnsatisfiedLinkError e) {
+			jriLoaded = false; // should be implicit, but well ...
+			String iu = System.getProperty("jri.ignore.ule");
+			if (iu == null || !iu.equals("yes")) {
+				System.err.println("Cannot find JRI native library!\nPlease make sure that the JRI native library is in a directory listed in java.library.path.\n");
+				e.printStackTrace();
+				System.exit(1);
+			}
+        }
+    }
+
+    static Thread mainRThread = null;
+
+	// constrants to be used with rniSpecialObject
+	/** constant to be used in {@link #rniSpecialObject} to return <code>R_NilValue</code> reference */
+	public static final int SO_NilValue     = 0;
+	/** constant to be used in {@link #rniSpecialObject} to return <code>R_GlobalEnv</code> reference */
+	public static final int SO_GlobalEnv    = 1;
+	/** constant to be used in {@link #rniSpecialObject} to return <code>R_EmptyEnv</code> reference */
+	public static final int SO_EmptyEnv     = 2;
+	/** constant to be used in {@link #rniSpecialObject} to return <code>R_baseEnv</code> reference */
+	public static final int SO_BaseEnv      = 3;
+	/** constant to be used in {@link #rniSpecialObject} to return <code>R_UnboundValue</code> reference */
+	public static final int SO_UnboundValue = 4;
+	/** constant to be used in {@link #rniSpecialObject} to return <code>R_MissingArg</code> reference */
+	public static final int SO_MissingArg   = 5;
+	/** constant to be used in {@link #rniSpecialObject} to return <code>R_NaString</code> reference */
+	public static final int SO_NaString     = 6;
+	/** constant to be used in {@link #rniSpecialObject} to return <code>R_BlankString</code> reference */
+	public static final int SO_BlankString  = 7;
+
+	/**	API version of the Rengine itself; see also rniGetVersion() for binary version. It's a good idea for the calling program to check the versions of both and abort if they don't match. This should be done using {@link #versionCheck}
+		@return version number as <code>long</code> in the form <code>0xMMmm</code> */
+    public static long getVersion() {
+        return 0x010a;
+    }
+
+    /** check API version of this class and the native binary. This is usually a good idea to ensure consistency.
+	@return <code>true</code> if the API version of the Java code and the native library matches, <code>false</code> otherwise */
+	public static boolean versionCheck() {
+		return (getVersion()==rniGetVersion());
+	}
+	
+    /** debug flag. Set to value &gt;0 to enable debugging messages. The verbosity increases with increasing number */
+    public static int DEBUG = 0;
+	
+	/** this value specifies the time (in ms) to spend sleeping between checks for R shutdown requests if R event loop is not used. The default is 200ms. Higher values lower the CPU usage but may make R less responsive to shutdown attempts (in theory it should not matter because {@link #stop()} uses interrupt to awake from the idle sleep immediately, but some implementation may not honor that).
+	@since JRI 0.3
+	*/
+	public int idleDelay = 200;
+	
+    /** main engine. Since there can be only one instance of R, this is also the only instance. */
+    static Rengine mainEngine=null;
+    
+    /** return the current main R engine instance. Since there can be only one true R instance at a time, this is also the only instance. This may not be true for future versions, though.
+	@return current instance of the R engine or <code>null</code> if no R engine was started yet. */
+    public static Rengine getMainEngine() { return mainEngine; }
+
+    /* public static Thread getMainRThread() { return mainRThread; } */
+
+    /** returns <code>true</code> if the current thread is the main R thread, <code>false</code> otherwise
+	@since JRI 0.4
+     */
+    public static boolean inMainRThread() {
+	return (mainRThread != null && mainRThread.equals(Thread.currentThread()));
+    }
+
+    boolean standAlone = true;
+
+    /** returns <code>true</code> if this engine was started as a stand-alone Java application or <code>false</code> if this engine was hooked into an existing R instance
+	@since JRI 0.4
+    */
+    public boolean isStandAlone() { return standAlone; }
+
+    boolean died, alive, runLoop, loopRunning;
+    /** arguments used to initialize R, set by the constructor */
+	String[] args;
+	/** synchronization mutex */
+	Mutex Rsync;
+	/** callback handler */
+    RMainLoopCallbacks callback;
+	
+    /** create and start a new instance of R. 
+	@param args arguments to be passed to R. Please note that R requires the presence of certain arguments (e.g. <code>--save</code> or <code>--no-save</code> or equivalents), so passing an empty list usually doesn't work.
+	@param runMainLoop if set to <code>true</code> the the event loop will be started as soon as possible, otherwise no event loop is started. Running loop requires <code>initialCallbacks</code> to be set correspondingly as well.
+	@param initialCallbacks an instance implementing the {@link org.rosuda.JRI.RMainLoopCallbacks RMainLoopCallbacks} interface that provides methods to be called by R
+    */
+    public Rengine(String[] args, boolean runMainLoop, RMainLoopCallbacks initialCallbacks) {
+        super();
+        Rsync=new Mutex();
+        died=false;
+        alive=false;
+        runLoop=runMainLoop;
+        loopRunning=false;
+        this.args=args;
+        callback=initialCallbacks;
+        mainEngine=this;
+	mainRThread=this;
+        start();
+        while (!alive && !died) yield();
+    }
+
+    /** create a new engine by hooking into an existing, initialized R instance which is calling this constructor. Currently JRI won't influence this R instance other than disabling stack checks (i.e. no callbacks can be registered etc.). It is *not* the designated constructor and it should be used *only* from withing rJava.
+	@since JRI 0.4
+     */
+    public Rengine() {
+	super();
+	Rsync=new Mutex();
+	died=false;
+	alive=true;
+	runLoop=false;
+	loopRunning=true;
+	standAlone=false;
+	args=new String[] { "--zero-init"};
+	callback=null;
+	mainEngine=this;
+	mainRThread=Thread.currentThread();
+	rniSetupR(args);
+    }
+
+    /** RNI: setup R with supplied parameters (should <b>not</b> be used directly!).
+	@param args arguments
+	@return result code
+     */
+    native int rniSetupR(String[] args);
+    
+    /** RNI: setup IPC with RJava. This method is used by rJava to pass the IPC information to the JRI engine for synchronization
+	@since experimental, not in the public API!
+     */
+    public native int rniSetupRJava(int _in, int _out);
+
+    /** RNI: lock rJava to allow callbacks - this interrupts R event loop until @link{rniRJavaUnlock} is called.
+	@return 0 = lock failed, 1 = locked via IPC (you must use rniRJavaUnlock subsequently), 2 = rJava is already locked */
+    public native int rniRJavaLock();
+
+    /** RNI: unlock rJava - resumes R event loop. Please note that unlocking without a previously successful lock may cause fatal errors, because it may release a lock issued by another thread which may not have finished yet. */
+    public native int rniRJavaUnlock();
+
+    synchronized int setupR() {
+        return setupR(null);
+    }
+    
+    synchronized int setupR(String[] args) {
+        int r=rniSetupR(args);
+        if (r==0) {
+            alive=true; died=false;
+        } else {
+            alive=false; died=true;
+        }
+        return r;
+    }
+    
+    /** RNI: parses a string into R expressions (do NOT use directly unless you know exactly what you're doing, where possible use {@link #eval} instead). Note that no synchronization is performed!
+	@param s string to parse
+	@param parts number of expressions contained in the string
+	@return reference to the resulting list of expressions */
+    public synchronized native long rniParse(String s, int parts);
+    /** RNI: evaluate R expression (do NOT use directly unless you know exactly what you're doing, where possible use {@link #eval} instead). Note that no synchronization is performed!
+	@param exp reference to the expression to evaluate
+	@param rho environment to use for evaluation (or 0 for global environemnt)
+	@return result of the evaluation or 0 if an error occurred */
+    public synchronized native long rniEval(long exp, long rho);
+
+	/** RNI: protect an R object (c.f. PROTECT macro in C)
+		@since API 1.5, JRI 0.3
+		@param exp reference to protect */
+	public synchronized native void rniProtect(long exp);
+	/** RNI: unprotect last <code>count</code> references (c.f. UNPROTECT in C)
+		@since API 1.5, JRI 0.3
+		@param count number of references to unprotect */
+	public synchronized native void rniUnprotect(int count);
+
+    /** RNI: get the contents of the first entry of a character vector
+	@param exp reference to STRSXP
+	@return contents or <code>null</code> if the reference is not STRSXP */
+    public synchronized native String rniGetString(long exp);
+    /** RNI: get the contents of a character vector
+	@param exp reference to STRSXP
+	@return contents or <code>null</code> if the reference is not STRSXP */
+    public synchronized native String[] rniGetStringArray(long exp);
+    /** RNI: get the contents of an integer vector
+	@param exp reference to INTSXP
+	@return contents or <code>null</code> if the reference is not INTSXP */
+    public synchronized native int[] rniGetIntArray(long exp);
+    /** RNI: get the contents of a logical vector in its integer array form
+	@since API 1.6, JRI 0.3-2
+	@param exp reference to LGLSXP
+	@return contents or <code>null</code> if the reference is not LGLSXP */
+    public synchronized native int[] rniGetBoolArrayI(long exp);
+    /** RNI: get the contents of a numeric vector
+	@param exp reference to REALSXP
+	@return contents or <code>null</code> if the reference is not REALSXP */
+    public synchronized native double[] rniGetDoubleArray(long exp);
+    /** RNI: get the contents of a raw vector
+	 @since API 1.9, JRI 0.5
+	 @param exp reference to RAWSXP
+	 @return contents or <code>null</code> if the reference is not RAWSXP */
+    public synchronized native byte[] rniGetRawArray(long exp);
+    /** RNI: get the contents of a generic vector (aka list)
+	@param exp reference to VECSXP
+	@return contents as an array of references or <code>null</code> if the reference is not VECSXP */
+    public synchronized native long[] rniGetVector(long exp);
+
+    /** RNI: create a character vector of the length 1
+	@param s initial contents of the first entry
+	@return reference to the resulting STRSXP */
+    public synchronized native long rniPutString(String s);
+    /** RNI: create a character vector
+	@param a initial contents of the vector
+	@return reference to the resulting STRSXP */
+    public synchronized native long rniPutStringArray(String[] a);
+    /** RNI: create an integer vector
+	@param a initial contents of the vector
+	@return reference to the resulting INTSXP */
+    public synchronized native long rniPutIntArray(int [] a);
+    /** RNI: create a boolean vector from an integer vector
+	@since API 1.6, JRI 0.3-2
+	@param a initial contents of the vector
+	@return reference to the resulting LGLSXP */
+    public synchronized native long rniPutBoolArrayI(int [] a);
+    /** RNI: create a boolean vector
+	@since API 1.6, JRI 0.3-2
+	@param a initial contents of the vector
+	@return reference to the resulting LGLSXP */
+    public synchronized native long rniPutBoolArray(boolean [] a);
+    /** RNI: create a numeric vector
+	@param a initial contents of the vector
+	@return reference to the resulting REALSXP */
+    public synchronized native long rniPutDoubleArray(double[] a);
+    /** RNI: create a raw vector
+	 @since API 1.9, JRI 0.5
+	 @param a initial contents of the vector
+	 @return reference to the resulting RAWSXP */
+    public synchronized native long rniPutRawArray(byte[] a);
+    /** RNI: create a generic vector (aka a list)
+	@param exps initial contents of the vector consisiting of an array of references
+	@return reference to the resulting VECSXP */
+    public synchronized native long rniPutVector(long[] exps);
+    
+    /** RNI: get an attribute
+	@param exp reference to the object whose attribute is requested
+	@param name name of the attribute
+	@return reference to the attribute or 0 if there is none */
+    public synchronized native long rniGetAttr(long exp, String name);
+	/** RNI: get attribute names
+	 @param exp reference to the object whose attributes are requested
+	 @return a list of strings naming all attributes or <code>null</code> if there are none 
+	 @since API 1.9, JRI 0.5 */
+    public synchronized native String[] rniGetAttrNames(long exp);	
+    /** RNI: set an attribute
+	 @param exp reference to the object whose attribute is to be modified
+	 @param name attribute name
+	 @param attr reference to the object to be used as the contents of the attribute */
+    public synchronized native void rniSetAttr(long exp, String name, long attr);
+
+	/** RNI: determines whether an R object instance inherits from a specific class (S3 for now)
+		@since API 1.5, JRI 0.3
+		@param exp reference to an object
+		@param cName name of the class to check
+		@return <code>true</code> if <code>cName</code> inherits from class <code>cName</code> (see <code>inherits</code> in R) */ 
+	public synchronized native boolean rniInherits(long exp, String cName);
+
+    /** RNI: create a dotted-pair list (LISTSXP or LANGSXP)
+	@param head CAR
+	@param tail CDR (must be a reference to LISTSXP or 0)
+	@param tag TAG
+	@param lang if <code>true</code> then LANGSXP is created, otherwise LISTSXP.
+	@return reference to the newly created LISTSXP/LANGSXP
+	@since API 1.7, JRI 0.3-7
+*/
+    public synchronized native long rniCons(long head, long tail, long tag, boolean lang);
+
+    /** RNI: create a dotted-pair list (LISTSXP)
+	@param head CAR
+	@param tail CDR (must be a reference to LISTSXP or 0)
+	@return reference to the newly created LISTSXP
+    */
+    public long rniCons(long head, long tail) { return rniCons(head, tail, 0, false); }
+    /** RNI: create a dotted-pair language list (LANGSXP)
+	@param head CAR
+	@param tail CDR (must be a reference to LANGSXP or 0)
+	@return reference to the newly created LANGSXP
+	@since API 1.7, JRI 0.3-7
+    */
+    public long rniLCons(long head, long tail) { return rniCons(head, tail, 0, true); }
+
+    /** RNI: get CAR of a dotted-pair list (LISTSXP)
+	@param exp reference to the list
+	@return reference to CAR of the list (head) */
+    public synchronized native long rniCAR(long exp);
+    /** RNI: get CDR of a dotted-pair list (LISTSXP)
+	@param exp reference to the list
+	@return reference to CDR of the list (tail) */
+    public synchronized native long rniCDR(long exp);
+    /** RNI: get TAG of a dotted-pair list (LISTSXP)
+		@param exp reference to the list
+		@return reference to TAG of the list (tail) */
+    public synchronized native long rniTAG(long exp);
+    /** RNI: create a dotted-pair list (LISTSXP)
+		@since API 1.5, JRI 0.3
+		@param cont contents as an array of references
+		@return reference to the newly created LISTSXP */
+    public synchronized native long rniPutList(long[] cont);
+    /** RNI: retrieve CAR part of a dotted-part list recursively as an array of references
+	@param exp reference to a dotted-pair list (LISTSXP)
+	@return contents of the list as an array of references */
+    public synchronized native long[] rniGetList(long exp);
+	/** RNI: retrieve name of a symbol (c.f. PRINTNAME)
+		@since API 1.5, JRI 0.3
+		@param sym reference to a symbol
+		@return name of the symbol or <code>null</code> on error or if exp is no symbol */
+	public synchronized native String rniGetSymbolName(long sym);
+	/** RNI: install a symbol name
+		@since API 1.5, JRI 0.3
+		@param sym symbol name
+		@return reference to SYMSXP referencing the symbol */
+	public synchronized native long rniInstallSymbol(String sym);
+
+	/** RNI: print.<p><i>Note:</i> May NOT be called inside any WriteConsole callback as it would cause an infinite loop.
+		@since API 1.8, JRI 0.4
+		@param s string to print (as-is)
+		@param oType output type (see R for exact references, but 0 should be regular output and 1 error/warning) */
+	public synchronized native void rniPrint(String s, int oType);
+
+	/** RNI: print the value of a given R object (via print or show method) to the console
+		@since API 1.9, JRI 0.5
+		@param exp reference to an R object */
+	public synchronized native void rniPrintValue(long exp);
+
+	/** RNI: preserve object (prevent grabage collection in R) until rniRelease is called.
+		@since API 1.9, JRI 0.5
+		@param exp reference to an R object */
+	public synchronized native void rniPreserve(long exp);
+	/** RNI: release object previously preserved via rniPreserve.<p>Note: releasing an obejct that was not preserved is an error and results in an undefined behavior.
+		@since API 1.9, JRI 0.5
+		@param exp reference to an R object */
+	public synchronized native void rniRelease(long exp);
+	
+	/** RNI: return the parent environment
+		@since API 1.9, JRI 0.5
+		@param exp reference to environment
+		@return parent environment */
+	public synchronized native long rniParentEnv(long exp);
+
+	/** RNI: find variable in an environment
+		@since API 1.9, JRI 0.5
+		@param sym symbol name
+		@param rho reference to environment
+		@return reference to the value or UnboundValue if not found */
+	public synchronized native long rniFindVar(String sym, long rho);
+
+	/** RNI: return the list of variable names of an environment
+		@since API 1.9, JRI 0.5
+		@param exp reference to the environment
+		@param all if set to <code>true</code> then all objects will be shown, otherwise hidden objects will be omitted
+		@return reference to a string vector of names in the environment */
+	public synchronized native long rniListEnv(long exp, boolean all);
+
+	/** RNI: return a special object reference. Note that all such references are constants valid for the entire session and cannot be protected/preserved (they are persistent already).
+		@since API 1.9, JRI 0.5
+		@param which constant referring to a particular special object (see SO_xxx constants)
+		@return reference to a special object or 0 if the kind of object it unknown/unsupported */
+	public synchronized native long rniSpecialObject(int which);
+	
+	//--- was API 1.4 but it only caused portability problems, so we got rid of it
+    //public static native void rniSetEnv(String key, String val);
+    //public static native String rniGetEnv(String key);
+	//--- end API 1.4
+
+	/** RNI: convert Java object to EXTPTRSEXP
+		@param o arbitrary Java object
+		@return new EXTPTRSEXP pointing to the Java object
+		@since API 1.5, JRI 0.3
+		*/
+	public synchronized native long rniJavaToXref(Object o);
+	/** RNI: convert EXTPTRSEXP to Java object - make sure the pointer is really what you expect, otherwise you'll crash the JVM!
+		@param exp reference to EXTPTRSEXP pointing to a Java object
+		@return resulting Java object
+		@since API 1.5, JRI 0.3
+		*/
+	public synchronized native Object rniXrefToJava(long exp);
+	
+    /** RNI: return the API version of the native library
+		@return API version of the native library */
+    public static native long rniGetVersion();
+    
+    /** RNI: interrupt the R process (if possible). Note that R handles interrupt requests in (R-thread-)synchronous, co-operative fashion as it wants to make sure that the interrupted state is recoverable. If interrupting from another thread while using blocking ReadConsole REPL make sure you also interrupt your ReadConsole call after rniStop such that R can act on the signalled interrupt.
+	@param flag determines how to attempt to inform R about the interrput. For normal (safe) operation using flag signalling must be 0. Other options are 1 (SIGINT for compatibility with older JRI API) and 2 (<tt>Rf_onintr</tT> call - use <u>only</u> on the R thread and only if you know what it means). Values other than 0 are only supported since JRI 0.5-4.
+	@return result code (currently 0) */
+    public native int rniStop(int flag);
+    
+    /** RNI: assign a value to an environment
+	@param name name
+	@param exp value
+	@param rho environment (use 0 for the global environment)
+	@return <code>true</code> if successful, <code>false</code> on failure (usually this means that the binding is locked)
+        @since API 1.10, JRI 0.5-1 (existed before but returned <code>void</code>)
+    */
+    public synchronized native boolean rniAssign(String name, long exp, long rho);
+    
+    /** RNI: get the SEXP type
+	@param exp reference to a SEXP
+	@return type of the expression (see xxxSEXP constants) */
+    public synchronized native int rniExpType(long exp);
+    /** RNI: run the main loop.<br> <i>Note:</i> this is an internal method and it doesn't return until the loop exits. Don't use directly! */
+    public native void rniRunMainLoop();
+    
+    /** RNI: run other event handlers in R */
+    public synchronized native void rniIdle();
+
+    /** Add a handler for R callbacks. The current implementation supports only one handler at a time, so call to this function implicitly removes any previous handlers */
+    public void addMainLoopCallbacks(RMainLoopCallbacks c)
+    {
+        // we don't really "add", we just replace ... (so far)
+        callback = c;
+    }
+
+    /** if Rengine was initialized with <code>runMainLoop=false</code> then this method can be used to start the main loop at a later point. It has no effect if the loop is running already. This method returns immediately but the loop will be started once the engine is ready. Please note that there is currently no way of stopping the R thread if the R event loop is running other than using <code>quit</code> command in R which closes the entire application. */
+    public void startMainLoop() {
+		runLoop=true;
+    }
+    
+    //============ R callback methods =========
+
+    /** JRI: R_WriteConsole call-back from R
+	@param text text to disply */
+    public void jriWriteConsole(String text, int oType)
+    {
+        if (callback!=null) callback.rWriteConsole(this, text, oType);
+    }
+
+    /** JRI: R_Busy call-back from R
+	@param which state */
+    public void jriBusy(int which)
+    {
+        if (callback!=null) callback.rBusy(this, which);
+    }
+
+    /** JRI: R_ReadConsole call-back from R.
+	@param prompt prompt to display before waiting for the input.<br><i>Note:</i> implementations should block for input. Returning immediately is usually a bad idea, because the loop will be cycling.
+	@param addToHistory flag specifying whether the entered contents should be added to history
+	@return content entered by the user. Returning <code>null</code> corresponds to an EOF and usually causes R to exit (as in <code>q()</doce>). */
+    public String jriReadConsole(String prompt, int addToHistory)
+    {
+	if (DEBUG>1)
+	    System.out.println("Rengine.jreReadConsole BEGIN "+Thread.currentThread());
+        if (loopHasLock) {
+	    Rsync.unlock();
+	    loopHasLock = false;
+	}
+        String s = (callback == null) ? null : callback.rReadConsole(this, prompt, addToHistory);
+        loopHasLock = Rsync.safeLock();
+	if (!loopHasLock) {
+            String es = "\n>>JRI Warning: jriReadConsole detected a possible deadlock ["+Rsync+"]["+Thread.currentThread()+"]. Proceeding without lock, but this is inherently unsafe.\n";
+            jriWriteConsole(es, 1);
+            System.err.print(es);
+        }
+	if (DEBUG>1)
+	    System.out.println("Rengine.jreReadConsole END "+Thread.currentThread());
+        return s;
+    }
+
+    /** JRI: R_ShowMessage call-back from R
+	@param message message */
+    public void jriShowMessage(String message)
+    {
+        if (callback!=null) callback.rShowMessage(this, message);
+    }
+    
+    /** JRI: R_loadhistory call-back from R
+	@param filename name of the history file */
+    public void jriLoadHistory(String filename)
+    {
+        if (callback!=null) callback.rLoadHistory(this, filename);
+    }
+
+    /** JRI: R_savehistory call-back from R
+	@param filename name of the history file */
+    public void jriSaveHistory(String filename)
+    {
+        if (callback!=null) callback.rSaveHistory(this, filename);
+    }
+	
+    /** JRI: R_ChooseFile call-back from R
+	@param newFile flag specifying whether an existing or new file is requested
+	@return name of the selected file or <code>null</code> if cancelled */
+    public String jriChooseFile(int newFile)
+    {
+        if (callback!=null) return callback.rChooseFile(this, newFile);
+		return null;
+    }
+	
+    /** JRI: R_FlushConsole call-back from R */	
+    public void jriFlushConsole()
+    {
+        if (callback!=null) callback.rFlushConsole(this);
+    }
+	
+    
+    //============ "official" API =============
+
+
+    /** Parses and evaluates an R expression and returns the result. Has the same effect as calling <code>eval(s, true)</code>.
+	@param s expression (as string) to parse and evaluate
+	@return resulting expression or <code>null</code> if something wnet wrong */
+    public synchronized REXP eval(String s) {
+		return eval(s, true);
+	}
+	
+    /** Parses and evaluates an R expression and returns the result.
+		@since JRI 0.3
+		@param s expression (as string) to parse and evaluate
+		@param convert if set to <code>true</code> the resulting REXP will contain native representation of the contents, otherwise an empty REXP will be returned. Depending on the back-end an empty REXP may or may not be used to convert the result at a later point.
+		@return resulting expression or <code>null</code> if something wnet wrong */
+    public synchronized REXP eval(String s, boolean convert) {
+	if (DEBUG>0)
+	    System.out.println("Rengine.eval("+s+"): BEGIN "+Thread.currentThread());
+        boolean obtainedLock=Rsync.safeLock();
+        try {
+            /* --- so far, we ignore this, because it can happen when a callback needs an eval which is ok ...
+            if (!obtainedLock) {
+                String es="\n>>JRI Warning: eval(\""+s+"\") detected a possible deadlock ["+Rsync+"]["+Thread.currentThread()+"]. Proceeding without lock, but this is inherently unsafe.\n";
+                jriWriteConsole(es);
+                System.err.print(es);
+            }
+             */
+            long pr = rniParse(s, 1);
+            if (pr != 0) {
+                long er = rniEval(pr, 0);
+                if (er != 0) {
+                    REXP x = new REXP(this, er, convert);
+                    if (DEBUG>0) System.out.println("Rengine.eval("+s+"): END (OK)"+Thread.currentThread());
+                    return x;
+                }
+            }
+        } finally {
+            if (obtainedLock) Rsync.unlock();
+        }
+        if (DEBUG>0) System.out.println("Rengine.eval("+s+"): END (ERR)"+Thread.currentThread());
+        return null;
+    }
+    
+    /** This method is very much like {@link #eval(String)}, except that it is non-blocking and returns <code>null</code> if the engine is busy.
+        @param s string to evaluate
+        @return result of the evaluation or <code>null</code> if the engine is busy
+        */
+    public synchronized REXP idleEval(String s) {
+		return idleEval(s, true);
+	}
+
+    /** This method is very much like {@link #eval(String,boolean)}, except that it is non-blocking and returns <code>null</code> if the engine is busy.
+		@since JRI 0.3
+        @param s string to evaluate
+		@param convert flag denoting whether an empty or fully-converted REXP should be returned (see {@link #eval(String,boolean)} for details)
+        @return result of the evaluation or <code>null</code> if the engine is busy
+        */
+    public synchronized REXP idleEval(String s, boolean convert) {
+        int lockStatus=Rsync.tryLock();
+        if (lockStatus==1) return null; // 1=locked by someone else
+        boolean obtainedLock=(lockStatus==0);
+        try {
+            long pr = rniParse(s, 1);
+            if (pr != 0) {
+                long er = rniEval(pr, 0);
+                if (er != 0) {
+                    REXP x = new REXP(this, er, convert);
+                    return x;
+                }
+            }
+        } finally {
+            if (obtainedLock) Rsync.unlock();
+        }
+        return null;
+    }
+    
+	/** returns the synchronization mutex for this engine. If an external code needs to use RNI calls, it should do so only in properly protected environment secured by this mutex. Usually the procedure should be as follows:<pre>
+	boolean obtainedLock = e.getRsync().safeLock();
+	try {
+		// use RNI here ...
+	} finally {
+		if (obtainedLock) e.getRsync().unlock();
+	}
+	</pre>
+		@return synchronization mutex
+		@since JRI 0.3
+		*/
+	public Mutex getRsync() {
+		return Rsync;
+	}
+	
+    /** check the state of R
+		@return <code>true</code> if R is alive and <code>false</code> if R died or exitted */
+    public synchronized boolean waitForR() {
+        return alive;
+    }
+
+    /** attempt to shut down R. This method is asynchronous. */
+    public void end() {
+        alive = false;
+        interrupt();
+    }
+    
+    /** The implementation of the R thread. This method should not be called directly. */	
+    public void run() {
+	if (DEBUG > 0)
+	    System.out.println("Starting R...");
+	loopHasLock = Rsync.safeLock(); // force all code to wait until R is ready
+	try {
+	    if (setupR(args) == 0) {
+		if (!runLoop && loopHasLock) { // without event loop we can unlock now since we woin't do anything
+		    Rsync.unlock();
+		    loopHasLock = false;
+		}
+		while (alive) {
+		    try {
+			if (runLoop) {                        
+			    if (DEBUG > 0)
+				System.out.println("***> launching main loop:");
+			    loopRunning = true;
+			    rniRunMainLoop();
+			    // actually R never returns from runMainLoop ...
+			    loopRunning = false;
+			    if (DEBUG > 0)
+				System.out.println("***> main loop finished:");
+			    runLoop = false;
+			    died = true;
+			    return;
+			}
+			sleep(idleDelay);
+			if (runLoop) rniIdle();
+		    } catch (InterruptedException ie) {
+			interrupted();
+		    }
+		}
+		died=true;
+		if (DEBUG>0)
+		    System.out.println("Terminating R thread.");
+	    } else {
+		System.err.println("Unable to start R");
+	    }
+	} finally {
+	    if (loopHasLock) Rsync.unlock();
+	}
+    }
+	
+	/** assign a string value to a symbol in R. The symbol is created if it doesn't exist already.
+         *  @param sym symbol name.  The symbol name is used as-is, i.e. as if it was quoted in R code (for example assigning to "foo$bar" has the same effect as `foo$bar`&lt;- and NOT foo$bar&lt;-).
+	 *  @param ct contents
+	 *  @return <code>true</code> if successful, <code>false</code> otherwise
+	 *  @since JRI 0.3 (return value changed to boolean in JRI 0.5-1)
+	 */
+    public boolean assign(String sym, String ct) {
+	boolean obtainedLock = Rsync.safeLock();
+	try {
+	    long x1 = rniPutString(ct);
+	    return rniAssign(sym,x1,0);
+	} finally {
+	    if (obtainedLock) Rsync.unlock();
+	}
+    }
+
+    /** assign a content of a REXP to a symbol in R. The symbol is created if it doesn't exist already.
+        @param sym symbol name. The symbol name is used as-is, i.e. as if it was quoted in R code (for example assigning to "foo$bar" has the same effect as `foo$bar`&lt;- and NOT foo$bar&lt;-).
+        @param r contents as <code>REXP</code>. currently only raw references and basic types (int, double, int[], double[], boolean[]) are supported.
+	@return <code>true</code> if successful, <code>false</code> otherwise (usually locked binding or unsupported REXP)
+	@since JRI 0.3 (return value changed to boolean in JRI 0.5-1)
+        */
+    public boolean assign(String sym, REXP r) {
+	boolean obtainedLock = Rsync.safeLock();
+	try {
+	    if (r.Xt == REXP.XT_NONE) {
+		return rniAssign(sym, r.xp, 0);
+	    }
+	    if (r.Xt == REXP.XT_INT || r.Xt == REXP.XT_ARRAY_INT) {
+    		int[] cont = r.rtype == REXP.XT_INT?new int[]{((Integer)r.cont).intValue()}:(int[])r.cont;
+    		long x1 = rniPutIntArray(cont);
+    		return rniAssign(sym,x1,0);
+	    }
+	    if (r.Xt == REXP.XT_DOUBLE || r.Xt == REXP.XT_ARRAY_DOUBLE) {
+    		double[] cont = r.rtype == REXP.XT_DOUBLE?new double[]{((Double)r.cont).intValue()}:(double[])r.cont;
+    		long x1 = rniPutDoubleArray(cont);
+    		return rniAssign(sym,x1,0);
+	    }
+	    if (r.Xt == REXP.XT_ARRAY_BOOL_INT) {
+		long x1 = rniPutBoolArrayI((int[])r.cont);
+		return rniAssign(sym,x1,0);
+	    }
+	    if (r.Xt == REXP.XT_STR || r.Xt == REXP.XT_ARRAY_STR) {
+		String[] cont = r.rtype == REXP.XT_STR?new String[]{(String)r.cont}:(String[])r.cont;
+		long x1 = rniPutStringArray(cont);
+		return rniAssign(sym,x1,0);
+	    }
+	} finally {
+	    if (obtainedLock) Rsync.unlock();
+	}
+	return false;
+    }
+
+    /** assign values of an array of doubles to a symbol in R (creating an integer vector).<br>
+        equals to calling {@link #assign(String, REXP)}.
+		@param sym symbol name
+		@param val double array to assign
+		@return <code>true</code> if successful, <code>false</code> otherwise
+		@since JRI 0.3 (return value changed to boolean in JRI 0.5-1)
+	*/
+    public boolean assign(String sym, double[] val)  {
+        return assign(sym,new REXP(val));
+    }
+
+    /** assign values of an array of integers to a symbol in R (creating a numeric vector).<br>
+        equals to calling {@link #assign(String, REXP)}.
+		@param sym symbol name
+		@param val integer array to assign
+		@return <code>true</code> if successful, <code>false</code> otherwise
+		@since JRI 0.3 (return value changed to boolean in JRI 0.5-1)
+		*/
+    public boolean assign(String sym, int[] val) {
+        return assign(sym,new REXP(val));
+    }
+
+    /** assign values of an array of booleans to a symbol in R (creating a logical vector).<br>
+        equals to calling {@link #assign(String, REXP)}.
+		@param sym symbol name
+		@param val boolean array to assign
+		@return <code>true</code> if successful, <code>false</code> otherwise
+		@since JRI 0.3-2 (return value changed to boolean in JRI 0.5-1)
+		*/
+    public boolean assign(String sym, boolean[] val) {
+        return assign(sym,new REXP(val));
+    }
+
+    /** assign values of an array of strings to a symbol in R (creating a character vector).<br>
+        equals to calling {@link #assign(String, REXP)}.
+		@param sym symbol name
+		@param val string array to assign
+		@return <code>true</code> if successful, <code>false</code> otherwise
+		@since JRI 0.3 (return value changed to boolean in JRI 0.5-1)
+		*/
+    public boolean assign(String sym, String[] val) {
+        return assign(sym,new REXP(val));
+    }
+
+    /** creates a <code>jobjRef</code> reference in R via rJava.<br><b>Important:</b> rJava must be loaded and intialized in R (e.g. via <code>eval("{library(rJava);.jinit()}",false)</code>, otherwise this will fail. Requires rJava 0.4-13 or higher!
+	@param o object to push
+	@return Pure REXP reference of the newly created <code>jobjRef</code> object or <code>null</code> upon failure. It will have the type <code>XT_NONE</code> such that it can be used in @link{assign(String, REXP)}.
+	@since JRI 0.3-7
+    */
+    public REXP createRJavaRef(Object o) {
+	    if (o == null) return null;
+	    String klass = o.getClass().getName();
+	    boolean obtainedLock = Rsync.safeLock();
+	    try {
+		    long l = rniEval(
+				     rniLCons(
+					      rniInstallSymbol(".jmkref"),
+					      rniLCons(
+						       rniJavaToXref(o),
+						       rniLCons(
+								rniPutString(klass), 0
+								)
+						       )
+					      )
+				     , 0);
+		    if (l <= 0 && l > -4) return null; /* for safety failure codes are only -3 .. 0 to not clash with 64-bit pointers */
+		    return new REXP(this, l, false);
+	    } finally {
+		    if (obtainedLock) Rsync.unlock();
+	    }
+    }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/Boot.java b/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/Boot.java
new file mode 100644
index 0000000000000000000000000000000000000000..0f0d8583e4017bdd33312b8da8467f150e4b8281
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/Boot.java
@@ -0,0 +1,133 @@
+import java.io.File;
+import java.io.InputStream;
+import java.io.FileOutputStream;
+import java.util.StringTokenizer;
+import java.util.zip.ZipFile;
+import java.util.zip.ZipEntry;
+import java.lang.reflect.Method;
+
+public class Boot {
+    public static String bootFile = null;
+
+	public static String findInPath(String path, String fn) {
+		StringTokenizer st = new StringTokenizer(path, File.pathSeparator);
+		while (st.hasMoreTokens()) {
+			String dirname=st.nextToken();
+			try {
+				File f = new File(dirname+File.separator+fn);
+				if (f.isFile()) return f.getPath();
+			} catch (Exception fex) {}
+		}
+		return null;
+	}
+
+	public static String findNativeLibrary(String basename, boolean internalFirst) {
+		String libName = "lib"+basename;
+		String ext = ".so";
+		String os = System.getProperty("os.name");
+		if (os.startsWith("Win")) {
+			os = "Win";
+			ext= ".dll";
+			libName=basename;
+		}
+		if (os.startsWith("Mac")) {
+			os = "Mac";
+			ext= ".jnilib";
+		}
+		String fullName = libName+ext;
+
+		// first, try the system path unless instructed otherwise
+		if (!internalFirst) {
+			try {
+				String r = findInPath("."+File.pathSeparator+System.getProperty("java.library.path"),
+									  fullName);
+				if (r != null) return r;
+			} catch (Exception ex1) {}
+		}
+
+		// second, try to locate in on the class path (in the JAR file or in one of the directories)
+		String cp = System.getProperty("java.class.path");
+		StringTokenizer st = new StringTokenizer(cp, File.pathSeparator);
+		while (st.hasMoreTokens()) {
+			String dirname=st.nextToken();
+			try {
+				File f = new File(dirname);
+				if (f.isFile()) {
+					// look in a JAR file and extract it if necessary
+					ZipFile jf = new ZipFile(f);
+					ZipEntry ze = jf.getEntry(fullName);
+					if (ze != null) { // found it inside a JAR file						
+						try {
+						    bootFile = f.toString();
+							File tf = File.createTempFile(basename,ext);
+							System.out.println("Boot.findNativeLibrary: found in a JAR ("+jf+"), extracting into "+tf);
+							InputStream zis = jf.getInputStream(ze);
+							FileOutputStream fos = new FileOutputStream(tf);
+							byte b[] = new byte[65536];
+							while (zis.available()>0) {
+								int n = zis.read(b);
+								if (n>0) fos.write(b, 0, n);
+							}
+							zis.close();
+							fos.close();
+							tf.deleteOnExit();
+							return tf.getPath();
+						} catch (Exception foo) {
+						}
+					}
+				} else if (f.isDirectory()) {
+					File ff = new File(dirname+File.separator+fullName);
+					if (ff.isFile()) return ff.getPath();
+				}
+			} catch(Exception ex2) {}
+		}
+
+		// third, try the system path if we didn't look there before
+		if (internalFirst) {
+			try {
+				String r = findInPath("."+File.pathSeparator+System.getProperty("java.library.path"),
+									  fullName);
+				if (r != null) return r;
+			} catch (Exception ex3) {}
+		}
+		return null;
+	}
+
+	public static void main(String[] args) {
+		// 1) instantiate master class loader
+		JRIClassLoader mcl = JRIClassLoader.getMainLoader();
+
+		// 2) locate boot JNI library
+		String nl = findNativeLibrary("boot", false);
+		
+		if (nl == null) {
+			System.err.println("ERROR: Unable to locate native bootstrap library.");
+			System.exit(1);
+		}
+		
+		// register boot library with MCL
+		mcl.registerLibrary("boot", new File(nl));
+
+		// add path necessary for loading JRIBootstrap to MCL
+		String cp = System.getProperty("java.class.path");
+		StringTokenizer st = new StringTokenizer(cp, File.pathSeparator);
+		while (st.hasMoreTokens()) {
+		    String p = st.nextToken();
+		    mcl.addClassPath(p);
+		    // we assume that the first file on the CP is us (FIXME: verify this!)
+		    if (bootFile==null && (new File(p)).isFile()) bootFile=p;
+		}
+		
+		// call static bootstrap method
+		try {
+			// force the use of the MCL even if the system loader could find it
+			Class stage2class = mcl.findAndLinkClass("JRIBootstrap");
+			Method m = stage2class.getMethod("bootstrap", new Class[] { String[].class });
+			m.invoke(null, new Object[] { args });
+		} catch (Exception rtx) {
+			System.err.println("ERROR: Unable to invoke bootstrap method in JRIBootstrap! ("+rtx+")");
+			rtx.printStackTrace();
+			System.exit(2);
+		}
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/DelegatedClassLoader.java b/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/DelegatedClassLoader.java
new file mode 100644
index 0000000000000000000000000000000000000000..b1abef480f5e99c5380a5f1903281105b7db12f3
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/DelegatedClassLoader.java
@@ -0,0 +1,7 @@
+import java.net.URL;
+
+public interface DelegatedClassLoader {
+    public String delegatedFindLibrary(String name);
+    public Class delegatedFindClass(String name) throws ClassNotFoundException;
+    public URL delegatedFindResource(String name);
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/DelegatedURLClassLoader.java b/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/DelegatedURLClassLoader.java
new file mode 100644
index 0000000000000000000000000000000000000000..9a8333f16bc6d91b4ee76b9b864d47584fb187fd
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/DelegatedURLClassLoader.java
@@ -0,0 +1,22 @@
+/* An extension of URLClassLoader that implements DelegatedClassLoader */
+
+import java.net.URL;
+import java.net.URLClassLoader;
+
+public class DelegatedURLClassLoader extends URLClassLoader implements DelegatedClassLoader {
+    public DelegatedURLClassLoader() {
+	super(new URL[]{});
+    }
+    public DelegatedURLClassLoader(URL[] urls) {
+	super(urls);
+    }
+    public String delegatedFindLibrary(String name) {
+	return super.findLibrary(name);
+    }
+    public Class delegatedFindClass(String name) throws ClassNotFoundException {
+	return super.findClass(name);
+    }
+    public URL delegatedFindResource(String name) {
+	return super.findResource(name);
+    }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/JRIBootstrap.c b/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/JRIBootstrap.c
new file mode 100644
index 0000000000000000000000000000000000000000..22f3df916f6b271a84e1885856e4ac156e78d068
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/JRIBootstrap.c
@@ -0,0 +1,166 @@
+#include "JRIBootstrap.h"
+
+#if defined WIN32 || defined Win32
+
+#include <windows.h>
+#include <winreg.h>
+
+static const HKEY keyDB[2] = { HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER };
+
+JNIEXPORT jstring JNICALL Java_JRIBootstrap_getenv
+(JNIEnv *env, jclass cl, jstring sVar) {
+  char cVal[1024];
+  int res;
+  const char *cVar = (*env)->GetStringUTFChars(env, sVar, 0);
+  if (!cVar) return 0;
+  *cVal=0; cVal[1023]=0;
+  res = GetEnvironmentVariable(cVar, cVal, 1023);
+  (*env)->ReleaseStringUTFChars(env, sVar, cVar);
+  return res?((*env)->NewStringUTF(env, cVal)):0;
+}
+
+JNIEXPORT void JNICALL Java_JRIBootstrap_setenv
+(JNIEnv *env, jclass cl, jstring sVar, jstring sVal) {
+  const char *cVar = sVar?(*env)->GetStringUTFChars(env, sVar, 0):0;
+  const char *cVal = sVal?(*env)->GetStringUTFChars(env, sVal, 0):0;
+  if (cVar) SetEnvironmentVariable(cVar, cVal?cVal:"");
+  if (cVar) (*env)->ReleaseStringUTFChars(env, sVar, cVar);
+  if (cVal) (*env)->ReleaseStringUTFChars(env, sVal, cVal);
+  return;
+}
+
+JNIEXPORT jstring JNICALL Java_JRIBootstrap_regvalue
+(JNIEnv *env, jclass cl, jint iRoot, jstring sKey, jstring sVal) {
+  const char *cKey = sKey?(*env)->GetStringUTFChars(env, sKey, 0):0;
+  const char *cVal = sVal?(*env)->GetStringUTFChars(env, sVal, 0):0;
+  jstring res = 0;
+  if (cKey && cVal) {
+    HKEY key;
+    if (RegOpenKeyEx(keyDB[iRoot], cKey, 0, KEY_QUERY_VALUE, &key) == ERROR_SUCCESS) {
+      char buf[1024];
+      DWORD t, s = 1023;
+      *buf=0; buf[1023]=0;
+      if (RegQueryValueEx(key, cVal, 0, &t, buf, &s) == ERROR_SUCCESS) {
+	res = (*env)->NewStringUTF(env, buf);
+      }
+      RegCloseKey(key);
+    }
+  }
+  if (cVal) (*env)->ReleaseStringUTFChars(env, sVal, cVal);
+  if (cKey) (*env)->ReleaseStringUTFChars(env, sKey, cKey);
+  
+  return res;
+}
+
+JNIEXPORT jobjectArray JNICALL Java_JRIBootstrap_regsubkeys
+(JNIEnv *env, jclass cl, jint iRoot, jstring sKey) {
+  const char *cKey = sKey?(*env)->GetStringUTFChars(env, sKey, 0):0;
+  jobjectArray res = 0;
+  if (cKey) {
+    HKEY key;
+    if (RegOpenKeyEx(keyDB[iRoot], cKey, 0, KEY_ENUMERATE_SUB_KEYS|KEY_QUERY_VALUE, &key) == ERROR_SUCCESS) {
+      int n = 0, i = 0;
+      char buf[256];
+      jclass cStr;
+      *buf=0;
+      buf[255]=0;
+      /* pass 1: count the entries */
+      while (RegEnumKey(key, n, buf, 254) == ERROR_SUCCESS) n++;
+      /* pass 2: get the values */
+      cStr = (*env)->FindClass(env, "java/lang/String");
+      res = (*env)->NewObjectArray(env, n, cStr, 0);
+      (*env)->DeleteLocalRef(env, cStr);
+      while (i<n && RegEnumKey(key, i, buf, 254) == ERROR_SUCCESS)
+	(*env)->SetObjectArrayElement(env, res, i++,
+				      (*env)->NewStringUTF(env, buf));
+      RegCloseKey(key);
+    }
+    (*env)->ReleaseStringUTFChars(env, sKey, cKey);
+  }
+  return res;
+}
+
+JNIEXPORT jstring JNICALL Java_JRIBootstrap_expand
+(JNIEnv *env, jclass cl, jstring sVal) {
+  jstring res = sVal;
+  const char *cVal = sVal?(*env)->GetStringUTFChars(env, sVal, 0):0;
+  char buf[1024];
+  *buf=0; buf[1023]=0;
+  if (cVal) {
+    if (ExpandEnvironmentStrings(cVal, buf, 1023))
+      res = (*env)->NewStringUTF(env, buf);
+  }
+  if (cVal) (*env)->ReleaseStringUTFChars(env, sVal, cVal);
+  return res;
+}
+
+JNIEXPORT jboolean JNICALL Java_JRIBootstrap_hasreg
+(JNIEnv *env, jclass cl) {
+  return JNI_TRUE;
+}
+
+#else
+
+#include <stdlib.h>
+
+JNIEXPORT jstring JNICALL Java_JRIBootstrap_getenv
+(JNIEnv *env, jclass cl, jstring sVar) {
+  char *cVal;
+  const char *cVar = sVar?(*env)->GetStringUTFChars(env, sVar, 0):0;
+  if (!cVar) return 0;
+  cVal=getenv(cVar);
+  (*env)->ReleaseStringUTFChars(env, sVar, cVar);
+  return cVal?((*env)->NewStringUTF(env, cVal)):0;
+}
+
+JNIEXPORT void JNICALL Java_JRIBootstrap_setenv
+(JNIEnv *env, jclass cl, jstring sVar, jstring sVal) {
+  const char *cVar = sVar?(*env)->GetStringUTFChars(env, sVar, 0):0;
+  const char *cVal = sVal?(*env)->GetStringUTFChars(env, sVal, 0):0;
+  if (cVar) setenv(cVar, cVal?cVal:"", 1);
+  if (cVar) (*env)->ReleaseStringUTFChars(env, sVar, cVar);
+  if (cVal) (*env)->ReleaseStringUTFChars(env, sVal, cVal);
+  return;
+}
+
+/* no registry on unix, so always return null */
+JNIEXPORT jstring JNICALL Java_JRIBootstrap_regvalue
+(JNIEnv *env, jclass cl, jint iRoot, jstring sKey, jstring sVal) {
+  return 0;
+}
+
+JNIEXPORT jobjectArray JNICALL Java_JRIBootstrap_regsubkeys
+(JNIEnv *env, jclass cl, jint iRoot, jstring sKey) {
+  return 0;
+}
+
+JNIEXPORT jstring JNICALL Java_JRIBootstrap_expand
+(JNIEnv *env, jclass cl, jstring sVal) {
+  return sVal;
+}
+
+JNIEXPORT jboolean JNICALL Java_JRIBootstrap_hasreg
+(JNIEnv *env, jclass cl) {
+  return JNI_FALSE;
+}
+
+#endif
+
+JNIEXPORT jstring JNICALL Java_JRIBootstrap_arch
+(JNIEnv *env, jclass cl) {
+  const char *ca = "unknown";
+  /* this is mainly for Macs so we can determine the correct arch ... */
+#ifdef __ppc__
+  ca = "ppc";
+#endif
+#ifdef __i386__
+  ca = "i386";
+#endif
+#ifdef __x86_64__
+  ca = "x86_64";
+#endif
+#ifdef __ppc64__
+  ca = "ppc64";
+#endif
+  return (*env)->NewStringUTF(env, ca);
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/JRIBootstrap.h b/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/JRIBootstrap.h
new file mode 100644
index 0000000000000000000000000000000000000000..39ba8dfc1519cd9fc53e078fcb9d2894bbab7727
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/JRIBootstrap.h
@@ -0,0 +1,57 @@
+/* DO NOT EDIT THIS FILE - it is machine generated */
+#include <jni.h>
+/* Header for class JRIBootstrap */
+
+#ifndef _Included_JRIBootstrap
+#define _Included_JRIBootstrap
+#ifdef __cplusplus
+extern "C" {
+#endif
+#undef JRIBootstrap_HKLM
+#define JRIBootstrap_HKLM 0L
+#undef JRIBootstrap_HKCU
+#define JRIBootstrap_HKCU 1L
+/*
+ * Class:     JRIBootstrap
+ * Method:    getenv
+ * Signature: (Ljava/lang/String;)Ljava/lang/String;
+ */
+JNIEXPORT jstring JNICALL Java_JRIBootstrap_getenv
+  (JNIEnv *, jclass, jstring);
+
+/*
+ * Class:     JRIBootstrap
+ * Method:    setenv
+ * Signature: (Ljava/lang/String;Ljava/lang/String;)V
+ */
+JNIEXPORT void JNICALL Java_JRIBootstrap_setenv
+  (JNIEnv *, jclass, jstring, jstring);
+
+/*
+ * Class:     JRIBootstrap
+ * Method:    regvalue
+ * Signature: (ILjava/lang/String;Ljava/lang/String;)Ljava/lang/String;
+ */
+JNIEXPORT jstring JNICALL Java_JRIBootstrap_regvalue
+  (JNIEnv *, jclass, jint, jstring, jstring);
+
+/*
+ * Class:     JRIBootstrap
+ * Method:    regsubkeys
+ * Signature: (ILjava/lang/String;)[Ljava/lang/String;
+ */
+JNIEXPORT jobjectArray JNICALL Java_JRIBootstrap_regsubkeys
+  (JNIEnv *, jclass, jint, jstring);
+
+/*
+ * Class:     JRIBootstrap
+ * Method:    expand
+ * Signature: (Ljava/lang/String;)Ljava/lang/String;
+ */
+JNIEXPORT jstring JNICALL Java_JRIBootstrap_expand
+  (JNIEnv *, jclass, jstring);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/JRIBootstrap.java b/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/JRIBootstrap.java
new file mode 100644
index 0000000000000000000000000000000000000000..bec97661528197f91d0bb9734732426d172229b2
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/JRIBootstrap.java
@@ -0,0 +1,398 @@
+import java.io.File;
+import java.io.PrintStream;
+import java.io.FileOutputStream;
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.util.StringTokenizer;
+
+public class JRIBootstrap {
+	//--- global constants ---
+	public static final int HKLM = 0; // HKEY_LOCAL_MACHINE
+	public static final int HKCU = 1; // HKEY_CURRENT_USER
+
+	//--- native methods ---
+	public static native String getenv(String var);
+	public static native void setenv(String var, String val);
+
+	public static native String regvalue(int root, String key, String value);
+	public static native String[] regsubkeys(int root, String key);
+
+	public static native String expand(String val);
+
+	public static native boolean hasreg();
+
+	public static native String arch();
+
+	//--- helper methods ---	
+	static void fail(String msg) {
+		System.err.println("ERROR: "+msg);
+		System.exit(1);
+	}
+
+        public static String findInPath(String path, String fn, boolean mustBeFile) {
+                StringTokenizer st = new StringTokenizer(path, File.pathSeparator);
+                while (st.hasMoreTokens()) {
+                        String dirname=st.nextToken();
+                        try {
+                                File f = new File(dirname+File.separator+fn);
+				System.out.println(" * "+f+" ("+f.exists()+", "+f.isFile()+")");
+                                if (f.exists() && (!mustBeFile || f.isFile())) return f.getPath();
+                        } catch (Exception fex) {}
+                }
+                return null;
+        }
+
+    // set ONLY after findR was run
+    public static boolean isWin32 = false;
+    public static boolean isMac = false;
+
+    static String findR(boolean findAllSettings) {
+	String ip = null;
+	try {
+	    if (hasreg()) {
+		isWin32 = true;
+		int rroot = HKLM;
+		System.out.println("has registry, trying to find R");
+		ip = regvalue(HKLM, "SOFTWARE\\R-core\\R","InstallPath");
+		if (ip == null)
+		    ip = regvalue(rroot=HKCU, "SOFTWARE\\R-core\\R","InstallPath");
+		if (ip == null) {
+		    System.out.println(" - InstallPath not present (possibly uninstalled R)");
+		    String[] vers = regsubkeys(rroot=HKLM, "SOFTWARE\\R-core\\R");
+		    if (vers == null)
+			vers = regsubkeys(rroot=HKCU, "SOFTWARE\\R-core\\R");
+		    if (vers!=null) {
+			String lvn = ""; // FIXME: we compare versions lexicographically which may fail if we really reach R 2.10
+			int i = 0; while (i<vers.length) {
+			    if (vers[i] != null && lvn.compareTo(vers[i]) < 0)
+				lvn = vers[i];
+			    i++;
+			}
+			if (!lvn.equals(""))
+			    ip = regvalue(rroot, "SOFTWARE\\R-core\\R\\"+lvn, "InstallPath");
+		    }
+		}
+		if (ip == null) {
+		    ip = getenv("R_HOME");
+		    if (ip==null || ip.length()<1) ip = getenv("RHOME");
+		    if (ip==null || ip.length()<1) ip=null;
+		}
+		if (ip != null) rs_home = ip;
+		return ip;
+	    }
+	    isMac = System.getProperty("os.name").startsWith("Mac");
+	    File f = null;
+	    ip = getenv("R_HOME");
+	    if (ip == null || ip.length()<1)
+		ip = getenv("RHOME");
+	    if (ip == null || ip.length()<1) {
+		if (isMac) {
+		    f=new File("/Library/Frameworks/R.framework/Resources/bin/R");
+		    if (!f.exists())
+			f=new File(getenv("HOME")+"/Library/Frameworks/R.framework/Resources/bin/R");
+		    if (!f.exists())
+			f=null;
+		}
+		if (f==null) {
+		    String fn = findInPath(getenv("PATH"), "R", true);
+		    if (fn == null)
+			fn = findInPath("/usr/bin:/usr/local/bin:/sw/bin:/opt/bin:/usr/lib/R/bin:/usr/local/lib/R/bin", "R", true);
+		    if (fn != null) f = new File(fn);
+		}
+		if (!findAllSettings) {
+		    String s = f.getAbsolutePath();
+		    if (s.length()>6) ip = s.substring(0, s.length()-6);
+		}
+	    }
+	    if (findAllSettings) {
+		if (f==null && ip!=null) f=new File(u2w(ip+"/bin/R"));
+		if (f!=null) ip = getRSettings(f.getAbsolutePath());
+	    }
+
+	} catch (Exception e) {
+	}
+	return ip;
+    }
+
+    public static String rs_home = "";
+    public static String rs_arch = "";
+    public static String rs_docdir = "";
+    public static String rs_incdir = "";
+    public static String rs_sharedir = "";
+    public static String rs_ldp = "";
+    public static String rs_dyldp = "";
+    public static String rs_unzip = "";
+    public static String rs_latex = "";
+    public static String rs_paper = "";
+    public static String rs_print = "";
+    public static String rs_libs = "";
+
+    public static void setREnv() {
+	if (rs_home!=null && rs_home.length()>0) setenv("R_HOME", rs_home);
+	if (rs_arch!=null && rs_arch.length()>0) setenv("R_ARCH", rs_arch);
+	if (rs_docdir!=null && rs_docdir.length()>0) setenv("R_DOC_DIR", rs_docdir);
+	if (rs_incdir!=null && rs_incdir.length()>0) setenv("R_INCLUDE_DIR", rs_incdir);
+	if (rs_sharedir!=null && rs_sharedir.length()>0) setenv("R_SHARE_DIR", rs_sharedir);
+	if (rs_ldp!=null && rs_ldp.length()>0) setenv("LD_LIBRARY_PATH", rs_ldp);
+	if (rs_dyldp!=null && rs_dyldp.length()>0) setenv("DYLD_LIBRARY_PATH", rs_dyldp);
+	if (rs_libs!=null && rs_libs.length()>0) setenv("R_LIBS", rs_libs);
+    }
+
+    public static int execR(String cmd) {
+	try {
+	    String binR = u2w(rs_home+"/bin/R");
+	    if (isWin32) {
+		binR+=".exe";
+		File fin = File.createTempFile("rboot",".R");
+		File fout = File.createTempFile("rboot",".tmp");
+		PrintStream p = new PrintStream(new FileOutputStream(fin));
+		p.println(cmd);
+		p.close();
+		Process rp = Runtime.getRuntime().exec(new String[] {
+			binR,"CMD","BATCH","--no-restore","--no-save","--slave",fin.getAbsolutePath(),
+			fout.getAbsolutePath()});
+		int i = rp.waitFor();
+		if (!fin.delete()) fin.deleteOnExit();
+		if (!fout.delete()) fout.deleteOnExit();
+		return i;
+	    } else {
+		Process rp = Runtime.getRuntime().exec(new String[] {
+			"/bin/sh","-c","echo \""+cmd+"\" |"+binR+" --no-restore --no-save --slave >/dev/null 2>&1" });
+		return rp.waitFor();
+	    }
+	} catch (Exception e) {
+	    lastError = e.toString();
+	    return -1;
+	}
+    }
+
+    public static String getRSettings(String binR) {
+	try {
+	    File fin = File.createTempFile("rboot",".R");
+	    File fout = File.createTempFile("rboot",".tmp");
+	    PrintStream p = new PrintStream(new FileOutputStream(fin));
+	    p.println("cat(unlist(lapply(c('R_HOME','R_ARCH','R_DOC_DIR','R_INCLUDE_DIR','R_SHARE_DIR','LD_LIBRARY_PATH','DYLD_LIBRARY_PATH','R_UNZIPCMD','R_LATEXCMD','R_PAPERSIZE','R_PRINTCMD'),Sys.getenv)),sep='\n')");
+	    p.println("cat(paste(.libPaths(),collapse=.Platform$path.sep),'\n',sep='')");
+	    p.close();
+	    Process rp = Runtime.getRuntime().exec(new String[] {
+		    "/bin/sh","-c",binR+" --no-restore --no-save --slave < \""+fin.getAbsolutePath()+"\" > \""+fout.getAbsolutePath()+"\"" });
+	    int i = rp.waitFor();
+	    System.out.println("getRSettings, i="+i);
+	    BufferedReader r = new BufferedReader(new FileReader(fout));
+	    rs_home = r.readLine();
+	    rs_arch = r.readLine();
+	    rs_docdir = r.readLine();
+	    rs_incdir = r.readLine();
+	    rs_sharedir = r.readLine();
+	    rs_ldp = r.readLine();
+	    rs_dyldp = r.readLine();
+	    rs_unzip = r.readLine();
+	    rs_latex = r.readLine();
+	    rs_paper = r.readLine();
+	    rs_print = r.readLine();
+	    rs_libs = r.readLine();
+	    r.close();
+	    if (!fin.delete()) fin.deleteOnExit();
+	    //if (!fout.delete()) fout.deleteOnExit();
+	    System.out.println(" - retrieved R settings, home: "+rs_home+" (arch="+rs_arch+", libs="+rs_libs+")");
+	} catch (Exception e) {
+	    System.err.println("Failed to get R settings: "+e);
+	}
+	return rs_home;
+    }
+
+    public static String u2w(String fn) {
+	return (java.io.File.separatorChar != '/')?fn.replace('/',java.io.File.separatorChar):fn;
+    }
+
+    public static Object bootRJavaLoader = null;
+
+    public static Object getBootRJavaLoader() {
+	System.out.println("JRIBootstrap.bootRJavaLoader="+bootRJavaLoader);
+	return bootRJavaLoader;
+    }
+
+    static void addClassPath(String s) {
+	if (bootRJavaLoader==null) return;
+	try {
+	    Method m = bootRJavaLoader.getClass().getMethod("addClassPath", new Class[] { String.class });
+	    m.invoke(bootRJavaLoader, new Object[] { s });
+	} catch (Exception e) {
+	    System.err.println("FAILED: JRIBootstrap.addClassPath");
+	}
+    }
+
+    static String lastError = "";
+
+    static String findPackage(String name) {
+	String pd = null;
+	if (rs_libs!=null && rs_libs.length()>0)
+	    pd = findInPath(rs_libs, name, false);
+	if (pd == null) {
+	    pd = u2w(rs_home+"/library/"+name);
+	    if (!(new File(pd)).exists()) pd = null;
+	}
+	return pd;	
+    }
+
+    static Object createRJavaLoader(String rhome, String[] cp, boolean addJRI) {
+	String rJavaRoot = null;
+	if (rs_libs!=null && rs_libs.length()>0)
+	    rJavaRoot = findInPath(rs_libs, "rJava", false);
+	if (rJavaRoot == null)
+	    rJavaRoot = u2w(rhome+"/library/rJava");
+
+	if (!(new File(rJavaRoot)).exists()) {
+	    lastError="Unable to find rJava";
+	    return null;
+	}
+
+	File f = new File(u2w(rJavaRoot+"/java/boot"));
+	if (!f.exists()) {
+	    // try harder ...
+	    lastError = "rJava too old";
+	    return null;
+	}
+	String rJavaHome = u2w(rJavaRoot);
+	File lf = null;
+	if (rs_arch!=null && rs_arch.length()>0) lf = new File(u2w(rJavaRoot+"/libs"+rs_arch));
+	if (lf == null || !lf.exists()) lf = new File(u2w(rJavaRoot+"/libs/"+arch()));
+	if (!lf.exists()) lf = new File(u2w(rJavaRoot+"/libs"));
+	String rJavaLibs = lf.toString();
+	JRIClassLoader mcl = JRIClassLoader.getMainLoader();
+	mcl.addClassPath(f.toString()); // add rJava boot to primary CP
+	try {
+	    // force the use of the MCL even if the system loader could find it
+	    Class rjlclass = mcl.findAndLinkClass("RJavaClassLoader");
+	    Constructor c = rjlclass.getConstructor(new Class[] { String.class, String.class });
+	    Object rjcl = c.newInstance(new Object[] { rJavaHome, rJavaLibs });
+	    System.out.println("RJavaClassLoader: "+rjcl);
+	    if (addJRI) {
+		if (cp==null || cp.length==0)
+		    cp = new String[] { u2w(rJavaRoot+"/jri/JRI.jar") };
+		else {
+		    String[] ncp = new String[cp.length+1];
+		    System.arraycopy(cp, 0, ncp, 1, cp.length);
+		    ncp[0] = u2w(rJavaRoot+"/jri/JRI.jar");
+		    cp = ncp;
+		}
+	    }
+	    if (cp==null || cp.length==0)
+		cp = new String[] { u2w(rJavaRoot+"/java/boot") };
+	    else {
+		String[] ncp = new String[cp.length+1];
+		System.arraycopy(cp, 0, ncp, 1, cp.length);
+		ncp[0] = u2w(rJavaRoot+"/java/boot");
+		cp = ncp;
+	    }
+	    if (cp != null) {
+		System.out.println(" - adding class paths");
+		Method m = rjlclass.getMethod("addClassPath", new Class[] { String[].class });
+		m.invoke(rjcl, new Object[] { cp });
+	    }
+	    return rjcl;
+	} catch (Exception rtx) {
+	    System.err.println("ERROR: Unable to create new RJavaClassLoader in JRIBootstrap! ("+rtx+")");
+	    rtx.printStackTrace();
+	    System.exit(2);
+	}
+	return null;
+    }
+	
+	//--- main bootstrap method ---
+	public static void bootstrap(String[] args) {
+		System.out.println("JRIBootstrap("+args+")");
+		try {
+			System.loadLibrary("boot");
+		} catch (Exception e) {
+			fail("Unable to load boot library!");
+		}
+		
+		// just testing from now on
+		String rhome = findR(true);
+		if (rhome == null) fail("Unable to find R!");
+		if (isWin32) {
+		    String path = getenv("PATH");
+		    if (path==null || path.length()<1) path=rhome+"\\bin";
+		    else path=rhome+"\\bin;"+path;
+		    setenv("PATH",path);
+		}
+		setREnv();
+
+		System.out.println("PATH="+getenv("PATH")+"\nR_LIBS="+getenv("R_LIBS"));
+
+		if (!isMac && !isWin32) {
+		    String stage = System.getProperty("stage");
+		    if (stage==null || stage.length()<1) {
+			File jl = new File(u2w(System.getProperty("java.home")+"/bin/java"));
+			if (jl.exists()) {
+			    try {
+				System.out.println(jl.toString()+" -cp "+System.getProperty("java.class.path")+" -Xmx512m -Dstage=2 Boot");
+				Process p = Runtime.getRuntime().exec(new String[] {
+				    jl.toString(), "-cp", System.getProperty("java.class.path"),
+				    "-Xmx512m", "-Dstage=2", "Boot" });
+				System.out.println("Started stage 2 ("+p+"), waiting for it to finish...");
+				System.exit(p.waitFor());
+			    } catch (Exception re) {
+			    }
+			}
+		    }
+		}
+
+		String needPkg = null;
+		String rj = findPackage("rJava");
+		if (rj == null) {
+		    System.err.println("**ERROR: rJava is not installed");
+		    if (needPkg==null) needPkg="'rJava'"; else needPkg+=",'rJava'";
+		}
+		String ipl = findPackage("iplots");
+		if (ipl == null) {
+		    System.err.println("**ERROR: iplots is not installed");
+		    if (needPkg==null) needPkg="'iplots'"; else needPkg+=",'iplots'";
+		}
+		String jgr = findPackage("JGR");
+		if (jgr == null) {
+		    System.err.println("**ERROR: JGR is not installed");
+		    if (needPkg==null) needPkg="'JGR'"; else needPkg+=",'JGR'";
+		}
+		if (needPkg != null) {
+		    if (!isWin32 && !isMac) {
+			System.err.println("*** Please run the following in R as root to install missing packages:\n install.packages(c("+needPkg+"),,'http://www.rforge.net/')");
+			System.exit(4);
+		    }
+		    if (execR("install.packages(c("+needPkg+"),,c('http://www.rforge.net/','http://cran.r-project.org'))")!=0) {
+			System.err.println("*** ERROR: failed to install necessary packages");
+			System.exit(4);
+		    }
+		    rj = findPackage("rJava");
+		    ipl = findPackage("iplots");
+		    jgr = findPackage("JGR");
+		    if (rj==null || ipl==null || jgr==null) {
+			System.err.println("*** ERROR: failed to find installed packages");
+			System.exit(5);
+		    }
+		}
+
+		Object o = bootRJavaLoader = createRJavaLoader(rhome, new String[] { "main" }, true);
+
+		addClassPath(u2w(jgr+"/cont/JGR.jar"));
+		addClassPath(u2w(ipl+"/cont/iplots.jar"));
+		String mainClass = "org.rosuda.JGR.JGR";
+
+		try {
+		    Method m = o.getClass().getMethod("bootClass", new Class[] { String.class, String.class, String[].class });
+		    m.invoke(o, new Object[] { mainClass, "main", args });
+		} catch(Exception ie) {		    
+		    System.out.println("cannot boot the final class: "+ie);
+		    ie.printStackTrace();
+		}
+	}
+
+	public static void main(String[] args) {
+		System.err.println("*** WARNING: JRIBootstrap.main should NOT be called directly, it is intended for debugging use ONLY. Use Boot wrapper instead.");
+		// just for testing
+		bootstrap(args);
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/JRIClassLoader.java b/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/JRIClassLoader.java
new file mode 100644
index 0000000000000000000000000000000000000000..26eab9c53b306375d4cce4a1e6bdb200351153ab
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/JRIClassLoader.java
@@ -0,0 +1,121 @@
+import java.net.URLClassLoader;
+import java.net.URL;
+import java.util.HashMap;
+import java.util.Vector;
+import java.util.Enumeration;
+import java.io.File;
+
+public class JRIClassLoader extends URLClassLoader {
+	HashMap libMap;
+
+	Vector children;
+
+	static JRIClassLoader mainLoader;
+
+	public static JRIClassLoader getMainLoader() {
+		if (mainLoader == null) mainLoader = new JRIClassLoader();
+		return mainLoader;
+	}
+
+	public JRIClassLoader() {
+		super(new URL[]{});
+		children = new Vector();
+		libMap = new HashMap();
+		System.out.println("JRIClassLoader: new loader "+this);
+	}
+
+	public void registerLoader(DelegatedClassLoader cl) {
+		if (!children.contains(cl))
+			children.add(cl);
+	}
+
+	public void unregisterLoader(DelegatedClassLoader cl) {
+		children.removeElement(cl);
+	}
+
+	public void registerLibrary(String name, File f) {
+		libMap.put(name, f);
+	}
+
+	/** add path to the class path list
+		@param path string denoting the path to the file or directory */
+	public void addClassPath(String path) {
+		try {
+			File f = new File(path);
+			if (f.exists()) addURL(f.toURL());
+		} catch (Exception x) {}
+	}
+
+	/** add path to the class path list
+		@param f file/directory to add to the list */
+	public void addClassPath(File f) {
+		try {
+			if (f.exists()) addURL(f.toURL());
+		} catch (Exception x) {}
+	}
+
+	protected String findLibrary(String name) {
+		String s = null;
+		System.out.println("boot findLibrary(\""+name+"\")");
+		try {
+			for (Enumeration e = children.elements() ; e.hasMoreElements() ;) {
+				DelegatedClassLoader cl = (DelegatedClassLoader)e.nextElement();
+				if (cl != null) {
+					s = cl.delegatedFindLibrary(name);
+					if (s != null) {
+						System.out.println(" - found delegated answer "+s+" from "+cl);
+						return s;
+					}
+				}
+			}
+		} catch (Exception ex) {}
+
+		File u = (File) libMap.get(name);
+		if (u!=null && u.exists()) s=u.getAbsolutePath();
+		System.out.println(" - mapping to "+((s==null)?"<none>":s));
+
+		return s;
+	}
+
+	public Class findAndLinkClass(String name) throws ClassNotFoundException {
+		Class c = findClass(name);
+		resolveClass(c);
+		return c;
+	}
+
+	protected Class findClass(String name) throws ClassNotFoundException {
+		Class cl = null;
+		System.out.println("boot findClass(\""+name+"\")");
+		for (Enumeration e = children.elements() ; e.hasMoreElements() ;) {
+			DelegatedClassLoader ldr = (DelegatedClassLoader)e.nextElement();
+			if (ldr != null) {
+				try {
+					cl = ldr.delegatedFindClass(name);
+					if (cl != null) {
+						System.out.println(" - found delegated answer "+cl+" from "+ldr);
+						return cl;
+					}
+				} catch (Exception ex) {}
+			}
+		}
+		return super.findClass(name);
+	}
+
+	public URL findResource(String name) {
+		URL u = null;
+		System.out.println("boot findResource(\""+name+"\")");
+		for (Enumeration e = children.elements() ; e.hasMoreElements() ;) {
+			DelegatedClassLoader ldr = (DelegatedClassLoader)e.nextElement();
+			if (ldr != null) {
+				try {
+					u = ldr.delegatedFindResource(name);
+					if (u != null) {
+						System.out.println(" - found delegated answer "+u+" from "+ldr);
+						return u;
+					}
+				} catch (Exception ex) {}
+			}
+		}
+		return super.findResource(name);
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/Makefile b/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..044daea04fa22dc097b632779112026d3b8a27cc
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/Makefile
@@ -0,0 +1,69 @@
+# Makefile for JRI bootstrap
+# Win/OSX should be ok, Linux will need some tweaking
+
+all: boot.jar
+
+OSKIND=$(shell if echo "${OS}"|grep -i windows >/dev/null 2>&1; then echo win32; else uname -s; fi)
+
+ifeq ($(OSKIND),win32)
+ifeq ($(JAVA_HOME),)
+JAVA_HOME=N:/java/jdk1.5.0
+endif
+JSO_PREFIX=
+JSO_SUFFIX=.dll
+JCPPFLAGS=-DWIN32 -I$(JAVA_HOME)/include -I$(JAVA_HOME)/include/win32
+JLDFLAGS=-shared -Wl,--add-stdcall-alias -mno-cygwin
+JLIBS=-L$(JAVA_HOME)/jre/bin/client -L$(JAVA_HOME)/jre/bin -ljvm
+PATHSEP=\;
+KNOWNOS=yes
+OSNAME=Windows
+JAVA=$(JAVA_HOME)/bin/java
+JAVAC=$(JAVA_HOME)/bin/javac
+JAR=$(JAVA_HOME)/bin/jar
+endif
+ifeq ($(OSKIND),Darwin)
+JSO_PREFIX=lib
+JSO_SUFFIX=.jnilib
+JLDFLAGS=-dynamiclib
+JLIBS=-framework JavaVM
+JCPPFLAGS=-I/System/Library/Frameworks/JavaVM.framework/Headers
+PATHSEP=:
+KNOWNOS=yes
+OSNAME=MacOSX
+JAVA=java
+JAVAC=javac
+JAR=jar
+endif
+ifneq ($(KNOWNOS),yes)
+ifeq ($(JAVA_HOME),)
+JAVA_HOME=/usr/lib/java
+endif
+JSO_PREFIX=lib
+JSO_SUFFIX=.so
+JCPPFLAGS=-I$(JAVA_HOME)/include -I$(shell dirname `find $(JAVA_HOME)/include -name jni_md.h|sed -n -e 1p`)
+JLDFLAGS=-shared
+JLIBS=-L$(JAVA_HOME)/lib -ljvm
+PATHSEP=:
+OSNAME="generic unix"
+JAVA=java
+JAVAC=javac
+JAR=jar
+endif
+
+$(JSO_PREFIX)boot$(JSO_SUFFIX): JRIBootstrap.o
+	$(CC) $(JLDFLAGS) -o $@ $^ #$(JLIBS)
+
+JRIBootstrap.o: JRIBootstrap.c JRIBootstrap.h
+	$(CC) -c -o $@ $< $(JCPPFLAGS)
+
+run: boot.jar
+	$(JAVA) -jar $<
+
+clean:
+	rm -f JRIBootstrap.o $(JSO_PREFIX)boot$(JSO_SUFFIX) *.class *~
+
+boot.jar: $(JSO_PREFIX)boot$(JSO_SUFFIX)
+	$(JAVAC) -source 1.2 -target 1.2 *.java
+	$(JAR) fcm $@ mft *.class $^
+
+.PHONY: clean run all
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/mft b/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/mft
new file mode 100644
index 0000000000000000000000000000000000000000..5a2288cba85ce357b5f27ed9abb55b53227d95d5
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/bootstrap/mft
@@ -0,0 +1 @@
+Main-Class: Boot
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/configure b/com.oracle.truffle.r.pkgs/rJava/jri/configure
new file mode 100755
index 0000000000000000000000000000000000000000..501cd3234cf7b2332076259fb9607119a5fa6d88
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/configure
@@ -0,0 +1,5148 @@
+#! /bin/sh
+# Guess values for system-dependent variables and create Makefiles.
+# Generated by GNU Autoconf 2.69 for JRI 0.3.
+#
+# Report bugs to <simon.urbanek@r-project.org>.
+#
+#
+# Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
+#
+#
+# This configure script is free software; the Free Software Foundation
+# gives unlimited permission to copy, distribute and modify it.
+## -------------------- ##
+## M4sh Initialization. ##
+## -------------------- ##
+
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
+  emulate sh
+  NULLCMD=:
+  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in #(
+  *posix*) :
+    set -o posix ;; #(
+  *) :
+     ;;
+esac
+fi
+
+
+as_nl='
+'
+export as_nl
+# Printing a long string crashes Solaris 7 /usr/bin/printf.
+as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
+# Prefer a ksh shell builtin over an external printf program on Solaris,
+# but without wasting forks for bash or zsh.
+if test -z "$BASH_VERSION$ZSH_VERSION" \
+    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='print -r --'
+  as_echo_n='print -rn --'
+elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='printf %s\n'
+  as_echo_n='printf %s'
+else
+  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
+    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
+    as_echo_n='/usr/ucb/echo -n'
+  else
+    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
+    as_echo_n_body='eval
+      arg=$1;
+      case $arg in #(
+      *"$as_nl"*)
+	expr "X$arg" : "X\\(.*\\)$as_nl";
+	arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
+      esac;
+      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
+    '
+    export as_echo_n_body
+    as_echo_n='sh -c $as_echo_n_body as_echo'
+  fi
+  export as_echo_body
+  as_echo='sh -c $as_echo_body as_echo'
+fi
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  PATH_SEPARATOR=:
+  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
+    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
+      PATH_SEPARATOR=';'
+  }
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+IFS=" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+as_myself=
+case $0 in #((
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+  done
+IFS=$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  exit 1
+fi
+
+# Unset variables that we do not need and which cause bugs (e.g. in
+# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
+# suppresses any "Segmentation fault" message there.  '((' could
+# trigger a bug in pdksh 5.2.14.
+for as_var in BASH_ENV ENV MAIL MAILPATH
+do eval test x\${$as_var+set} = xset \
+  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+LC_ALL=C
+export LC_ALL
+LANGUAGE=C
+export LANGUAGE
+
+# CDPATH.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+# Use a proper internal environment variable to ensure we don't fall
+  # into an infinite loop, continuously re-executing ourselves.
+  if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then
+    _as_can_reexec=no; export _as_can_reexec;
+    # We cannot yet assume a decent shell, so we have to provide a
+# neutralization value for shells without unset; and this also
+# works around shells that cannot unset nonexistent variables.
+# Preserve -v and -x to the replacement shell.
+BASH_ENV=/dev/null
+ENV=/dev/null
+(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
+case $- in # ((((
+  *v*x* | *x*v* ) as_opts=-vx ;;
+  *v* ) as_opts=-v ;;
+  *x* ) as_opts=-x ;;
+  * ) as_opts= ;;
+esac
+exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
+# Admittedly, this is quite paranoid, since all the known shells bail
+# out after a failed `exec'.
+$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
+as_fn_exit 255
+  fi
+  # We don't want this to propagate to other subprocesses.
+          { _as_can_reexec=; unset _as_can_reexec;}
+if test "x$CONFIG_SHELL" = x; then
+  as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :
+  emulate sh
+  NULLCMD=:
+  # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '\${1+\"\$@\"}'='\"\$@\"'
+  setopt NO_GLOB_SUBST
+else
+  case \`(set -o) 2>/dev/null\` in #(
+  *posix*) :
+    set -o posix ;; #(
+  *) :
+     ;;
+esac
+fi
+"
+  as_required="as_fn_return () { (exit \$1); }
+as_fn_success () { as_fn_return 0; }
+as_fn_failure () { as_fn_return 1; }
+as_fn_ret_success () { return 0; }
+as_fn_ret_failure () { return 1; }
+
+exitcode=0
+as_fn_success || { exitcode=1; echo as_fn_success failed.; }
+as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; }
+as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; }
+as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; }
+if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then :
+
+else
+  exitcode=1; echo positional parameters were not saved.
+fi
+test x\$exitcode = x0 || exit 1
+test -x / || exit 1"
+  as_suggested="  as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO
+  as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO
+  eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" &&
+  test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1
+test \$(( 1 + 1 )) = 2 || exit 1"
+  if (eval "$as_required") 2>/dev/null; then :
+  as_have_required=yes
+else
+  as_have_required=no
+fi
+  if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then :
+
+else
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+as_found=false
+for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  as_found=:
+  case $as_dir in #(
+	 /*)
+	   for as_base in sh bash ksh sh5; do
+	     # Try only shells that exist, to save several forks.
+	     as_shell=$as_dir/$as_base
+	     if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
+		    { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then :
+  CONFIG_SHELL=$as_shell as_have_required=yes
+		   if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then :
+  break 2
+fi
+fi
+	   done;;
+       esac
+  as_found=false
+done
+$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } &&
+	      { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then :
+  CONFIG_SHELL=$SHELL as_have_required=yes
+fi; }
+IFS=$as_save_IFS
+
+
+      if test "x$CONFIG_SHELL" != x; then :
+  export CONFIG_SHELL
+             # We cannot yet assume a decent shell, so we have to provide a
+# neutralization value for shells without unset; and this also
+# works around shells that cannot unset nonexistent variables.
+# Preserve -v and -x to the replacement shell.
+BASH_ENV=/dev/null
+ENV=/dev/null
+(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
+case $- in # ((((
+  *v*x* | *x*v* ) as_opts=-vx ;;
+  *v* ) as_opts=-v ;;
+  *x* ) as_opts=-x ;;
+  * ) as_opts= ;;
+esac
+exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
+# Admittedly, this is quite paranoid, since all the known shells bail
+# out after a failed `exec'.
+$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
+exit 255
+fi
+
+    if test x$as_have_required = xno; then :
+  $as_echo "$0: This script requires a shell more modern than all"
+  $as_echo "$0: the shells that I found on your system."
+  if test x${ZSH_VERSION+set} = xset ; then
+    $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should"
+    $as_echo "$0: be upgraded to zsh 4.3.4 or later."
+  else
+    $as_echo "$0: Please tell bug-autoconf@gnu.org and
+$0: simon.urbanek@r-project.org about your system,
+$0: including any error possibly output before this
+$0: message. Then install a modern shell, or manually run
+$0: the script under such a shell if you do have one."
+  fi
+  exit 1
+fi
+fi
+fi
+SHELL=${CONFIG_SHELL-/bin/sh}
+export SHELL
+# Unset more variables known to interfere with behavior of common tools.
+CLICOLOR_FORCE= GREP_OPTIONS=
+unset CLICOLOR_FORCE GREP_OPTIONS
+
+## --------------------- ##
+## M4sh Shell Functions. ##
+## --------------------- ##
+# as_fn_unset VAR
+# ---------------
+# Portably unset VAR.
+as_fn_unset ()
+{
+  { eval $1=; unset $1;}
+}
+as_unset=as_fn_unset
+
+# as_fn_set_status STATUS
+# -----------------------
+# Set $? to STATUS, without forking.
+as_fn_set_status ()
+{
+  return $1
+} # as_fn_set_status
+
+# as_fn_exit STATUS
+# -----------------
+# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
+as_fn_exit ()
+{
+  set +e
+  as_fn_set_status $1
+  exit $1
+} # as_fn_exit
+
+# as_fn_mkdir_p
+# -------------
+# Create "$as_dir" as a directory, including parents if necessary.
+as_fn_mkdir_p ()
+{
+
+  case $as_dir in #(
+  -*) as_dir=./$as_dir;;
+  esac
+  test -d "$as_dir" || eval $as_mkdir_p || {
+    as_dirs=
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
+      *) as_qdir=$as_dir;;
+      esac
+      as_dirs="'$as_qdir' $as_dirs"
+      as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_dir" : 'X\(//\)[^/]' \| \
+	 X"$as_dir" : 'X\(//\)$' \| \
+	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_dir" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+      test -d "$as_dir" && break
+    done
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
+
+
+} # as_fn_mkdir_p
+
+# as_fn_executable_p FILE
+# -----------------------
+# Test if FILE is an executable regular file.
+as_fn_executable_p ()
+{
+  test -f "$1" && test -x "$1"
+} # as_fn_executable_p
+# as_fn_append VAR VALUE
+# ----------------------
+# Append the text in VALUE to the end of the definition contained in VAR. Take
+# advantage of any shell optimizations that allow amortized linear growth over
+# repeated appends, instead of the typical quadratic growth present in naive
+# implementations.
+if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
+  eval 'as_fn_append ()
+  {
+    eval $1+=\$2
+  }'
+else
+  as_fn_append ()
+  {
+    eval $1=\$$1\$2
+  }
+fi # as_fn_append
+
+# as_fn_arith ARG...
+# ------------------
+# Perform arithmetic evaluation on the ARGs, and store the result in the
+# global $as_val. Take advantage of shells that can avoid forks. The arguments
+# must be portable across $(()) and expr.
+if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
+  eval 'as_fn_arith ()
+  {
+    as_val=$(( $* ))
+  }'
+else
+  as_fn_arith ()
+  {
+    as_val=`expr "$@" || test $? -eq 1`
+  }
+fi # as_fn_arith
+
+
+# as_fn_error STATUS ERROR [LINENO LOG_FD]
+# ----------------------------------------
+# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
+# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
+# script with STATUS, using 1 if that was 0.
+as_fn_error ()
+{
+  as_status=$1; test $as_status -eq 0 && as_status=1
+  if test "$4"; then
+    as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
+  fi
+  $as_echo "$as_me: error: $2" >&2
+  as_fn_exit $as_status
+} # as_fn_error
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+  as_basename=basename
+else
+  as_basename=false
+fi
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
+
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+
+  as_lineno_1=$LINENO as_lineno_1a=$LINENO
+  as_lineno_2=$LINENO as_lineno_2a=$LINENO
+  eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" &&
+  test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || {
+  # Blame Lee E. McMahon (1931-1989) for sed's syntax.  :-)
+  sed -n '
+    p
+    /[$]LINENO/=
+  ' <$as_myself |
+    sed '
+      s/[$]LINENO.*/&-/
+      t lineno
+      b
+      :lineno
+      N
+      :loop
+      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
+      t loop
+      s/-\n.*//
+    ' >$as_me.lineno &&
+  chmod +x "$as_me.lineno" ||
+    { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; }
+
+  # If we had to re-execute with $CONFIG_SHELL, we're ensured to have
+  # already done that, so ensure we don't try to do so again and fall
+  # in an infinite loop.  This has already happened in practice.
+  _as_can_reexec=no; export _as_can_reexec
+  # Don't try to exec as it changes $[0], causing all sort of problems
+  # (the dirname of $[0] is not the place where we might find the
+  # original and so on.  Autoconf is especially sensitive to this).
+  . "./$as_me.lineno"
+  # Exit status is that of the last command.
+  exit
+}
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in #(((((
+-n*)
+  case `echo 'xy\c'` in
+  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
+  xy)  ECHO_C='\c';;
+  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
+       ECHO_T='	';;
+  esac;;
+*)
+  ECHO_N='-n';;
+esac
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir 2>/dev/null
+fi
+if (echo >conf$$.file) 2>/dev/null; then
+  if ln -s conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s='ln -s'
+    # ... but there are two gotchas:
+    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+    # In both cases, we have to default to `cp -pR'.
+    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+      as_ln_s='cp -pR'
+  elif ln conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s=ln
+  else
+    as_ln_s='cp -pR'
+  fi
+else
+  as_ln_s='cp -pR'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+if mkdir -p . 2>/dev/null; then
+  as_mkdir_p='mkdir -p "$as_dir"'
+else
+  test -d ./-p && rmdir ./-p
+  as_mkdir_p=false
+fi
+
+as_test_x='test -x'
+as_executable_p=as_fn_executable_p
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+test -n "$DJDIR" || exec 7<&0 </dev/null
+exec 6>&1
+
+# Name of the host.
+# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status,
+# so uname gets run too.
+ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`
+
+#
+# Initializations.
+#
+ac_default_prefix=/usr/local
+ac_clean_files=
+ac_config_libobj_dir=.
+LIBOBJS=
+cross_compiling=no
+subdirs=
+MFLAGS=
+MAKEFLAGS=
+
+# Identity of this package.
+PACKAGE_NAME='JRI'
+PACKAGE_TARNAME='jri'
+PACKAGE_VERSION='0.3'
+PACKAGE_STRING='JRI 0.3'
+PACKAGE_BUGREPORT='simon.urbanek@r-project.org'
+PACKAGE_URL=''
+
+ac_unique_file="src/jri.h"
+ac_subst_vars='LTLIBOBJS
+LIBOBJS
+DEFFLAGS
+RLD
+RINC
+CPICF
+JNIPREFIX
+JNISO
+JNILD
+JAVA_CFLAGS
+JAVA_INC
+JAVA_LIBS
+JAVA_LD_PATH
+JAVA_HOME
+JAR
+JAVAH
+JAVAC
+JAVA_PROG
+EGREP
+GREP
+CPP
+OBJEXT
+EXEEXT
+ac_ct_CC
+CPPFLAGS
+LDFLAGS
+CFLAGS
+CC
+R_INCLUDE_DIR
+R_DOC_DIR
+R_SHARE_DIR
+R_HOME
+host_os
+host_vendor
+host_cpu
+host
+build_os
+build_vendor
+build_cpu
+build
+target_alias
+host_alias
+build_alias
+LIBS
+ECHO_T
+ECHO_N
+ECHO_C
+DEFS
+mandir
+localedir
+libdir
+psdir
+pdfdir
+dvidir
+htmldir
+infodir
+docdir
+oldincludedir
+includedir
+localstatedir
+sharedstatedir
+sysconfdir
+datadir
+datarootdir
+libexecdir
+sbindir
+bindir
+program_transform_name
+prefix
+exec_prefix
+PACKAGE_URL
+PACKAGE_BUGREPORT
+PACKAGE_STRING
+PACKAGE_VERSION
+PACKAGE_TARNAME
+PACKAGE_NAME
+PATH_SEPARATOR
+SHELL'
+ac_subst_files=''
+ac_user_opts='
+enable_option_checking
+'
+      ac_precious_vars='build_alias
+host_alias
+target_alias
+CC
+CFLAGS
+LDFLAGS
+LIBS
+CPPFLAGS
+CPP'
+
+
+# Initialize some variables set by options.
+ac_init_help=
+ac_init_version=false
+ac_unrecognized_opts=
+ac_unrecognized_sep=
+# The variables have the same names as the options, with
+# dashes changed to underlines.
+cache_file=/dev/null
+exec_prefix=NONE
+no_create=
+no_recursion=
+prefix=NONE
+program_prefix=NONE
+program_suffix=NONE
+program_transform_name=s,x,x,
+silent=
+site=
+srcdir=
+verbose=
+x_includes=NONE
+x_libraries=NONE
+
+# Installation directory options.
+# These are left unexpanded so users can "make install exec_prefix=/foo"
+# and all the variables that are supposed to be based on exec_prefix
+# by default will actually change.
+# Use braces instead of parens because sh, perl, etc. also accept them.
+# (The list follows the same order as the GNU Coding Standards.)
+bindir='${exec_prefix}/bin'
+sbindir='${exec_prefix}/sbin'
+libexecdir='${exec_prefix}/libexec'
+datarootdir='${prefix}/share'
+datadir='${datarootdir}'
+sysconfdir='${prefix}/etc'
+sharedstatedir='${prefix}/com'
+localstatedir='${prefix}/var'
+includedir='${prefix}/include'
+oldincludedir='/usr/include'
+docdir='${datarootdir}/doc/${PACKAGE_TARNAME}'
+infodir='${datarootdir}/info'
+htmldir='${docdir}'
+dvidir='${docdir}'
+pdfdir='${docdir}'
+psdir='${docdir}'
+libdir='${exec_prefix}/lib'
+localedir='${datarootdir}/locale'
+mandir='${datarootdir}/man'
+
+ac_prev=
+ac_dashdash=
+for ac_option
+do
+  # If the previous option needs an argument, assign it.
+  if test -n "$ac_prev"; then
+    eval $ac_prev=\$ac_option
+    ac_prev=
+    continue
+  fi
+
+  case $ac_option in
+  *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;;
+  *=)   ac_optarg= ;;
+  *)    ac_optarg=yes ;;
+  esac
+
+  # Accept the important Cygnus configure options, so we can diagnose typos.
+
+  case $ac_dashdash$ac_option in
+  --)
+    ac_dashdash=yes ;;
+
+  -bindir | --bindir | --bindi | --bind | --bin | --bi)
+    ac_prev=bindir ;;
+  -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
+    bindir=$ac_optarg ;;
+
+  -build | --build | --buil | --bui | --bu)
+    ac_prev=build_alias ;;
+  -build=* | --build=* | --buil=* | --bui=* | --bu=*)
+    build_alias=$ac_optarg ;;
+
+  -cache-file | --cache-file | --cache-fil | --cache-fi \
+  | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
+    ac_prev=cache_file ;;
+  -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
+  | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
+    cache_file=$ac_optarg ;;
+
+  --config-cache | -C)
+    cache_file=config.cache ;;
+
+  -datadir | --datadir | --datadi | --datad)
+    ac_prev=datadir ;;
+  -datadir=* | --datadir=* | --datadi=* | --datad=*)
+    datadir=$ac_optarg ;;
+
+  -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \
+  | --dataroo | --dataro | --datar)
+    ac_prev=datarootdir ;;
+  -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \
+  | --dataroot=* | --dataroo=* | --dataro=* | --datar=*)
+    datarootdir=$ac_optarg ;;
+
+  -disable-* | --disable-*)
+    ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error $? "invalid feature name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"enable_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval enable_$ac_useropt=no ;;
+
+  -docdir | --docdir | --docdi | --doc | --do)
+    ac_prev=docdir ;;
+  -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*)
+    docdir=$ac_optarg ;;
+
+  -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv)
+    ac_prev=dvidir ;;
+  -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*)
+    dvidir=$ac_optarg ;;
+
+  -enable-* | --enable-*)
+    ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error $? "invalid feature name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"enable_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval enable_$ac_useropt=\$ac_optarg ;;
+
+  -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
+  | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
+  | --exec | --exe | --ex)
+    ac_prev=exec_prefix ;;
+  -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
+  | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
+  | --exec=* | --exe=* | --ex=*)
+    exec_prefix=$ac_optarg ;;
+
+  -gas | --gas | --ga | --g)
+    # Obsolete; use --with-gas.
+    with_gas=yes ;;
+
+  -help | --help | --hel | --he | -h)
+    ac_init_help=long ;;
+  -help=r* | --help=r* | --hel=r* | --he=r* | -hr*)
+    ac_init_help=recursive ;;
+  -help=s* | --help=s* | --hel=s* | --he=s* | -hs*)
+    ac_init_help=short ;;
+
+  -host | --host | --hos | --ho)
+    ac_prev=host_alias ;;
+  -host=* | --host=* | --hos=* | --ho=*)
+    host_alias=$ac_optarg ;;
+
+  -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht)
+    ac_prev=htmldir ;;
+  -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \
+  | --ht=*)
+    htmldir=$ac_optarg ;;
+
+  -includedir | --includedir | --includedi | --included | --include \
+  | --includ | --inclu | --incl | --inc)
+    ac_prev=includedir ;;
+  -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \
+  | --includ=* | --inclu=* | --incl=* | --inc=*)
+    includedir=$ac_optarg ;;
+
+  -infodir | --infodir | --infodi | --infod | --info | --inf)
+    ac_prev=infodir ;;
+  -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
+    infodir=$ac_optarg ;;
+
+  -libdir | --libdir | --libdi | --libd)
+    ac_prev=libdir ;;
+  -libdir=* | --libdir=* | --libdi=* | --libd=*)
+    libdir=$ac_optarg ;;
+
+  -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \
+  | --libexe | --libex | --libe)
+    ac_prev=libexecdir ;;
+  -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \
+  | --libexe=* | --libex=* | --libe=*)
+    libexecdir=$ac_optarg ;;
+
+  -localedir | --localedir | --localedi | --localed | --locale)
+    ac_prev=localedir ;;
+  -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*)
+    localedir=$ac_optarg ;;
+
+  -localstatedir | --localstatedir | --localstatedi | --localstated \
+  | --localstate | --localstat | --localsta | --localst | --locals)
+    ac_prev=localstatedir ;;
+  -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
+  | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*)
+    localstatedir=$ac_optarg ;;
+
+  -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
+    ac_prev=mandir ;;
+  -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
+    mandir=$ac_optarg ;;
+
+  -nfp | --nfp | --nf)
+    # Obsolete; use --without-fp.
+    with_fp=no ;;
+
+  -no-create | --no-create | --no-creat | --no-crea | --no-cre \
+  | --no-cr | --no-c | -n)
+    no_create=yes ;;
+
+  -no-recursion | --no-recursion | --no-recursio | --no-recursi \
+  | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)
+    no_recursion=yes ;;
+
+  -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \
+  | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \
+  | --oldin | --oldi | --old | --ol | --o)
+    ac_prev=oldincludedir ;;
+  -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
+  | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
+  | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
+    oldincludedir=$ac_optarg ;;
+
+  -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
+    ac_prev=prefix ;;
+  -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
+    prefix=$ac_optarg ;;
+
+  -program-prefix | --program-prefix | --program-prefi | --program-pref \
+  | --program-pre | --program-pr | --program-p)
+    ac_prev=program_prefix ;;
+  -program-prefix=* | --program-prefix=* | --program-prefi=* \
+  | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)
+    program_prefix=$ac_optarg ;;
+
+  -program-suffix | --program-suffix | --program-suffi | --program-suff \
+  | --program-suf | --program-su | --program-s)
+    ac_prev=program_suffix ;;
+  -program-suffix=* | --program-suffix=* | --program-suffi=* \
+  | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)
+    program_suffix=$ac_optarg ;;
+
+  -program-transform-name | --program-transform-name \
+  | --program-transform-nam | --program-transform-na \
+  | --program-transform-n | --program-transform- \
+  | --program-transform | --program-transfor \
+  | --program-transfo | --program-transf \
+  | --program-trans | --program-tran \
+  | --progr-tra | --program-tr | --program-t)
+    ac_prev=program_transform_name ;;
+  -program-transform-name=* | --program-transform-name=* \
+  | --program-transform-nam=* | --program-transform-na=* \
+  | --program-transform-n=* | --program-transform-=* \
+  | --program-transform=* | --program-transfor=* \
+  | --program-transfo=* | --program-transf=* \
+  | --program-trans=* | --program-tran=* \
+  | --progr-tra=* | --program-tr=* | --program-t=*)
+    program_transform_name=$ac_optarg ;;
+
+  -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd)
+    ac_prev=pdfdir ;;
+  -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*)
+    pdfdir=$ac_optarg ;;
+
+  -psdir | --psdir | --psdi | --psd | --ps)
+    ac_prev=psdir ;;
+  -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*)
+    psdir=$ac_optarg ;;
+
+  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+  | -silent | --silent | --silen | --sile | --sil)
+    silent=yes ;;
+
+  -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
+    ac_prev=sbindir ;;
+  -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
+  | --sbi=* | --sb=*)
+    sbindir=$ac_optarg ;;
+
+  -sharedstatedir | --sharedstatedir | --sharedstatedi \
+  | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
+  | --sharedst | --shareds | --shared | --share | --shar \
+  | --sha | --sh)
+    ac_prev=sharedstatedir ;;
+  -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \
+  | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
+  | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
+  | --sha=* | --sh=*)
+    sharedstatedir=$ac_optarg ;;
+
+  -site | --site | --sit)
+    ac_prev=site ;;
+  -site=* | --site=* | --sit=*)
+    site=$ac_optarg ;;
+
+  -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
+    ac_prev=srcdir ;;
+  -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
+    srcdir=$ac_optarg ;;
+
+  -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \
+  | --syscon | --sysco | --sysc | --sys | --sy)
+    ac_prev=sysconfdir ;;
+  -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \
+  | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)
+    sysconfdir=$ac_optarg ;;
+
+  -target | --target | --targe | --targ | --tar | --ta | --t)
+    ac_prev=target_alias ;;
+  -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
+    target_alias=$ac_optarg ;;
+
+  -v | -verbose | --verbose | --verbos | --verbo | --verb)
+    verbose=yes ;;
+
+  -version | --version | --versio | --versi | --vers | -V)
+    ac_init_version=: ;;
+
+  -with-* | --with-*)
+    ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error $? "invalid package name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"with_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval with_$ac_useropt=\$ac_optarg ;;
+
+  -without-* | --without-*)
+    ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error $? "invalid package name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"with_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval with_$ac_useropt=no ;;
+
+  --x)
+    # Obsolete; use --with-x.
+    with_x=yes ;;
+
+  -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \
+  | --x-incl | --x-inc | --x-in | --x-i)
+    ac_prev=x_includes ;;
+  -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \
+  | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)
+    x_includes=$ac_optarg ;;
+
+  -x-libraries | --x-libraries | --x-librarie | --x-librari \
+  | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)
+    ac_prev=x_libraries ;;
+  -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \
+  | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
+    x_libraries=$ac_optarg ;;
+
+  -*) as_fn_error $? "unrecognized option: \`$ac_option'
+Try \`$0 --help' for more information"
+    ;;
+
+  *=*)
+    ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='`
+    # Reject names that are not valid shell variable names.
+    case $ac_envvar in #(
+      '' | [0-9]* | *[!_$as_cr_alnum]* )
+      as_fn_error $? "invalid variable name: \`$ac_envvar'" ;;
+    esac
+    eval $ac_envvar=\$ac_optarg
+    export $ac_envvar ;;
+
+  *)
+    # FIXME: should be removed in autoconf 3.0.
+    $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2
+    expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2
+    : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}"
+    ;;
+
+  esac
+done
+
+if test -n "$ac_prev"; then
+  ac_option=--`echo $ac_prev | sed 's/_/-/g'`
+  as_fn_error $? "missing argument to $ac_option"
+fi
+
+if test -n "$ac_unrecognized_opts"; then
+  case $enable_option_checking in
+    no) ;;
+    fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;;
+    *)     $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;;
+  esac
+fi
+
+# Check all directory arguments for consistency.
+for ac_var in	exec_prefix prefix bindir sbindir libexecdir datarootdir \
+		datadir sysconfdir sharedstatedir localstatedir includedir \
+		oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
+		libdir localedir mandir
+do
+  eval ac_val=\$$ac_var
+  # Remove trailing slashes.
+  case $ac_val in
+    */ )
+      ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'`
+      eval $ac_var=\$ac_val;;
+  esac
+  # Be sure to have absolute directory names.
+  case $ac_val in
+    [\\/$]* | ?:[\\/]* )  continue;;
+    NONE | '' ) case $ac_var in *prefix ) continue;; esac;;
+  esac
+  as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val"
+done
+
+# There might be people who depend on the old broken behavior: `$host'
+# used to hold the argument of --host etc.
+# FIXME: To remove some day.
+build=$build_alias
+host=$host_alias
+target=$target_alias
+
+# FIXME: To remove some day.
+if test "x$host_alias" != x; then
+  if test "x$build_alias" = x; then
+    cross_compiling=maybe
+  elif test "x$build_alias" != "x$host_alias"; then
+    cross_compiling=yes
+  fi
+fi
+
+ac_tool_prefix=
+test -n "$host_alias" && ac_tool_prefix=$host_alias-
+
+test "$silent" = yes && exec 6>/dev/null
+
+
+ac_pwd=`pwd` && test -n "$ac_pwd" &&
+ac_ls_di=`ls -di .` &&
+ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` ||
+  as_fn_error $? "working directory cannot be determined"
+test "X$ac_ls_di" = "X$ac_pwd_ls_di" ||
+  as_fn_error $? "pwd does not report name of working directory"
+
+
+# Find the source files, if location was not specified.
+if test -z "$srcdir"; then
+  ac_srcdir_defaulted=yes
+  # Try the directory containing this script, then the parent directory.
+  ac_confdir=`$as_dirname -- "$as_myself" ||
+$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_myself" : 'X\(//\)[^/]' \| \
+	 X"$as_myself" : 'X\(//\)$' \| \
+	 X"$as_myself" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_myself" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+  srcdir=$ac_confdir
+  if test ! -r "$srcdir/$ac_unique_file"; then
+    srcdir=..
+  fi
+else
+  ac_srcdir_defaulted=no
+fi
+if test ! -r "$srcdir/$ac_unique_file"; then
+  test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .."
+  as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir"
+fi
+ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work"
+ac_abs_confdir=`(
+	cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg"
+	pwd)`
+# When building in place, set srcdir=.
+if test "$ac_abs_confdir" = "$ac_pwd"; then
+  srcdir=.
+fi
+# Remove unnecessary trailing slashes from srcdir.
+# Double slashes in file names in object file debugging info
+# mess up M-x gdb in Emacs.
+case $srcdir in
+*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;;
+esac
+for ac_var in $ac_precious_vars; do
+  eval ac_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_env_${ac_var}_value=\$${ac_var}
+  eval ac_cv_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_cv_env_${ac_var}_value=\$${ac_var}
+done
+
+#
+# Report the --help message.
+#
+if test "$ac_init_help" = "long"; then
+  # Omit some internal or obsolete options to make the list less imposing.
+  # This message is too long to be a string in the A/UX 3.1 sh.
+  cat <<_ACEOF
+\`configure' configures JRI 0.3 to adapt to many kinds of systems.
+
+Usage: $0 [OPTION]... [VAR=VALUE]...
+
+To assign environment variables (e.g., CC, CFLAGS...), specify them as
+VAR=VALUE.  See below for descriptions of some of the useful variables.
+
+Defaults for the options are specified in brackets.
+
+Configuration:
+  -h, --help              display this help and exit
+      --help=short        display options specific to this package
+      --help=recursive    display the short help of all the included packages
+  -V, --version           display version information and exit
+  -q, --quiet, --silent   do not print \`checking ...' messages
+      --cache-file=FILE   cache test results in FILE [disabled]
+  -C, --config-cache      alias for \`--cache-file=config.cache'
+  -n, --no-create         do not create output files
+      --srcdir=DIR        find the sources in DIR [configure dir or \`..']
+
+Installation directories:
+  --prefix=PREFIX         install architecture-independent files in PREFIX
+                          [$ac_default_prefix]
+  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
+                          [PREFIX]
+
+By default, \`make install' will install all the files in
+\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc.  You can specify
+an installation prefix other than \`$ac_default_prefix' using \`--prefix',
+for instance \`--prefix=\$HOME'.
+
+For better control, use the options below.
+
+Fine tuning of the installation directories:
+  --bindir=DIR            user executables [EPREFIX/bin]
+  --sbindir=DIR           system admin executables [EPREFIX/sbin]
+  --libexecdir=DIR        program executables [EPREFIX/libexec]
+  --sysconfdir=DIR        read-only single-machine data [PREFIX/etc]
+  --sharedstatedir=DIR    modifiable architecture-independent data [PREFIX/com]
+  --localstatedir=DIR     modifiable single-machine data [PREFIX/var]
+  --libdir=DIR            object code libraries [EPREFIX/lib]
+  --includedir=DIR        C header files [PREFIX/include]
+  --oldincludedir=DIR     C header files for non-gcc [/usr/include]
+  --datarootdir=DIR       read-only arch.-independent data root [PREFIX/share]
+  --datadir=DIR           read-only architecture-independent data [DATAROOTDIR]
+  --infodir=DIR           info documentation [DATAROOTDIR/info]
+  --localedir=DIR         locale-dependent data [DATAROOTDIR/locale]
+  --mandir=DIR            man documentation [DATAROOTDIR/man]
+  --docdir=DIR            documentation root [DATAROOTDIR/doc/jri]
+  --htmldir=DIR           html documentation [DOCDIR]
+  --dvidir=DIR            dvi documentation [DOCDIR]
+  --pdfdir=DIR            pdf documentation [DOCDIR]
+  --psdir=DIR             ps documentation [DOCDIR]
+_ACEOF
+
+  cat <<\_ACEOF
+
+System types:
+  --build=BUILD     configure for building on BUILD [guessed]
+  --host=HOST       cross-compile to build programs to run on HOST [BUILD]
+_ACEOF
+fi
+
+if test -n "$ac_init_help"; then
+  case $ac_init_help in
+     short | recursive ) echo "Configuration of JRI 0.3:";;
+   esac
+  cat <<\_ACEOF
+
+Some influential environment variables:
+  CC          C compiler command
+  CFLAGS      C compiler flags
+  LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries in a
+              nonstandard directory <lib dir>
+  LIBS        libraries to pass to the linker, e.g. -l<library>
+  CPPFLAGS    (Objective) C/C++ preprocessor flags, e.g. -I<include dir> if
+              you have headers in a nonstandard directory <include dir>
+  CPP         C preprocessor
+
+Use these variables to override the choices made by `configure' or to help
+it to find libraries and programs with nonstandard names/locations.
+
+Report bugs to <simon.urbanek@r-project.org>.
+_ACEOF
+ac_status=$?
+fi
+
+if test "$ac_init_help" = "recursive"; then
+  # If there are subdirs, report their specific --help.
+  for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
+    test -d "$ac_dir" ||
+      { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } ||
+      continue
+    ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+    cd "$ac_dir" || { ac_status=$?; continue; }
+    # Check for guested configure.
+    if test -f "$ac_srcdir/configure.gnu"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure.gnu" --help=recursive
+    elif test -f "$ac_srcdir/configure"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure" --help=recursive
+    else
+      $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
+    fi || ac_status=$?
+    cd "$ac_pwd" || { ac_status=$?; break; }
+  done
+fi
+
+test -n "$ac_init_help" && exit $ac_status
+if $ac_init_version; then
+  cat <<\_ACEOF
+JRI configure 0.3
+generated by GNU Autoconf 2.69
+
+Copyright (C) 2012 Free Software Foundation, Inc.
+This configure script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it.
+_ACEOF
+  exit
+fi
+
+## ------------------------ ##
+## Autoconf initialization. ##
+## ------------------------ ##
+
+# ac_fn_c_try_compile LINENO
+# --------------------------
+# Try to compile conftest.$ac_ext, and return whether this succeeded.
+ac_fn_c_try_compile ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  rm -f conftest.$ac_objext
+  if { { ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compile") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_retval=1
+fi
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_compile
+
+# ac_fn_c_try_cpp LINENO
+# ----------------------
+# Try to preprocess conftest.$ac_ext, and return whether this succeeded.
+ac_fn_c_try_cpp ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  if { { ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } > conftest.i && {
+	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       }; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+    ac_retval=1
+fi
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_cpp
+
+# ac_fn_c_try_run LINENO
+# ----------------------
+# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes
+# that executables *can* be run.
+ac_fn_c_try_run ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  if { { ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && { ac_try='./conftest$ac_exeext'
+  { { case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_try") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; }; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: program exited with status $ac_status" >&5
+       $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+       ac_retval=$ac_status
+fi
+  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_run
+
+# ac_fn_c_try_link LINENO
+# -----------------------
+# Try to link conftest.$ac_ext, and return whether this succeeded.
+ac_fn_c_try_link ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  rm -f conftest.$ac_objext conftest$ac_exeext
+  if { { ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest$ac_exeext && {
+	 test "$cross_compiling" = yes ||
+	 test -x conftest$ac_exeext
+       }; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_retval=1
+fi
+  # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information
+  # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would
+  # interfere with the next link command; also delete a directory that is
+  # left behind by Apple's compiler.  We do this before executing the actions.
+  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_link
+cat >config.log <<_ACEOF
+This file contains any messages produced by compilers while
+running configure, to aid debugging if configure makes a mistake.
+
+It was created by JRI $as_me 0.3, which was
+generated by GNU Autoconf 2.69.  Invocation command line was
+
+  $ $0 $@
+
+_ACEOF
+exec 5>>config.log
+{
+cat <<_ASUNAME
+## --------- ##
+## Platform. ##
+## --------- ##
+
+hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`
+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 || echo unknown`
+/bin/uname -X     = `(/bin/uname -X) 2>/dev/null     || echo unknown`
+
+/bin/arch              = `(/bin/arch) 2>/dev/null              || echo unknown`
+/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null       || echo unknown`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
+/usr/bin/hostinfo      = `(/usr/bin/hostinfo) 2>/dev/null      || echo unknown`
+/bin/machine           = `(/bin/machine) 2>/dev/null           || echo unknown`
+/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null       || echo unknown`
+/bin/universe          = `(/bin/universe) 2>/dev/null          || echo unknown`
+
+_ASUNAME
+
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    $as_echo "PATH: $as_dir"
+  done
+IFS=$as_save_IFS
+
+} >&5
+
+cat >&5 <<_ACEOF
+
+
+## ----------- ##
+## Core tests. ##
+## ----------- ##
+
+_ACEOF
+
+
+# Keep a trace of the command line.
+# Strip out --no-create and --no-recursion so they do not pile up.
+# Strip out --silent because we don't want to record it for future runs.
+# Also quote any args containing shell meta-characters.
+# Make two passes to allow for proper duplicate-argument suppression.
+ac_configure_args=
+ac_configure_args0=
+ac_configure_args1=
+ac_must_keep_next=false
+for ac_pass in 1 2
+do
+  for ac_arg
+  do
+    case $ac_arg in
+    -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;;
+    -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+    | -silent | --silent | --silen | --sile | --sil)
+      continue ;;
+    *\'*)
+      ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    esac
+    case $ac_pass in
+    1) as_fn_append ac_configure_args0 " '$ac_arg'" ;;
+    2)
+      as_fn_append ac_configure_args1 " '$ac_arg'"
+      if test $ac_must_keep_next = true; then
+	ac_must_keep_next=false # Got value, back to normal.
+      else
+	case $ac_arg in
+	  *=* | --config-cache | -C | -disable-* | --disable-* \
+	  | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \
+	  | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \
+	  | -with-* | --with-* | -without-* | --without-* | --x)
+	    case "$ac_configure_args0 " in
+	      "$ac_configure_args1"*" '$ac_arg' "* ) continue ;;
+	    esac
+	    ;;
+	  -* ) ac_must_keep_next=true ;;
+	esac
+      fi
+      as_fn_append ac_configure_args " '$ac_arg'"
+      ;;
+    esac
+  done
+done
+{ ac_configure_args0=; unset ac_configure_args0;}
+{ ac_configure_args1=; unset ac_configure_args1;}
+
+# When interrupted or exit'd, cleanup temporary files, and complete
+# config.log.  We remove comments because anyway the quotes in there
+# would cause problems or look ugly.
+# WARNING: Use '\'' to represent an apostrophe within the trap.
+# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug.
+trap 'exit_status=$?
+  # Save into config.log some information that might help in debugging.
+  {
+    echo
+
+    $as_echo "## ---------------- ##
+## Cache variables. ##
+## ---------------- ##"
+    echo
+    # The following way of writing the cache mishandles newlines in values,
+(
+  for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
+$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
+      *) { eval $ac_var=; unset $ac_var;} ;;
+      esac ;;
+    esac
+  done
+  (set) 2>&1 |
+    case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
+      sed -n \
+	"s/'\''/'\''\\\\'\'''\''/g;
+	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p"
+      ;; #(
+    *)
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+      ;;
+    esac |
+    sort
+)
+    echo
+
+    $as_echo "## ----------------- ##
+## Output variables. ##
+## ----------------- ##"
+    echo
+    for ac_var in $ac_subst_vars
+    do
+      eval ac_val=\$$ac_var
+      case $ac_val in
+      *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+      esac
+      $as_echo "$ac_var='\''$ac_val'\''"
+    done | sort
+    echo
+
+    if test -n "$ac_subst_files"; then
+      $as_echo "## ------------------- ##
+## File substitutions. ##
+## ------------------- ##"
+      echo
+      for ac_var in $ac_subst_files
+      do
+	eval ac_val=\$$ac_var
+	case $ac_val in
+	*\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+	esac
+	$as_echo "$ac_var='\''$ac_val'\''"
+      done | sort
+      echo
+    fi
+
+    if test -s confdefs.h; then
+      $as_echo "## ----------- ##
+## confdefs.h. ##
+## ----------- ##"
+      echo
+      cat confdefs.h
+      echo
+    fi
+    test "$ac_signal" != 0 &&
+      $as_echo "$as_me: caught signal $ac_signal"
+    $as_echo "$as_me: exit $exit_status"
+  } >&5
+  rm -f core *.core core.conftest.* &&
+    rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
+    exit $exit_status
+' 0
+for ac_signal in 1 2 13 15; do
+  trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal
+done
+ac_signal=0
+
+# confdefs.h avoids OS command line length limits that DEFS can exceed.
+rm -f -r conftest* confdefs.h
+
+$as_echo "/* confdefs.h */" > confdefs.h
+
+# Predefined preprocessor variables.
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_NAME "$PACKAGE_NAME"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_TARNAME "$PACKAGE_TARNAME"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_VERSION "$PACKAGE_VERSION"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_STRING "$PACKAGE_STRING"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_URL "$PACKAGE_URL"
+_ACEOF
+
+
+# Let the site file select an alternate cache file if it wants to.
+# Prefer an explicitly selected file to automatically selected ones.
+ac_site_file1=NONE
+ac_site_file2=NONE
+if test -n "$CONFIG_SITE"; then
+  # We do not want a PATH search for config.site.
+  case $CONFIG_SITE in #((
+    -*)  ac_site_file1=./$CONFIG_SITE;;
+    */*) ac_site_file1=$CONFIG_SITE;;
+    *)   ac_site_file1=./$CONFIG_SITE;;
+  esac
+elif test "x$prefix" != xNONE; then
+  ac_site_file1=$prefix/share/config.site
+  ac_site_file2=$prefix/etc/config.site
+else
+  ac_site_file1=$ac_default_prefix/share/config.site
+  ac_site_file2=$ac_default_prefix/etc/config.site
+fi
+for ac_site_file in "$ac_site_file1" "$ac_site_file2"
+do
+  test "x$ac_site_file" = xNONE && continue
+  if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5
+$as_echo "$as_me: loading site script $ac_site_file" >&6;}
+    sed 's/^/| /' "$ac_site_file" >&5
+    . "$ac_site_file" \
+      || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "failed to load site script $ac_site_file
+See \`config.log' for more details" "$LINENO" 5; }
+  fi
+done
+
+if test -r "$cache_file"; then
+  # Some versions of bash will fail to source /dev/null (special files
+  # actually), so we avoid doing that.  DJGPP emulates it as a regular file.
+  if test /dev/null != "$cache_file" && test -f "$cache_file"; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5
+$as_echo "$as_me: loading cache $cache_file" >&6;}
+    case $cache_file in
+      [\\/]* | ?:[\\/]* ) . "$cache_file";;
+      *)                      . "./$cache_file";;
+    esac
+  fi
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5
+$as_echo "$as_me: creating cache $cache_file" >&6;}
+  >$cache_file
+fi
+
+# Check that the precious variables saved in the cache have kept the same
+# value.
+ac_cache_corrupted=false
+for ac_var in $ac_precious_vars; do
+  eval ac_old_set=\$ac_cv_env_${ac_var}_set
+  eval ac_new_set=\$ac_env_${ac_var}_set
+  eval ac_old_val=\$ac_cv_env_${ac_var}_value
+  eval ac_new_val=\$ac_env_${ac_var}_value
+  case $ac_old_set,$ac_new_set in
+    set,)
+      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
+$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
+      ac_cache_corrupted=: ;;
+    ,set)
+      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5
+$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
+      ac_cache_corrupted=: ;;
+    ,);;
+    *)
+      if test "x$ac_old_val" != "x$ac_new_val"; then
+	# differences in whitespace do not lead to failure.
+	ac_old_val_w=`echo x $ac_old_val`
+	ac_new_val_w=`echo x $ac_new_val`
+	if test "$ac_old_val_w" != "$ac_new_val_w"; then
+	  { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5
+$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
+	  ac_cache_corrupted=:
+	else
+	  { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5
+$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;}
+	  eval $ac_var=\$ac_old_val
+	fi
+	{ $as_echo "$as_me:${as_lineno-$LINENO}:   former value:  \`$ac_old_val'" >&5
+$as_echo "$as_me:   former value:  \`$ac_old_val'" >&2;}
+	{ $as_echo "$as_me:${as_lineno-$LINENO}:   current value: \`$ac_new_val'" >&5
+$as_echo "$as_me:   current value: \`$ac_new_val'" >&2;}
+      fi;;
+  esac
+  # Pass precious variables to config.status.
+  if test "$ac_new_set" = set; then
+    case $ac_new_val in
+    *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
+    *) ac_arg=$ac_var=$ac_new_val ;;
+    esac
+    case " $ac_configure_args " in
+      *" '$ac_arg' "*) ;; # Avoid dups.  Use of quotes ensures accuracy.
+      *) as_fn_append ac_configure_args " '$ac_arg'" ;;
+    esac
+  fi
+done
+if $ac_cache_corrupted; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+  { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5
+$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;}
+  as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5
+fi
+## -------------------- ##
+## Main body of script. ##
+## -------------------- ##
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+
+ac_config_headers="$ac_config_headers src/config.h"
+
+ac_aux_dir=
+for ac_dir in tools "$srcdir"/tools; do
+  if test -f "$ac_dir/install-sh"; then
+    ac_aux_dir=$ac_dir
+    ac_install_sh="$ac_aux_dir/install-sh -c"
+    break
+  elif test -f "$ac_dir/install.sh"; then
+    ac_aux_dir=$ac_dir
+    ac_install_sh="$ac_aux_dir/install.sh -c"
+    break
+  elif test -f "$ac_dir/shtool"; then
+    ac_aux_dir=$ac_dir
+    ac_install_sh="$ac_aux_dir/shtool install -c"
+    break
+  fi
+done
+if test -z "$ac_aux_dir"; then
+  as_fn_error $? "cannot find install-sh, install.sh, or shtool in tools \"$srcdir\"/tools" "$LINENO" 5
+fi
+
+# These three variables are undocumented and unsupported,
+# and are intended to be withdrawn in a future Autoconf release.
+# They can cause serious problems if a builder's source tree is in a directory
+# whose full name contains unusual characters.
+ac_config_guess="$SHELL $ac_aux_dir/config.guess"  # Please don't use this var.
+ac_config_sub="$SHELL $ac_aux_dir/config.sub"  # Please don't use this var.
+ac_configure="$SHELL $ac_aux_dir/configure"  # Please don't use this var.
+
+
+
+# Make sure we can run config.sub.
+$SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 ||
+  as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5
+$as_echo_n "checking build system type... " >&6; }
+if ${ac_cv_build+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_build_alias=$build_alias
+test "x$ac_build_alias" = x &&
+  ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"`
+test "x$ac_build_alias" = x &&
+  as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5
+ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` ||
+  as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5
+$as_echo "$ac_cv_build" >&6; }
+case $ac_cv_build in
+*-*-*) ;;
+*) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;;
+esac
+build=$ac_cv_build
+ac_save_IFS=$IFS; IFS='-'
+set x $ac_cv_build
+shift
+build_cpu=$1
+build_vendor=$2
+shift; shift
+# Remember, the first character of IFS is used to create $*,
+# except with old shells:
+build_os=$*
+IFS=$ac_save_IFS
+case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5
+$as_echo_n "checking host system type... " >&6; }
+if ${ac_cv_host+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test "x$host_alias" = x; then
+  ac_cv_host=$ac_cv_build
+else
+  ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` ||
+    as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5
+fi
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5
+$as_echo "$ac_cv_host" >&6; }
+case $ac_cv_host in
+*-*-*) ;;
+*) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;;
+esac
+host=$ac_cv_host
+ac_save_IFS=$IFS; IFS='-'
+set x $ac_cv_host
+shift
+host_cpu=$1
+host_vendor=$2
+shift; shift
+# Remember, the first character of IFS is used to create $*,
+# except with old shells:
+host_os=$*
+IFS=$ac_save_IFS
+case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac
+
+
+
+# find R home
+: ${R_HOME=`R RHOME`}
+if test -z "${R_HOME}"; then
+  echo "could not determine R_HOME"
+  exit 1
+fi
+# we attempt to use the same compiler as R did
+RBIN="${R_HOME}/bin/R"
+R_CC=`"${RBIN}" CMD config CC`
+R_CPP=`"${RBIN}" CMD config CPP`
+R_CFLAGS=`"${RBIN}" CMD config CFLAGS`
+
+
+# find R_SHARE_DIR
+: ${R_SHARE_DIR=`"${RBIN}" CMD sh -c 'echo $R_SHARE_DIR'`}
+if test -z "${R_SHARE_DIR}"; then
+  echo "could not determine R_SHARE_DIR"
+  exit 1
+fi
+
+# find R_DOC_DIR
+: ${R_DOC_DIR=`"${RBIN}" CMD sh -c 'echo $R_DOC_DIR'`}
+if test -z "${R_DOC_DIR}"; then
+  echo "could not determine R_DOC_DIR"
+  exit 1
+fi
+
+# find R_INCLUDE_DIR
+: ${R_INCLUDE_DIR=`"${RBIN}" CMD sh -c 'echo $R_INCLUDE_DIR'`}
+if test -z "${R_INCLUDE_DIR}"; then
+  echo "could not determine R_INCLUDE_DIR"
+  exit 1
+fi
+
+# if user did not specify CC then we use R's settings.
+# if CC was set then user is responsible for CFLAGS as well!
+if test -z "${CC}"; then
+   CC="${R_CC}"
+   CPP="${R_CPP}"
+   CFLAGS="${R_CFLAGS}"
+fi
+
+RINC=`"${RBIN}" CMD config --cppflags`
+RLD=`"${RBIN}" CMD config --ldflags`
+
+if test -z "$RLD"; then
+   as_fn_error $? "R was not compiled with --enable-R-shlib
+
+*** You must have libR.so or equivalent in order to use JRI ***
+" "$LINENO" 5
+fi
+
+
+
+
+
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args.
+set dummy ${ac_tool_prefix}gcc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_CC="${ac_tool_prefix}gcc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_CC"; then
+  ac_ct_CC=$CC
+  # Extract the first word of "gcc", so it can be a program name with args.
+set dummy gcc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_CC"; then
+  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_ac_ct_CC="gcc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+$as_echo "$ac_ct_CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
+else
+  CC="$ac_cv_prog_CC"
+fi
+
+if test -z "$CC"; then
+          if test -n "$ac_tool_prefix"; then
+    # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
+set dummy ${ac_tool_prefix}cc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_CC="${ac_tool_prefix}cc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  fi
+fi
+if test -z "$CC"; then
+  # Extract the first word of "cc", so it can be a program name with args.
+set dummy cc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+  ac_prog_rejected=no
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
+       ac_prog_rejected=yes
+       continue
+     fi
+    ac_cv_prog_CC="cc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+if test $ac_prog_rejected = yes; then
+  # We found a bogon in the path, so make sure we never use it.
+  set dummy $ac_cv_prog_CC
+  shift
+  if test $# != 0; then
+    # We chose a different compiler from the bogus one.
+    # However, it has the same basename, so the bogon will be chosen
+    # first if we set CC to just the basename; use the full file name.
+    shift
+    ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@"
+  fi
+fi
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$CC"; then
+  if test -n "$ac_tool_prefix"; then
+  for ac_prog in cl.exe
+  do
+    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+    test -n "$CC" && break
+  done
+fi
+if test -z "$CC"; then
+  ac_ct_CC=$CC
+  for ac_prog in cl.exe
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_CC"; then
+  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_ac_ct_CC="$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+$as_echo "$ac_ct_CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$ac_ct_CC" && break
+done
+
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
+fi
+
+fi
+
+
+test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "no acceptable C compiler found in \$PATH
+See \`config.log' for more details" "$LINENO" 5; }
+
+# Provide some information about the compiler.
+$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
+set X $ac_compile
+ac_compiler=$2
+for ac_option in --version -v -V -qversion; do
+  { { ac_try="$ac_compiler $ac_option >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compiler $ac_option >&5") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    sed '10a\
+... rest of stderr output deleted ...
+         10q' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+  fi
+  rm -f conftest.er1 conftest.err
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+done
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+ac_clean_files_save=$ac_clean_files
+ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out"
+# Try to create an executable without -o first, disregard a.out.
+# It will help us diagnose broken compilers, and finding out an intuition
+# of exeext.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5
+$as_echo_n "checking whether the C compiler works... " >&6; }
+ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
+
+# The possible output files:
+ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*"
+
+ac_rmfiles=
+for ac_file in $ac_files
+do
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
+    * ) ac_rmfiles="$ac_rmfiles $ac_file";;
+  esac
+done
+rm -f $ac_rmfiles
+
+if { { ac_try="$ac_link_default"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link_default") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then :
+  # Autoconf-2.13 could set the ac_cv_exeext variable to `no'.
+# So ignore a value of `no', otherwise this would lead to `EXEEXT = no'
+# in a Makefile.  We should not override ac_cv_exeext if it was cached,
+# so that the user can short-circuit this test for compilers unknown to
+# Autoconf.
+for ac_file in $ac_files ''
+do
+  test -f "$ac_file" || continue
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj )
+	;;
+    [ab].out )
+	# We found the default executable, but exeext='' is most
+	# certainly right.
+	break;;
+    *.* )
+	if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no;
+	then :; else
+	   ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+	fi
+	# We set ac_cv_exeext here because the later test for it is not
+	# safe: cross compilers may not add the suffix if given an `-o'
+	# argument, so we may need to know it at that point already.
+	# Even if this section looks crufty: it has the advantage of
+	# actually working.
+	break;;
+    * )
+	break;;
+  esac
+done
+test "$ac_cv_exeext" = no && ac_cv_exeext=
+
+else
+  ac_file=''
+fi
+if test -z "$ac_file"; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+$as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error 77 "C compiler cannot create executables
+See \`config.log' for more details" "$LINENO" 5; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5
+$as_echo_n "checking for C compiler default output file name... " >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5
+$as_echo "$ac_file" >&6; }
+ac_exeext=$ac_cv_exeext
+
+rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out
+ac_clean_files=$ac_clean_files_save
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5
+$as_echo_n "checking for suffix of executables... " >&6; }
+if { { ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then :
+  # If both `conftest.exe' and `conftest' are `present' (well, observable)
+# catch `conftest.exe'.  For instance with Cygwin, `ls conftest' will
+# work properly (i.e., refer to `conftest.exe'), while it won't with
+# `rm'.
+for ac_file in conftest.exe conftest conftest.*; do
+  test -f "$ac_file" || continue
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
+    *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+	  break;;
+    * ) break;;
+  esac
+done
+else
+  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "cannot compute suffix of executables: cannot compile and link
+See \`config.log' for more details" "$LINENO" 5; }
+fi
+rm -f conftest conftest$ac_cv_exeext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5
+$as_echo "$ac_cv_exeext" >&6; }
+
+rm -f conftest.$ac_ext
+EXEEXT=$ac_cv_exeext
+ac_exeext=$EXEEXT
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdio.h>
+int
+main ()
+{
+FILE *f = fopen ("conftest.out", "w");
+ return ferror (f) || fclose (f) != 0;
+
+  ;
+  return 0;
+}
+_ACEOF
+ac_clean_files="$ac_clean_files conftest.out"
+# Check that the compiler produces executables we can run.  If not, either
+# the compiler is broken, or we cross compile.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5
+$as_echo_n "checking whether we are cross compiling... " >&6; }
+if test "$cross_compiling" != yes; then
+  { { ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+  if { ac_try='./conftest$ac_cv_exeext'
+  { { case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_try") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; }; then
+    cross_compiling=no
+  else
+    if test "$cross_compiling" = maybe; then
+	cross_compiling=yes
+    else
+	{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "cannot run C compiled programs.
+If you meant to cross compile, use \`--host'.
+See \`config.log' for more details" "$LINENO" 5; }
+    fi
+  fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5
+$as_echo "$cross_compiling" >&6; }
+
+rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out
+ac_clean_files=$ac_clean_files_save
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5
+$as_echo_n "checking for suffix of object files... " >&6; }
+if ${ac_cv_objext+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.o conftest.obj
+if { { ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compile") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then :
+  for ac_file in conftest.o conftest.obj conftest.*; do
+  test -f "$ac_file" || continue;
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;;
+    *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'`
+       break;;
+  esac
+done
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "cannot compute suffix of object files: cannot compile
+See \`config.log' for more details" "$LINENO" 5; }
+fi
+rm -f conftest.$ac_cv_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5
+$as_echo "$ac_cv_objext" >&6; }
+OBJEXT=$ac_cv_objext
+ac_objext=$OBJEXT
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5
+$as_echo_n "checking whether we are using the GNU C compiler... " >&6; }
+if ${ac_cv_c_compiler_gnu+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+#ifndef __GNUC__
+       choke me
+#endif
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_compiler_gnu=yes
+else
+  ac_compiler_gnu=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_cv_c_compiler_gnu=$ac_compiler_gnu
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5
+$as_echo "$ac_cv_c_compiler_gnu" >&6; }
+if test $ac_compiler_gnu = yes; then
+  GCC=yes
+else
+  GCC=
+fi
+ac_test_CFLAGS=${CFLAGS+set}
+ac_save_CFLAGS=$CFLAGS
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
+$as_echo_n "checking whether $CC accepts -g... " >&6; }
+if ${ac_cv_prog_cc_g+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_save_c_werror_flag=$ac_c_werror_flag
+   ac_c_werror_flag=yes
+   ac_cv_prog_cc_g=no
+   CFLAGS="-g"
+   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_g=yes
+else
+  CFLAGS=""
+      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+
+else
+  ac_c_werror_flag=$ac_save_c_werror_flag
+	 CFLAGS="-g"
+	 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_g=yes
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+   ac_c_werror_flag=$ac_save_c_werror_flag
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5
+$as_echo "$ac_cv_prog_cc_g" >&6; }
+if test "$ac_test_CFLAGS" = set; then
+  CFLAGS=$ac_save_CFLAGS
+elif test $ac_cv_prog_cc_g = yes; then
+  if test "$GCC" = yes; then
+    CFLAGS="-g -O2"
+  else
+    CFLAGS="-g"
+  fi
+else
+  if test "$GCC" = yes; then
+    CFLAGS="-O2"
+  else
+    CFLAGS=
+  fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5
+$as_echo_n "checking for $CC option to accept ISO C89... " >&6; }
+if ${ac_cv_prog_cc_c89+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_cv_prog_cc_c89=no
+ac_save_CC=$CC
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdarg.h>
+#include <stdio.h>
+struct stat;
+/* Most of the following tests are stolen from RCS 5.7's src/conf.sh.  */
+struct buf { int x; };
+FILE * (*rcsopen) (struct buf *, struct stat *, int);
+static char *e (p, i)
+     char **p;
+     int i;
+{
+  return p[i];
+}
+static char *f (char * (*g) (char **, int), char **p, ...)
+{
+  char *s;
+  va_list v;
+  va_start (v,p);
+  s = g (p, va_arg (v,int));
+  va_end (v);
+  return s;
+}
+
+/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default.  It has
+   function prototypes and stuff, but not '\xHH' hex character constants.
+   These don't provoke an error unfortunately, instead are silently treated
+   as 'x'.  The following induces an error, until -std is added to get
+   proper ANSI mode.  Curiously '\x00'!='x' always comes out true, for an
+   array size at least.  It's necessary to write '\x00'==0 to get something
+   that's true only with -std.  */
+int osf4_cc_array ['\x00' == 0 ? 1 : -1];
+
+/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
+   inside strings and character constants.  */
+#define FOO(x) 'x'
+int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1];
+
+int test (int i, double x);
+struct s1 {int (*f) (int a);};
+struct s2 {int (*f) (double a);};
+int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int);
+int argc;
+char **argv;
+int
+main ()
+{
+return f (e, argv, 0) != argv[0]  ||  f (e, argv, 1) != argv[1];
+  ;
+  return 0;
+}
+_ACEOF
+for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \
+	-Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
+do
+  CC="$ac_save_CC $ac_arg"
+  if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_c89=$ac_arg
+fi
+rm -f core conftest.err conftest.$ac_objext
+  test "x$ac_cv_prog_cc_c89" != "xno" && break
+done
+rm -f conftest.$ac_ext
+CC=$ac_save_CC
+
+fi
+# AC_CACHE_VAL
+case "x$ac_cv_prog_cc_c89" in
+  x)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
+$as_echo "none needed" >&6; } ;;
+  xno)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
+$as_echo "unsupported" >&6; } ;;
+  *)
+    CC="$CC $ac_cv_prog_cc_c89"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5
+$as_echo "$ac_cv_prog_cc_c89" >&6; } ;;
+esac
+if test "x$ac_cv_prog_cc_c89" != xno; then :
+
+fi
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5
+$as_echo_n "checking how to run the C preprocessor... " >&6; }
+# On Suns, sometimes $CPP names a directory.
+if test -n "$CPP" && test -d "$CPP"; then
+  CPP=
+fi
+if test -z "$CPP"; then
+  if ${ac_cv_prog_CPP+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+      # Double quotes because CPP needs to be expanded
+    for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
+    do
+      ac_preproc_ok=false
+for ac_c_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
+  # On the NeXT, cc -E runs the code through the compiler's parser,
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+
+else
+  # Broken: fails on valid input.
+continue
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <ac_nonexistent.h>
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+  # Broken: success on invalid input.
+continue
+else
+  # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.i conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then :
+  break
+fi
+
+    done
+    ac_cv_prog_CPP=$CPP
+
+fi
+  CPP=$ac_cv_prog_CPP
+else
+  ac_cv_prog_CPP=$CPP
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5
+$as_echo "$CPP" >&6; }
+ac_preproc_ok=false
+for ac_c_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
+  # On the NeXT, cc -E runs the code through the compiler's parser,
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+
+else
+  # Broken: fails on valid input.
+continue
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <ac_nonexistent.h>
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+  # Broken: success on invalid input.
+continue
+else
+  # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.i conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then :
+
+else
+  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "C preprocessor \"$CPP\" fails sanity check
+See \`config.log' for more details" "$LINENO" 5; }
+fi
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5
+$as_echo_n "checking for grep that handles long lines and -e... " >&6; }
+if ${ac_cv_path_GREP+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -z "$GREP"; then
+  ac_path_GREP_found=false
+  # Loop through the user's path and test for each of PROGNAME-LIST
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_prog in grep ggrep; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext"
+      as_fn_executable_p "$ac_path_GREP" || continue
+# Check for GNU ac_path_GREP and select it if it is found.
+  # Check for GNU $ac_path_GREP
+case `"$ac_path_GREP" --version 2>&1` in
+*GNU*)
+  ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;;
+*)
+  ac_count=0
+  $as_echo_n 0123456789 >"conftest.in"
+  while :
+  do
+    cat "conftest.in" "conftest.in" >"conftest.tmp"
+    mv "conftest.tmp" "conftest.in"
+    cp "conftest.in" "conftest.nl"
+    $as_echo 'GREP' >> "conftest.nl"
+    "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break
+    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+    as_fn_arith $ac_count + 1 && ac_count=$as_val
+    if test $ac_count -gt ${ac_path_GREP_max-0}; then
+      # Best one so far, save it but keep looking for a better one
+      ac_cv_path_GREP="$ac_path_GREP"
+      ac_path_GREP_max=$ac_count
+    fi
+    # 10*(2^10) chars as input seems more than enough
+    test $ac_count -gt 10 && break
+  done
+  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+esac
+
+      $ac_path_GREP_found && break 3
+    done
+  done
+  done
+IFS=$as_save_IFS
+  if test -z "$ac_cv_path_GREP"; then
+    as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
+  fi
+else
+  ac_cv_path_GREP=$GREP
+fi
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5
+$as_echo "$ac_cv_path_GREP" >&6; }
+ GREP="$ac_cv_path_GREP"
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5
+$as_echo_n "checking for egrep... " >&6; }
+if ${ac_cv_path_EGREP+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if echo a | $GREP -E '(a|b)' >/dev/null 2>&1
+   then ac_cv_path_EGREP="$GREP -E"
+   else
+     if test -z "$EGREP"; then
+  ac_path_EGREP_found=false
+  # Loop through the user's path and test for each of PROGNAME-LIST
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_prog in egrep; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext"
+      as_fn_executable_p "$ac_path_EGREP" || continue
+# Check for GNU ac_path_EGREP and select it if it is found.
+  # Check for GNU $ac_path_EGREP
+case `"$ac_path_EGREP" --version 2>&1` in
+*GNU*)
+  ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;;
+*)
+  ac_count=0
+  $as_echo_n 0123456789 >"conftest.in"
+  while :
+  do
+    cat "conftest.in" "conftest.in" >"conftest.tmp"
+    mv "conftest.tmp" "conftest.in"
+    cp "conftest.in" "conftest.nl"
+    $as_echo 'EGREP' >> "conftest.nl"
+    "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break
+    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+    as_fn_arith $ac_count + 1 && ac_count=$as_val
+    if test $ac_count -gt ${ac_path_EGREP_max-0}; then
+      # Best one so far, save it but keep looking for a better one
+      ac_cv_path_EGREP="$ac_path_EGREP"
+      ac_path_EGREP_max=$ac_count
+    fi
+    # 10*(2^10) chars as input seems more than enough
+    test $ac_count -gt 10 && break
+  done
+  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+esac
+
+      $ac_path_EGREP_found && break 3
+    done
+  done
+  done
+IFS=$as_save_IFS
+  if test -z "$ac_cv_path_EGREP"; then
+    as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
+  fi
+else
+  ac_cv_path_EGREP=$EGREP
+fi
+
+   fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5
+$as_echo "$ac_cv_path_EGREP" >&6; }
+ EGREP="$ac_cv_path_EGREP"
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
+$as_echo_n "checking for ANSI C header files... " >&6; }
+if ${ac_cv_header_stdc+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <float.h>
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_header_stdc=yes
+else
+  ac_cv_header_stdc=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+if test $ac_cv_header_stdc = yes; then
+  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <string.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "memchr" >/dev/null 2>&1; then :
+
+else
+  ac_cv_header_stdc=no
+fi
+rm -f conftest*
+
+fi
+
+if test $ac_cv_header_stdc = yes; then
+  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdlib.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "free" >/dev/null 2>&1; then :
+
+else
+  ac_cv_header_stdc=no
+fi
+rm -f conftest*
+
+fi
+
+if test $ac_cv_header_stdc = yes; then
+  # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
+  if test "$cross_compiling" = yes; then :
+  :
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <ctype.h>
+#include <stdlib.h>
+#if ((' ' & 0x0FF) == 0x020)
+# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
+# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
+#else
+# define ISLOWER(c) \
+		   (('a' <= (c) && (c) <= 'i') \
+		     || ('j' <= (c) && (c) <= 'r') \
+		     || ('s' <= (c) && (c) <= 'z'))
+# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
+#endif
+
+#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
+int
+main ()
+{
+  int i;
+  for (i = 0; i < 256; i++)
+    if (XOR (islower (i), ISLOWER (i))
+	|| toupper (i) != TOUPPER (i))
+      return 2;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_run "$LINENO"; then :
+
+else
+  ac_cv_header_stdc=no
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5
+$as_echo "$ac_cv_header_stdc" >&6; }
+if test $ac_cv_header_stdc = yes; then
+
+$as_echo "#define STDC_HEADERS 1" >>confdefs.h
+
+fi
+
+
+## RUN_JAVA(variable for the result, parameters)
+## ----------
+## runs the java interpreter ${JAVA_PROG} with specified parameters and
+## saves the output to the supplied variable. The exit value is ignored.
+
+
+if test -n "${CONFIGURED}"; then
+## re-map varibles that don't match
+JAVA_PROG="${JAVA}"
+JAVA_INC="${JAVA_CPPFLAGS}"
+JAVA_LD_PATH="${JAVA_LD_LIBRARY_PATH}"
+else
+
+## find java compiler binaries
+if test -z "${JAVA_HOME}" ; then
+  JAVA_PATH=${PATH}
+else
+  JAVA_PATH=${JAVA_HOME}:${JAVA_HOME}/jre/bin:${JAVA_HOME}/bin:${JAVA_HOME}/../bin:${PATH}
+fi
+
+## if 'java' is not on the PATH or JAVA_HOME, add some guesses as of
+## where java could live
+JAVA_PATH=${JAVA_PATH}:/usr/java/bin:/usr/jdk/bin:/usr/lib/java/bin:/usr/lib/jdk/bin:/usr/local/java/bin:/usr/local/jdk/bin:/usr/local/lib/java/bin:/usr/local/lib/jdk/bin
+for ac_prog in java
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_JAVA_PROG+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $JAVA_PROG in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_JAVA_PROG="$JAVA_PROG" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in ${JAVA_PATH}
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_path_JAVA_PROG="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  ;;
+esac
+fi
+JAVA_PROG=$ac_cv_path_JAVA_PROG
+if test -n "$JAVA_PROG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $JAVA_PROG" >&5
+$as_echo "$JAVA_PROG" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$JAVA_PROG" && break
+done
+
+## FIXME: we may want to check for jikes, kaffe and others...
+for ac_prog in javac
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_JAVAC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $JAVAC in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_JAVAC="$JAVAC" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in ${JAVA_PATH}
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_path_JAVAC="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  ;;
+esac
+fi
+JAVAC=$ac_cv_path_JAVAC
+if test -n "$JAVAC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $JAVAC" >&5
+$as_echo "$JAVAC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$JAVAC" && break
+done
+
+for ac_prog in javah
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_JAVAH+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $JAVAH in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_JAVAH="$JAVAH" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in ${JAVA_PATH}
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_path_JAVAH="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  ;;
+esac
+fi
+JAVAH=$ac_cv_path_JAVAH
+if test -n "$JAVAH"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $JAVAH" >&5
+$as_echo "$JAVAH" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$JAVAH" && break
+done
+
+for ac_prog in jar
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_JAR+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $JAR in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_JAR="$JAR" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in ${JAVA_PATH}
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_path_JAR="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  ;;
+esac
+fi
+JAR=$ac_cv_path_JAR
+if test -n "$JAR"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $JAR" >&5
+$as_echo "$JAR" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$JAR" && break
+done
+
+fi
+
+have_all_java=yes
+if test -z "$JAVA_PROG"; then have_all_java=no; fi
+if test -z "$JAVAC"; then have_all_java=no; fi
+if test -z "$JAVAH"; then have_all_java=no; fi
+if test -z "$JAR"; then have_all_java=no; fi
+if test ${have_all_java} = no; then
+  as_fn_error $? "one or more Java tools are missing.
+
+*** JDK is incomplete! Please make sure you have a complete JDK. JRE is *not* sufficient." "$LINENO" 5
+fi
+
+## this is where our test-class lives
+getsp_cp=tools
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether Java interpreter works" >&5
+$as_echo_n "checking whether Java interpreter works... " >&6; }
+acx_java_works=no
+if test -n "${JAVA_PROG}" ; then
+
+  acx_java_result=
+  if test -z "${JAVA_PROG}"; then
+    echo "$as_me:$LINENO: JAVA_PROG is not set, cannot run java -classpath ${getsp_cp} getsp -test" >&5
+  else
+    echo "$as_me:$LINENO: running ${JAVA_PROG} -classpath ${getsp_cp} getsp -test" >&5
+    acx_java_result=`${JAVA_PROG} -classpath ${getsp_cp} getsp -test 2>&5`
+    echo "$as_me:$LINENO: output: '$acx_java_result'" >&5
+  fi
+  acx_jc_result=$acx_java_result
+
+  if test "${acx_jc_result}" = "Test1234OK"; then
+    acx_java_works=yes
+  fi
+  acx_jc_result=
+fi
+
+if test "x`uname -s 2>/dev/null`" = xDarwin; then
+  ## we need to pull that out of R in case re-export fails (which is does on 10.11)
+  DYLD_FALLBACK_LIBRARY_PATH=`"${RBIN}" --slave --vanilla -e 'cat(Sys.getenv("DYLD_FALLBACK_LIBRARY_PATH"))'`
+  export DYLD_FALLBACK_LIBRARY_PATH
+fi
+
+
+if test -z "${CONFIGURED}"; then
+
+if test ${acx_java_works} = yes; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Java environment" >&5
+$as_echo_n "checking for Java environment... " >&6; }
+  ## retrieve JAVA_HOME from Java itself if not set
+  if test -z "${JAVA_HOME}" ; then
+
+  acx_java_result=
+  if test -z "${JAVA_PROG}"; then
+    echo "$as_me:$LINENO: JAVA_PROG is not set, cannot run java -classpath ${getsp_cp} getsp java.home" >&5
+  else
+    echo "$as_me:$LINENO: running ${JAVA_PROG} -classpath ${getsp_cp} getsp java.home" >&5
+    acx_java_result=`${JAVA_PROG} -classpath ${getsp_cp} getsp java.home 2>&5`
+    echo "$as_me:$LINENO: output: '$acx_java_result'" >&5
+  fi
+  JAVA_HOME=$acx_java_result
+
+  fi
+
+  ## the availability of JAVA_HOME will tell us whether it's supported
+  if test -z "${JAVA_HOME}" ; then
+    if test x$acx_java_env_msg != xyes; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: not found" >&5
+$as_echo "not found" >&6; }
+    fi
+  else
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: in ${JAVA_HOME}" >&5
+$as_echo "in ${JAVA_HOME}" >&6; }
+
+    case "${host_os}" in
+      darwin*)
+        JAVA_LIBS="-framework JavaVM"
+        JAVA_LD_PATH=
+        ;;
+      *)
+
+  acx_java_result=
+  if test -z "${JAVA_PROG}"; then
+    echo "$as_me:$LINENO: JAVA_PROG is not set, cannot run java -classpath ${getsp_cp} getsp -libs" >&5
+  else
+    echo "$as_me:$LINENO: running ${JAVA_PROG} -classpath ${getsp_cp} getsp -libs" >&5
+    acx_java_result=`${JAVA_PROG} -classpath ${getsp_cp} getsp -libs 2>&5`
+    echo "$as_me:$LINENO: output: '$acx_java_result'" >&5
+  fi
+  JAVA_LIBS=$acx_java_result
+
+        JAVA_LIBS="${JAVA_LIBS} -ljvm"
+
+  acx_java_result=
+  if test -z "${JAVA_PROG}"; then
+    echo "$as_me:$LINENO: JAVA_PROG is not set, cannot run java -classpath ${getsp_cp} getsp java.library.path" >&5
+  else
+    echo "$as_me:$LINENO: running ${JAVA_PROG} -classpath ${getsp_cp} getsp java.library.path" >&5
+    acx_java_result=`${JAVA_PROG} -classpath ${getsp_cp} getsp java.library.path 2>&5`
+    echo "$as_me:$LINENO: output: '$acx_java_result'" >&5
+  fi
+  JAVA_LD_PATH=$acx_java_result
+
+        ;;
+    esac
+    ## note that we actually don't test JAVA_LIBS - we hope that the detection
+    ## was correct. We should also test the functionality for javac.
+
+    have_java=yes
+  fi
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+  as_fn_error $? "Java not found. Please install JDK 1.4 or later, make sure that the binaries are on the PATH and re-try. If that doesn't work, set JAVA_HOME correspondingly." "$LINENO" 5
+fi
+
+as_ac_File=`$as_echo "ac_cv_file_${JAVA_HOME}/include/jni.h" | $as_tr_sh`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${JAVA_HOME}/include/jni.h" >&5
+$as_echo_n "checking for ${JAVA_HOME}/include/jni.h... " >&6; }
+if eval \${$as_ac_File+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  test "$cross_compiling" = yes &&
+  as_fn_error $? "cannot check for file existence when cross compiling" "$LINENO" 5
+if test -r "${JAVA_HOME}/include/jni.h"; then
+  eval "$as_ac_File=yes"
+else
+  eval "$as_ac_File=no"
+fi
+fi
+eval ac_res=\$$as_ac_File
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+if eval test \"x\$"$as_ac_File"\" = x"yes"; then :
+  JNI_H="${JAVA_HOME}/include"
+else
+  as_ac_File=`$as_echo "ac_cv_file_${JAVA_HOME}/jni.h" | $as_tr_sh`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${JAVA_HOME}/jni.h" >&5
+$as_echo_n "checking for ${JAVA_HOME}/jni.h... " >&6; }
+if eval \${$as_ac_File+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  test "$cross_compiling" = yes &&
+  as_fn_error $? "cannot check for file existence when cross compiling" "$LINENO" 5
+if test -r "${JAVA_HOME}/jni.h"; then
+  eval "$as_ac_File=yes"
+else
+  eval "$as_ac_File=no"
+fi
+fi
+eval ac_res=\$$as_ac_File
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+if eval test \"x\$"$as_ac_File"\" = x"yes"; then :
+  JNI_H="${JAVA_HOME}"
+else
+  as_ac_File=`$as_echo "ac_cv_file_${JAVA_HOME}/../include/jni.h" | $as_tr_sh`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${JAVA_HOME}/../include/jni.h" >&5
+$as_echo_n "checking for ${JAVA_HOME}/../include/jni.h... " >&6; }
+if eval \${$as_ac_File+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  test "$cross_compiling" = yes &&
+  as_fn_error $? "cannot check for file existence when cross compiling" "$LINENO" 5
+if test -r "${JAVA_HOME}/../include/jni.h"; then
+  eval "$as_ac_File=yes"
+else
+  eval "$as_ac_File=no"
+fi
+fi
+eval ac_res=\$$as_ac_File
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+if eval test \"x\$"$as_ac_File"\" = x"yes"; then :
+  JNI_H="${JAVA_HOME}/../include"
+else
+  as_fn_error $? "jni headers not found. Please make sure you have a proper JDK installed." "$LINENO" 5
+
+fi
+
+
+fi
+
+
+fi
+
+
+JAVA_INC="-I${JNI_H}"
+: ${JAVA_CFLAGS=-D_REENTRANT}
+
+# Sun's JDK needs jni_md.h in in addition to jni.h and unfortunately it's stored somewhere else ...
+# this should be become more general at some point - so far we're checking linux and solaris only
+# (well, those are presumably the only platforms supported by Sun's JDK and others don't need this
+# at least as of now - 01/2004)
+jac_found_md=no
+for mddir in . linux solaris ppc irix alpha aix hp-ux genunix cygwin win32 freebsd; do
+as_ac_File=`$as_echo "ac_cv_file_${JNI_H}/$mddir/jni_md.h" | $as_tr_sh`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${JNI_H}/$mddir/jni_md.h" >&5
+$as_echo_n "checking for ${JNI_H}/$mddir/jni_md.h... " >&6; }
+if eval \${$as_ac_File+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  test "$cross_compiling" = yes &&
+  as_fn_error $? "cannot check for file existence when cross compiling" "$LINENO" 5
+if test -r "${JNI_H}/$mddir/jni_md.h"; then
+  eval "$as_ac_File=yes"
+else
+  eval "$as_ac_File=no"
+fi
+fi
+eval ac_res=\$$as_ac_File
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+if eval test \"x\$"$as_ac_File"\" = x"yes"; then :
+  JAVA_INC="${JAVA_INC} -I${JNI_H}/$mddir" jac_found_md=yes
+fi
+
+if test ${jac_found_md} = yes; then break; fi
+done
+
+fi
+
+## the configure variables may contain $(JAVA_HOME) which for testing needs to be replaced by the real path
+if test `echo foo | sed -e 's:foo:bar:'` = bar; then
+   JAVA_INC0=`echo ${JAVA_INC} | sed -e 's:$(JAVA_HOME):'${JAVA_HOME}':g'`
+   JAVA_LIBS0=`echo ${JAVA_LIBS} | sed -e 's:$(JAVA_HOME):'${JAVA_HOME}':g'`
+   JAVA_LD_PATH0=`echo ${JAVA_LD_PATH} | sed -e 's:$(JAVA_HOME):'${JAVA_HOME}':g'`
+else
+   { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: sed is not working properly - the configuration may fail" >&5
+$as_echo "$as_me: WARNING: sed is not working properly - the configuration may fail" >&2;}
+   JAVA_INC0="${JAVA_INC}"
+   JAVA_LIBS0="${JAVA_LIBS}"
+   JAVA_LD_PATH0="${JAVA_LD_PATH}"
+fi
+
+LIBS="${LIBS} ${JAVA_LIBS0}"
+CFLAGS="${CFLAGS} ${JAVA_CFLAGS} ${JAVA_INC0}"
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether JNI programs can be compiled" >&5
+$as_echo_n "checking whether JNI programs can be compiled... " >&6; }
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+#include <jni.h>
+int main(void) {
+    jobject o;
+    return 0;
+}
+
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+else
+  as_fn_error $? "Cannot compile a simple JNI program. See config.log for details." "$LINENO" 5
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+
+LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${JAVA_LD_PATH0}
+export LD_LIBRARY_PATH
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether JNI programs can be run" >&5
+$as_echo_n "checking whether JNI programs can be run... " >&6; }
+if test "$cross_compiling" = yes; then :
+  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "cannot run test program while cross compiling
+See \`config.log' for more details" "$LINENO" 5; }
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+#include <jni.h>
+int main(void) {
+    jobject o;
+    return 0;
+}
+
+_ACEOF
+if ac_fn_c_try_run "$LINENO"; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+else
+  as_fn_error $? "Cannot run a simple JNI program - probably your jvm library is in non-standard location or JVM is unsupported. See config.log for details." "$LINENO" 5
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking JNI data types" >&5
+$as_echo_n "checking JNI data types... " >&6; }
+if test "$cross_compiling" = yes; then :
+  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "cannot run test program while cross compiling
+See \`config.log' for more details" "$LINENO" 5; }
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+#include <jni.h>
+int main(void) {
+  return (sizeof(int)==sizeof(jint) && sizeof(long)==sizeof(long) && sizeof(jbyte)==sizeof(char) && sizeof(jshort)==sizeof(short) && sizeof(jfloat)==sizeof(float) && sizeof(jdouble)==sizeof(double))?0:1;
+}
+
+_ACEOF
+if ac_fn_c_try_run "$LINENO"; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5
+$as_echo "ok" >&6; }
+else
+  as_fn_error $? "One or more JNI types differ from the corresponding native type. You may need to use non-standard compiler flags or a different compiler in order to fix this." "$LINENO" 5
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+
+JNIPREFIX=lib
+CPICF=`"${RBIN}" CMD config CPICFLAGS`
+JNISO=.so
+JNILD=`"${RBIN}" CMD config SHLIB_LDFLAGS`" ${JAVA_LIBS}"
+
+# we need to adjust a few things according to OS ..
+case "${host_os}" in
+  darwin*)
+    JNISO=.jnilib
+    JNILD="-dynamiclib -framework JavaVM"
+    CPICF=-fno-common
+
+    if test -e "${R_HOME}/lib/i386" -a -e "${R_HOME}/lib/ppc" -a -e "${R_HOME}/lib/libR.dylib"; then
+       # we have an universal framework, so we will use stubs and fat lib
+       RLD="-framework R"
+       RINC="-I${R_HOME}/include"
+       # we can even cross-compile, maybe
+       if test -z "${FORCE_NATIVE}"; then
+          # find out the archs of JavaVM and build all of them
+          jarchs=`file -L /System/Library/Frameworks/JavaVM.framework/JavaVM 2>/dev/null | sed -n 's/.*for architecture //p' | sed 's:).*::' | sed 's:ppc7.*:ppc:' | tr '\n' ' '`
+	  jrarchs=''
+	  ## ok, we have Java archs, but R may not be available for all of those
+	  for a in ${jarchs}; do
+	     if test -e "${R_HOME}/lib/$a"; then jrarchs="${jrarchs} $a"; fi
+	  done
+	  ## if have have more than one arch, display info and add -arch flags
+	  if test -n "${jrarchs}"; then
+	     echo "*** building fat JNI with gcc for architectures: ${jrarchs} ***"
+	     echo "*** use FORCE_NATIVE=yes to avoid this and use R settings ***"
+	     CFLAGS=""
+	     LDFLAGS=""
+	     CC="gcc"
+	     for a in ${jrarchs}; do CC="${CC} -arch $a"; done
+	  fi
+       fi
+    fi
+    ;;
+  *)
+    ;;
+esac
+
+origCFLAGS=$CFLAGS
+CFLAGS="${CFLAGS} ${R_CFLAGS} ${RINC}"
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether Rinterface.h exports R_CStackXXX variables" >&5
+$as_echo_n "checking whether Rinterface.h exports R_CStackXXX variables... " >&6; }
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+#define CSTACK_DEFNS
+#include <R.h>
+#include <Rinterface.h>
+int main(void) {
+    return R_CStackLimit?0:1;
+}
+
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+           DEFFLAGS="${DEFFLAGS} -DRIF_HAS_CSTACK"
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether Rinterface.h exports R_SignalHandlers" >&5
+$as_echo_n "checking whether Rinterface.h exports R_SignalHandlers... " >&6; }
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+#include <R.h>
+#include <Rinterface.h>
+int main(void) {
+    return R_SignalHandlers;
+}
+
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+           DEFFLAGS="${DEFFLAGS} -DRIF_HAS_RSIGHAND"
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+CFLAGS=${origCFLAGS}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ac_config_files="$ac_config_files src/Makefile"
+
+ac_config_files="$ac_config_files Makefile"
+
+ac_config_files="$ac_config_files run"
+
+
+cat >confcache <<\_ACEOF
+# This file is a shell script that caches the results of configure
+# tests run on this system so they can be shared between configure
+# scripts and configure runs, see configure's option --config-cache.
+# It is not useful on other systems.  If it contains results you don't
+# want to keep, you may remove or edit it.
+#
+# config.status only pays attention to the cache file if you give it
+# the --recheck option to rerun configure.
+#
+# `ac_cv_env_foo' variables (set or unset) will be overridden when
+# loading this file, other *unset* `ac_cv_foo' will be assigned the
+# following values.
+
+_ACEOF
+
+# The following way of writing the cache mishandles newlines in values,
+# but we know of no workaround that is simple, portable, and efficient.
+# So, we kill variables containing newlines.
+# Ultrix sh set writes to stderr and can't be redirected directly,
+# and sets the high bit in the cache file unless we assign to the vars.
+(
+  for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
+$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
+      *) { eval $ac_var=; unset $ac_var;} ;;
+      esac ;;
+    esac
+  done
+
+  (set) 2>&1 |
+    case $as_nl`(ac_space=' '; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
+      # `set' does not quote correctly, so add quotes: double-quote
+      # substitution turns \\\\ into \\, and sed turns \\ into \.
+      sed -n \
+	"s/'/'\\\\''/g;
+	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
+      ;; #(
+    *)
+      # `set' quotes correctly as required by POSIX, so do not add quotes.
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+      ;;
+    esac |
+    sort
+) |
+  sed '
+     /^ac_cv_env_/b end
+     t clear
+     :clear
+     s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
+     t end
+     s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
+     :end' >>confcache
+if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
+  if test -w "$cache_file"; then
+    if test "x$cache_file" != "x/dev/null"; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5
+$as_echo "$as_me: updating cache $cache_file" >&6;}
+      if test ! -f "$cache_file" || test -h "$cache_file"; then
+	cat confcache >"$cache_file"
+      else
+        case $cache_file in #(
+        */* | ?:*)
+	  mv -f confcache "$cache_file"$$ &&
+	  mv -f "$cache_file"$$ "$cache_file" ;; #(
+        *)
+	  mv -f confcache "$cache_file" ;;
+	esac
+      fi
+    fi
+  else
+    { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5
+$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;}
+  fi
+fi
+rm -f confcache
+
+test "x$prefix" = xNONE && prefix=$ac_default_prefix
+# Let make expand exec_prefix.
+test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
+
+DEFS=-DHAVE_CONFIG_H
+
+ac_libobjs=
+ac_ltlibobjs=
+U=
+for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
+  # 1. Remove the extension, and $U if already installed.
+  ac_script='s/\$U\././;s/\.o$//;s/\.obj$//'
+  ac_i=`$as_echo "$ac_i" | sed "$ac_script"`
+  # 2. Prepend LIBOBJDIR.  When used with automake>=1.10 LIBOBJDIR
+  #    will be set to the directory where LIBOBJS objects are built.
+  as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext"
+  as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo'
+done
+LIBOBJS=$ac_libobjs
+
+LTLIBOBJS=$ac_ltlibobjs
+
+
+
+: "${CONFIG_STATUS=./config.status}"
+ac_write_fail=0
+ac_clean_files_save=$ac_clean_files
+ac_clean_files="$ac_clean_files $CONFIG_STATUS"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5
+$as_echo "$as_me: creating $CONFIG_STATUS" >&6;}
+as_write_fail=0
+cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1
+#! $SHELL
+# Generated by $as_me.
+# Run this file to recreate the current configuration.
+# Compiler output produced by configure, useful for debugging
+# configure, is in config.log if it exists.
+
+debug=false
+ac_cs_recheck=false
+ac_cs_silent=false
+
+SHELL=\${CONFIG_SHELL-$SHELL}
+export SHELL
+_ASEOF
+cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1
+## -------------------- ##
+## M4sh Initialization. ##
+## -------------------- ##
+
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
+  emulate sh
+  NULLCMD=:
+  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in #(
+  *posix*) :
+    set -o posix ;; #(
+  *) :
+     ;;
+esac
+fi
+
+
+as_nl='
+'
+export as_nl
+# Printing a long string crashes Solaris 7 /usr/bin/printf.
+as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
+# Prefer a ksh shell builtin over an external printf program on Solaris,
+# but without wasting forks for bash or zsh.
+if test -z "$BASH_VERSION$ZSH_VERSION" \
+    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='print -r --'
+  as_echo_n='print -rn --'
+elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='printf %s\n'
+  as_echo_n='printf %s'
+else
+  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
+    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
+    as_echo_n='/usr/ucb/echo -n'
+  else
+    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
+    as_echo_n_body='eval
+      arg=$1;
+      case $arg in #(
+      *"$as_nl"*)
+	expr "X$arg" : "X\\(.*\\)$as_nl";
+	arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
+      esac;
+      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
+    '
+    export as_echo_n_body
+    as_echo_n='sh -c $as_echo_n_body as_echo'
+  fi
+  export as_echo_body
+  as_echo='sh -c $as_echo_body as_echo'
+fi
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  PATH_SEPARATOR=:
+  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
+    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
+      PATH_SEPARATOR=';'
+  }
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+IFS=" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+as_myself=
+case $0 in #((
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+  done
+IFS=$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  exit 1
+fi
+
+# Unset variables that we do not need and which cause bugs (e.g. in
+# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
+# suppresses any "Segmentation fault" message there.  '((' could
+# trigger a bug in pdksh 5.2.14.
+for as_var in BASH_ENV ENV MAIL MAILPATH
+do eval test x\${$as_var+set} = xset \
+  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+LC_ALL=C
+export LC_ALL
+LANGUAGE=C
+export LANGUAGE
+
+# CDPATH.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+
+# as_fn_error STATUS ERROR [LINENO LOG_FD]
+# ----------------------------------------
+# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
+# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
+# script with STATUS, using 1 if that was 0.
+as_fn_error ()
+{
+  as_status=$1; test $as_status -eq 0 && as_status=1
+  if test "$4"; then
+    as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
+  fi
+  $as_echo "$as_me: error: $2" >&2
+  as_fn_exit $as_status
+} # as_fn_error
+
+
+# as_fn_set_status STATUS
+# -----------------------
+# Set $? to STATUS, without forking.
+as_fn_set_status ()
+{
+  return $1
+} # as_fn_set_status
+
+# as_fn_exit STATUS
+# -----------------
+# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
+as_fn_exit ()
+{
+  set +e
+  as_fn_set_status $1
+  exit $1
+} # as_fn_exit
+
+# as_fn_unset VAR
+# ---------------
+# Portably unset VAR.
+as_fn_unset ()
+{
+  { eval $1=; unset $1;}
+}
+as_unset=as_fn_unset
+# as_fn_append VAR VALUE
+# ----------------------
+# Append the text in VALUE to the end of the definition contained in VAR. Take
+# advantage of any shell optimizations that allow amortized linear growth over
+# repeated appends, instead of the typical quadratic growth present in naive
+# implementations.
+if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
+  eval 'as_fn_append ()
+  {
+    eval $1+=\$2
+  }'
+else
+  as_fn_append ()
+  {
+    eval $1=\$$1\$2
+  }
+fi # as_fn_append
+
+# as_fn_arith ARG...
+# ------------------
+# Perform arithmetic evaluation on the ARGs, and store the result in the
+# global $as_val. Take advantage of shells that can avoid forks. The arguments
+# must be portable across $(()) and expr.
+if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
+  eval 'as_fn_arith ()
+  {
+    as_val=$(( $* ))
+  }'
+else
+  as_fn_arith ()
+  {
+    as_val=`expr "$@" || test $? -eq 1`
+  }
+fi # as_fn_arith
+
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+  as_basename=basename
+else
+  as_basename=false
+fi
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
+
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in #(((((
+-n*)
+  case `echo 'xy\c'` in
+  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
+  xy)  ECHO_C='\c';;
+  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
+       ECHO_T='	';;
+  esac;;
+*)
+  ECHO_N='-n';;
+esac
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir 2>/dev/null
+fi
+if (echo >conf$$.file) 2>/dev/null; then
+  if ln -s conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s='ln -s'
+    # ... but there are two gotchas:
+    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+    # In both cases, we have to default to `cp -pR'.
+    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+      as_ln_s='cp -pR'
+  elif ln conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s=ln
+  else
+    as_ln_s='cp -pR'
+  fi
+else
+  as_ln_s='cp -pR'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+
+# as_fn_mkdir_p
+# -------------
+# Create "$as_dir" as a directory, including parents if necessary.
+as_fn_mkdir_p ()
+{
+
+  case $as_dir in #(
+  -*) as_dir=./$as_dir;;
+  esac
+  test -d "$as_dir" || eval $as_mkdir_p || {
+    as_dirs=
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
+      *) as_qdir=$as_dir;;
+      esac
+      as_dirs="'$as_qdir' $as_dirs"
+      as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_dir" : 'X\(//\)[^/]' \| \
+	 X"$as_dir" : 'X\(//\)$' \| \
+	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_dir" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+      test -d "$as_dir" && break
+    done
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
+
+
+} # as_fn_mkdir_p
+if mkdir -p . 2>/dev/null; then
+  as_mkdir_p='mkdir -p "$as_dir"'
+else
+  test -d ./-p && rmdir ./-p
+  as_mkdir_p=false
+fi
+
+
+# as_fn_executable_p FILE
+# -----------------------
+# Test if FILE is an executable regular file.
+as_fn_executable_p ()
+{
+  test -f "$1" && test -x "$1"
+} # as_fn_executable_p
+as_test_x='test -x'
+as_executable_p=as_fn_executable_p
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+exec 6>&1
+## ----------------------------------- ##
+## Main body of $CONFIG_STATUS script. ##
+## ----------------------------------- ##
+_ASEOF
+test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+# Save the log message, to keep $0 and so on meaningful, and to
+# report actual input values of CONFIG_FILES etc. instead of their
+# values after options handling.
+ac_log="
+This file was extended by JRI $as_me 0.3, which was
+generated by GNU Autoconf 2.69.  Invocation command line was
+
+  CONFIG_FILES    = $CONFIG_FILES
+  CONFIG_HEADERS  = $CONFIG_HEADERS
+  CONFIG_LINKS    = $CONFIG_LINKS
+  CONFIG_COMMANDS = $CONFIG_COMMANDS
+  $ $0 $@
+
+on `(hostname || uname -n) 2>/dev/null | sed 1q`
+"
+
+_ACEOF
+
+case $ac_config_files in *"
+"*) set x $ac_config_files; shift; ac_config_files=$*;;
+esac
+
+case $ac_config_headers in *"
+"*) set x $ac_config_headers; shift; ac_config_headers=$*;;
+esac
+
+
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+# Files that config.status was made for.
+config_files="$ac_config_files"
+config_headers="$ac_config_headers"
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+ac_cs_usage="\
+\`$as_me' instantiates files and other configuration actions
+from templates according to the current configuration.  Unless the files
+and actions are specified as TAGs, all are instantiated by default.
+
+Usage: $0 [OPTION]... [TAG]...
+
+  -h, --help       print this help, then exit
+  -V, --version    print version number and configuration settings, then exit
+      --config     print configuration, then exit
+  -q, --quiet, --silent
+                   do not print progress messages
+  -d, --debug      don't remove temporary files
+      --recheck    update $as_me by reconfiguring in the same conditions
+      --file=FILE[:TEMPLATE]
+                   instantiate the configuration file FILE
+      --header=FILE[:TEMPLATE]
+                   instantiate the configuration header FILE
+
+Configuration files:
+$config_files
+
+Configuration headers:
+$config_headers
+
+Report bugs to <simon.urbanek@r-project.org>."
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
+ac_cs_version="\\
+JRI config.status 0.3
+configured by $0, generated by GNU Autoconf 2.69,
+  with options \\"\$ac_cs_config\\"
+
+Copyright (C) 2012 Free Software Foundation, Inc.
+This config.status script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it."
+
+ac_pwd='$ac_pwd'
+srcdir='$srcdir'
+test -n "\$AWK" || AWK=awk
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+# The default lists apply if the user does not specify any file.
+ac_need_defaults=:
+while test $# != 0
+do
+  case $1 in
+  --*=?*)
+    ac_option=`expr "X$1" : 'X\([^=]*\)='`
+    ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
+    ac_shift=:
+    ;;
+  --*=)
+    ac_option=`expr "X$1" : 'X\([^=]*\)='`
+    ac_optarg=
+    ac_shift=:
+    ;;
+  *)
+    ac_option=$1
+    ac_optarg=$2
+    ac_shift=shift
+    ;;
+  esac
+
+  case $ac_option in
+  # Handling of the options.
+  -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
+    ac_cs_recheck=: ;;
+  --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
+    $as_echo "$ac_cs_version"; exit ;;
+  --config | --confi | --conf | --con | --co | --c )
+    $as_echo "$ac_cs_config"; exit ;;
+  --debug | --debu | --deb | --de | --d | -d )
+    debug=: ;;
+  --file | --fil | --fi | --f )
+    $ac_shift
+    case $ac_optarg in
+    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    '') as_fn_error $? "missing file argument" ;;
+    esac
+    as_fn_append CONFIG_FILES " '$ac_optarg'"
+    ac_need_defaults=false;;
+  --header | --heade | --head | --hea )
+    $ac_shift
+    case $ac_optarg in
+    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    esac
+    as_fn_append CONFIG_HEADERS " '$ac_optarg'"
+    ac_need_defaults=false;;
+  --he | --h)
+    # Conflict between --help and --header
+    as_fn_error $? "ambiguous option: \`$1'
+Try \`$0 --help' for more information.";;
+  --help | --hel | -h )
+    $as_echo "$ac_cs_usage"; exit ;;
+  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+  | -silent | --silent | --silen | --sile | --sil | --si | --s)
+    ac_cs_silent=: ;;
+
+  # This is an error.
+  -*) as_fn_error $? "unrecognized option: \`$1'
+Try \`$0 --help' for more information." ;;
+
+  *) as_fn_append ac_config_targets " $1"
+     ac_need_defaults=false ;;
+
+  esac
+  shift
+done
+
+ac_configure_extra_args=
+
+if $ac_cs_silent; then
+  exec 6>/dev/null
+  ac_configure_extra_args="$ac_configure_extra_args --silent"
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+if \$ac_cs_recheck; then
+  set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
+  shift
+  \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6
+  CONFIG_SHELL='$SHELL'
+  export CONFIG_SHELL
+  exec "\$@"
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+exec 5>>config.log
+{
+  echo
+  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
+## Running $as_me. ##
+_ASBOX
+  $as_echo "$ac_log"
+} >&5
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+
+# Handling of arguments.
+for ac_config_target in $ac_config_targets
+do
+  case $ac_config_target in
+    "src/config.h") CONFIG_HEADERS="$CONFIG_HEADERS src/config.h" ;;
+    "src/Makefile") CONFIG_FILES="$CONFIG_FILES src/Makefile" ;;
+    "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;;
+    "run") CONFIG_FILES="$CONFIG_FILES run" ;;
+
+  *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
+  esac
+done
+
+
+# If the user did not use the arguments to specify the items to instantiate,
+# then the envvar interface is used.  Set only those that are not.
+# We use the long form for the default assignment because of an extremely
+# bizarre bug on SunOS 4.1.3.
+if $ac_need_defaults; then
+  test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
+  test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers
+fi
+
+# Have a temporary directory for convenience.  Make it in the build tree
+# simply because there is no reason against having it here, and in addition,
+# creating and moving files from /tmp can sometimes cause problems.
+# Hook for its removal unless debugging.
+# Note that there is a small window in which the directory will not be cleaned:
+# after its creation but before its name has been assigned to `$tmp'.
+$debug ||
+{
+  tmp= ac_tmp=
+  trap 'exit_status=$?
+  : "${ac_tmp:=$tmp}"
+  { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status
+' 0
+  trap 'as_fn_exit 1' 1 2 13 15
+}
+# Create a (secure) tmp directory for tmp files.
+
+{
+  tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
+  test -d "$tmp"
+}  ||
+{
+  tmp=./conf$$-$RANDOM
+  (umask 077 && mkdir "$tmp")
+} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5
+ac_tmp=$tmp
+
+# Set up the scripts for CONFIG_FILES section.
+# No need to generate them if there are no CONFIG_FILES.
+# This happens for instance with `./config.status config.h'.
+if test -n "$CONFIG_FILES"; then
+
+
+ac_cr=`echo X | tr X '\015'`
+# On cygwin, bash can eat \r inside `` if the user requested igncr.
+# But we know of no other shell where ac_cr would be empty at this
+# point, so we can use a bashism as a fallback.
+if test "x$ac_cr" = x; then
+  eval ac_cr=\$\'\\r\'
+fi
+ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' </dev/null 2>/dev/null`
+if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then
+  ac_cs_awk_cr='\\r'
+else
+  ac_cs_awk_cr=$ac_cr
+fi
+
+echo 'BEGIN {' >"$ac_tmp/subs1.awk" &&
+_ACEOF
+
+
+{
+  echo "cat >conf$$subs.awk <<_ACEOF" &&
+  echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' &&
+  echo "_ACEOF"
+} >conf$$subs.sh ||
+  as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
+ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'`
+ac_delim='%!_!# '
+for ac_last_try in false false false false false :; do
+  . ./conf$$subs.sh ||
+    as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
+
+  ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X`
+  if test $ac_delim_n = $ac_delim_num; then
+    break
+  elif $ac_last_try; then
+    as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
+  else
+    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
+  fi
+done
+rm -f conf$$subs.sh
+
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK &&
+_ACEOF
+sed -n '
+h
+s/^/S["/; s/!.*/"]=/
+p
+g
+s/^[^!]*!//
+:repl
+t repl
+s/'"$ac_delim"'$//
+t delim
+:nl
+h
+s/\(.\{148\}\)..*/\1/
+t more1
+s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/
+p
+n
+b repl
+:more1
+s/["\\]/\\&/g; s/^/"/; s/$/"\\/
+p
+g
+s/.\{148\}//
+t nl
+:delim
+h
+s/\(.\{148\}\)..*/\1/
+t more2
+s/["\\]/\\&/g; s/^/"/; s/$/"/
+p
+b
+:more2
+s/["\\]/\\&/g; s/^/"/; s/$/"\\/
+p
+g
+s/.\{148\}//
+t delim
+' <conf$$subs.awk | sed '
+/^[^""]/{
+  N
+  s/\n//
+}
+' >>$CONFIG_STATUS || ac_write_fail=1
+rm -f conf$$subs.awk
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+_ACAWK
+cat >>"\$ac_tmp/subs1.awk" <<_ACAWK &&
+  for (key in S) S_is_set[key] = 1
+  FS = ""
+
+}
+{
+  line = $ 0
+  nfields = split(line, field, "@")
+  substed = 0
+  len = length(field[1])
+  for (i = 2; i < nfields; i++) {
+    key = field[i]
+    keylen = length(key)
+    if (S_is_set[key]) {
+      value = S[key]
+      line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3)
+      len += length(value) + length(field[++i])
+      substed = 1
+    } else
+      len += 1 + keylen
+  }
+
+  print line
+}
+
+_ACAWK
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then
+  sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g"
+else
+  cat
+fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \
+  || as_fn_error $? "could not setup config files machinery" "$LINENO" 5
+_ACEOF
+
+# VPATH may cause trouble with some makes, so we remove sole $(srcdir),
+# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and
+# trailing colons and then remove the whole line if VPATH becomes empty
+# (actually we leave an empty line to preserve line numbers).
+if test "x$srcdir" = x.; then
+  ac_vpsub='/^[	 ]*VPATH[	 ]*=[	 ]*/{
+h
+s///
+s/^/:/
+s/[	 ]*$/:/
+s/:\$(srcdir):/:/g
+s/:\${srcdir}:/:/g
+s/:@srcdir@:/:/g
+s/^:*//
+s/:*$//
+x
+s/\(=[	 ]*\).*/\1/
+G
+s/\n//
+s/^[^=]*=[	 ]*$//
+}'
+fi
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+fi # test -n "$CONFIG_FILES"
+
+# Set up the scripts for CONFIG_HEADERS section.
+# No need to generate them if there are no CONFIG_HEADERS.
+# This happens for instance with `./config.status Makefile'.
+if test -n "$CONFIG_HEADERS"; then
+cat >"$ac_tmp/defines.awk" <<\_ACAWK ||
+BEGIN {
+_ACEOF
+
+# Transform confdefs.h into an awk script `defines.awk', embedded as
+# here-document in config.status, that substitutes the proper values into
+# config.h.in to produce config.h.
+
+# Create a delimiter string that does not exist in confdefs.h, to ease
+# handling of long lines.
+ac_delim='%!_!# '
+for ac_last_try in false false :; do
+  ac_tt=`sed -n "/$ac_delim/p" confdefs.h`
+  if test -z "$ac_tt"; then
+    break
+  elif $ac_last_try; then
+    as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5
+  else
+    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
+  fi
+done
+
+# For the awk script, D is an array of macro values keyed by name,
+# likewise P contains macro parameters if any.  Preserve backslash
+# newline sequences.
+
+ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]*
+sed -n '
+s/.\{148\}/&'"$ac_delim"'/g
+t rset
+:rset
+s/^[	 ]*#[	 ]*define[	 ][	 ]*/ /
+t def
+d
+:def
+s/\\$//
+t bsnl
+s/["\\]/\\&/g
+s/^ \('"$ac_word_re"'\)\(([^()]*)\)[	 ]*\(.*\)/P["\1"]="\2"\
+D["\1"]=" \3"/p
+s/^ \('"$ac_word_re"'\)[	 ]*\(.*\)/D["\1"]=" \2"/p
+d
+:bsnl
+s/["\\]/\\&/g
+s/^ \('"$ac_word_re"'\)\(([^()]*)\)[	 ]*\(.*\)/P["\1"]="\2"\
+D["\1"]=" \3\\\\\\n"\\/p
+t cont
+s/^ \('"$ac_word_re"'\)[	 ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p
+t cont
+d
+:cont
+n
+s/.\{148\}/&'"$ac_delim"'/g
+t clear
+:clear
+s/\\$//
+t bsnlc
+s/["\\]/\\&/g; s/^/"/; s/$/"/p
+d
+:bsnlc
+s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p
+b cont
+' <confdefs.h | sed '
+s/'"$ac_delim"'/"\\\
+"/g' >>$CONFIG_STATUS || ac_write_fail=1
+
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+  for (key in D) D_is_set[key] = 1
+  FS = ""
+}
+/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ {
+  line = \$ 0
+  split(line, arg, " ")
+  if (arg[1] == "#") {
+    defundef = arg[2]
+    mac1 = arg[3]
+  } else {
+    defundef = substr(arg[1], 2)
+    mac1 = arg[2]
+  }
+  split(mac1, mac2, "(") #)
+  macro = mac2[1]
+  prefix = substr(line, 1, index(line, defundef) - 1)
+  if (D_is_set[macro]) {
+    # Preserve the white space surrounding the "#".
+    print prefix "define", macro P[macro] D[macro]
+    next
+  } else {
+    # Replace #undef with comments.  This is necessary, for example,
+    # in the case of _POSIX_SOURCE, which is predefined and required
+    # on some systems where configure will not decide to define it.
+    if (defundef == "undef") {
+      print "/*", prefix defundef, macro, "*/"
+      next
+    }
+  }
+}
+{ print }
+_ACAWK
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+  as_fn_error $? "could not setup config headers machinery" "$LINENO" 5
+fi # test -n "$CONFIG_HEADERS"
+
+
+eval set X "  :F $CONFIG_FILES  :H $CONFIG_HEADERS    "
+shift
+for ac_tag
+do
+  case $ac_tag in
+  :[FHLC]) ac_mode=$ac_tag; continue;;
+  esac
+  case $ac_mode$ac_tag in
+  :[FHL]*:*);;
+  :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;;
+  :[FH]-) ac_tag=-:-;;
+  :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
+  esac
+  ac_save_IFS=$IFS
+  IFS=:
+  set x $ac_tag
+  IFS=$ac_save_IFS
+  shift
+  ac_file=$1
+  shift
+
+  case $ac_mode in
+  :L) ac_source=$1;;
+  :[FH])
+    ac_file_inputs=
+    for ac_f
+    do
+      case $ac_f in
+      -) ac_f="$ac_tmp/stdin";;
+      *) # Look for the file first in the build tree, then in the source tree
+	 # (if the path is not absolute).  The absolute path cannot be DOS-style,
+	 # because $ac_f cannot contain `:'.
+	 test -f "$ac_f" ||
+	   case $ac_f in
+	   [\\/$]*) false;;
+	   *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
+	   esac ||
+	   as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;;
+      esac
+      case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac
+      as_fn_append ac_file_inputs " '$ac_f'"
+    done
+
+    # Let's still pretend it is `configure' which instantiates (i.e., don't
+    # use $as_me), people would be surprised to read:
+    #    /* config.h.  Generated by config.status.  */
+    configure_input='Generated from '`
+	  $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g'
+	`' by configure.'
+    if test x"$ac_file" != x-; then
+      configure_input="$ac_file.  $configure_input"
+      { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5
+$as_echo "$as_me: creating $ac_file" >&6;}
+    fi
+    # Neutralize special characters interpreted by sed in replacement strings.
+    case $configure_input in #(
+    *\&* | *\|* | *\\* )
+       ac_sed_conf_input=`$as_echo "$configure_input" |
+       sed 's/[\\\\&|]/\\\\&/g'`;; #(
+    *) ac_sed_conf_input=$configure_input;;
+    esac
+
+    case $ac_tag in
+    *:-:* | *:-) cat >"$ac_tmp/stdin" \
+      || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;;
+    esac
+    ;;
+  esac
+
+  ac_dir=`$as_dirname -- "$ac_file" ||
+$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$ac_file" : 'X\(//\)[^/]' \| \
+	 X"$ac_file" : 'X\(//\)$' \| \
+	 X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$ac_file" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+  as_dir="$ac_dir"; as_fn_mkdir_p
+  ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+
+  case $ac_mode in
+  :F)
+  #
+  # CONFIG_FILE
+  #
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+# If the template does not know about datarootdir, expand it.
+# FIXME: This hack should be removed a few years after 2.60.
+ac_datarootdir_hack=; ac_datarootdir_seen=
+ac_sed_dataroot='
+/datarootdir/ {
+  p
+  q
+}
+/@datadir@/p
+/@docdir@/p
+/@infodir@/p
+/@localedir@/p
+/@mandir@/p'
+case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in
+*datarootdir*) ac_datarootdir_seen=yes;;
+*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
+$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+  ac_datarootdir_hack='
+  s&@datadir@&$datadir&g
+  s&@docdir@&$docdir&g
+  s&@infodir@&$infodir&g
+  s&@localedir@&$localedir&g
+  s&@mandir@&$mandir&g
+  s&\\\${datarootdir}&$datarootdir&g' ;;
+esac
+_ACEOF
+
+# Neutralize VPATH when `$srcdir' = `.'.
+# Shell code in configure.ac might set extrasub.
+# FIXME: do we really want to maintain this feature?
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+ac_sed_extra="$ac_vpsub
+$extrasub
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+:t
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
+s|@configure_input@|$ac_sed_conf_input|;t t
+s&@top_builddir@&$ac_top_builddir_sub&;t t
+s&@top_build_prefix@&$ac_top_build_prefix&;t t
+s&@srcdir@&$ac_srcdir&;t t
+s&@abs_srcdir@&$ac_abs_srcdir&;t t
+s&@top_srcdir@&$ac_top_srcdir&;t t
+s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
+s&@builddir@&$ac_builddir&;t t
+s&@abs_builddir@&$ac_abs_builddir&;t t
+s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
+$ac_datarootdir_hack
+"
+eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \
+  >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5
+
+test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
+  { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } &&
+  { ac_out=`sed -n '/^[	 ]*datarootdir[	 ]*:*=/p' \
+      "$ac_tmp/out"`; test -z "$ac_out"; } &&
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined" >&5
+$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined" >&2;}
+
+  rm -f "$ac_tmp/stdin"
+  case $ac_file in
+  -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";;
+  *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";;
+  esac \
+  || as_fn_error $? "could not create $ac_file" "$LINENO" 5
+ ;;
+  :H)
+  #
+  # CONFIG_HEADER
+  #
+  if test x"$ac_file" != x-; then
+    {
+      $as_echo "/* $configure_input  */" \
+      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs"
+    } >"$ac_tmp/config.h" \
+      || as_fn_error $? "could not create $ac_file" "$LINENO" 5
+    if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5
+$as_echo "$as_me: $ac_file is unchanged" >&6;}
+    else
+      rm -f "$ac_file"
+      mv "$ac_tmp/config.h" "$ac_file" \
+	|| as_fn_error $? "could not create $ac_file" "$LINENO" 5
+    fi
+  else
+    $as_echo "/* $configure_input  */" \
+      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \
+      || as_fn_error $? "could not create -" "$LINENO" 5
+  fi
+ ;;
+
+
+  esac
+
+
+  case $ac_file$ac_mode in
+    "run":F) chmod +x run ;;
+
+  esac
+done # for ac_tag
+
+
+as_fn_exit 0
+_ACEOF
+ac_clean_files=$ac_clean_files_save
+
+test $ac_write_fail = 0 ||
+  as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5
+
+
+# configure is writing to config.log, and then calls config.status.
+# config.status does its own redirection, appending to config.log.
+# Unfortunately, on DOS this fails, as config.log is still kept open
+# by configure, so config.status won't be able to write to it; its
+# output is simply discarded.  So we exec the FD to /dev/null,
+# effectively closing config.log, so it can be properly (re)opened and
+# appended to by config.status.  When coming back to configure, we
+# need to make the FD available again.
+if test "$no_create" != yes; then
+  ac_cs_success=:
+  ac_config_status_args=
+  test "$silent" = yes &&
+    ac_config_status_args="$ac_config_status_args --quiet"
+  exec 5>/dev/null
+  $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false
+  exec 5>>config.log
+  # Use ||, not &&, to avoid exiting from the if with $? = 1, which
+  # would make configure fail if this is the last instruction.
+  $ac_cs_success || as_fn_exit 1
+fi
+if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5
+$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;}
+fi
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/configure.ac b/com.oracle.truffle.r.pkgs/rJava/jri/configure.ac
new file mode 100644
index 0000000000000000000000000000000000000000..fa8085b930a7f4826d73d669c19a21e04a5759a3
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/configure.ac
@@ -0,0 +1,346 @@
+AC_INIT([JRI],[0.3],[simon.urbanek@r-project.org])
+AC_CONFIG_SRCDIR([src/jri.h])
+AC_CONFIG_HEADER([src/config.h])
+AC_CONFIG_AUX_DIR([tools])
+
+AC_CANONICAL_BUILD
+AC_CANONICAL_HOST
+
+# find R home
+: ${R_HOME=`R RHOME`}
+if test -z "${R_HOME}"; then
+  echo "could not determine R_HOME"
+  exit 1
+fi
+# we attempt to use the same compiler as R did
+RBIN="${R_HOME}/bin/R"
+R_CC=`"${RBIN}" CMD config CC`
+R_CPP=`"${RBIN}" CMD config CPP`
+R_CFLAGS=`"${RBIN}" CMD config CFLAGS`
+
+
+# find R_SHARE_DIR
+: ${R_SHARE_DIR=`"${RBIN}" CMD sh -c 'echo $R_SHARE_DIR'`}
+if test -z "${R_SHARE_DIR}"; then
+  echo "could not determine R_SHARE_DIR"
+  exit 1
+fi
+
+# find R_DOC_DIR
+: ${R_DOC_DIR=`"${RBIN}" CMD sh -c 'echo $R_DOC_DIR'`}
+if test -z "${R_DOC_DIR}"; then
+  echo "could not determine R_DOC_DIR"
+  exit 1
+fi
+
+# find R_INCLUDE_DIR
+: ${R_INCLUDE_DIR=`"${RBIN}" CMD sh -c 'echo $R_INCLUDE_DIR'`}
+if test -z "${R_INCLUDE_DIR}"; then
+  echo "could not determine R_INCLUDE_DIR"
+  exit 1
+fi
+
+# if user did not specify CC then we use R's settings.
+# if CC was set then user is responsible for CFLAGS as well!
+if test -z "${CC}"; then
+   CC="${R_CC}"
+   CPP="${R_CPP}"
+   CFLAGS="${R_CFLAGS}"
+fi
+
+RINC=`"${RBIN}" CMD config --cppflags`
+RLD=`"${RBIN}" CMD config --ldflags`
+
+if test -z "$RLD"; then
+   AC_MSG_ERROR([R was not compiled with --enable-R-shlib
+
+*** You must have libR.so or equivalent in order to use JRI ***
+])
+fi
+
+AC_SUBST(R_HOME)
+AC_SUBST(R_SHARE_DIR)
+AC_SUBST(R_DOC_DIR)
+AC_SUBST(R_INCLUDE_DIR)
+
+AC_PROG_CC
+AC_HEADER_STDC
+
+## RUN_JAVA(variable for the result, parameters)
+## ----------
+## runs the java interpreter ${JAVA_PROG} with specified parameters and
+## saves the output to the supplied variable. The exit value is ignored.
+AC_DEFUN([RUN_JAVA],
+[
+  acx_java_result=
+  if test -z "${JAVA_PROG}"; then
+    echo "$as_me:$LINENO: JAVA_PROG is not set, cannot run java $2" >&AS_MESSAGE_LOG_FD
+  else
+    echo "$as_me:$LINENO: running ${JAVA_PROG} $2" >&AS_MESSAGE_LOG_FD
+    acx_java_result=`${JAVA_PROG} $2 2>&AS_MESSAGE_LOG_FD`
+    echo "$as_me:$LINENO: output: '$acx_java_result'" >&AS_MESSAGE_LOG_FD
+  fi
+  $1=$acx_java_result
+])
+
+if test -n "${CONFIGURED}"; then
+## re-map varibles that don't match
+JAVA_PROG="${JAVA}"
+JAVA_INC="${JAVA_CPPFLAGS}"
+JAVA_LD_PATH="${JAVA_LD_LIBRARY_PATH}"
+else
+
+## find java compiler binaries
+if test -z "${JAVA_HOME}" ; then
+  JAVA_PATH=${PATH}
+else
+  JAVA_PATH=${JAVA_HOME}:${JAVA_HOME}/jre/bin:${JAVA_HOME}/bin:${JAVA_HOME}/../bin:${PATH}
+fi
+
+## if 'java' is not on the PATH or JAVA_HOME, add some guesses as of
+## where java could live
+JAVA_PATH=${JAVA_PATH}:/usr/java/bin:/usr/jdk/bin:/usr/lib/java/bin:/usr/lib/jdk/bin:/usr/local/java/bin:/usr/local/jdk/bin:/usr/local/lib/java/bin:/usr/local/lib/jdk/bin
+AC_PATH_PROGS(JAVA_PROG,java,,${JAVA_PATH})
+## FIXME: we may want to check for jikes, kaffe and others...
+AC_PATH_PROGS(JAVAC,javac,,${JAVA_PATH})
+AC_PATH_PROGS(JAVAH,javah,,${JAVA_PATH})
+AC_PATH_PROGS(JAR,jar,,${JAVA_PATH})
+fi
+
+have_all_java=yes
+if test -z "$JAVA_PROG"; then have_all_java=no; fi
+if test -z "$JAVAC"; then have_all_java=no; fi
+if test -z "$JAVAH"; then have_all_java=no; fi
+if test -z "$JAR"; then have_all_java=no; fi
+if test ${have_all_java} = no; then
+  AC_MSG_ERROR([one or more Java tools are missing.
+
+*** JDK is incomplete! Please make sure you have a complete JDK. JRE is *not* sufficient.])
+fi
+
+## this is where our test-class lives
+getsp_cp=tools
+
+AC_MSG_CHECKING([whether Java interpreter works])
+acx_java_works=no
+if test -n "${JAVA_PROG}" ; then
+  RUN_JAVA(acx_jc_result,[-classpath ${getsp_cp} getsp -test])
+  if test "${acx_jc_result}" = "Test1234OK"; then
+    acx_java_works=yes
+  fi
+  acx_jc_result=
+fi
+
+if test "x`uname -s 2>/dev/null`" = xDarwin; then
+  ## we need to pull that out of R in case re-export fails (which is does on 10.11)                                                                  
+  DYLD_FALLBACK_LIBRARY_PATH=`"${RBIN}" --slave --vanilla -e 'cat(Sys.getenv("DYLD_FALLBACK_LIBRARY_PATH"))'`
+  export DYLD_FALLBACK_LIBRARY_PATH
+fi
+
+
+if test -z "${CONFIGURED}"; then
+
+if test ${acx_java_works} = yes; then
+  AC_MSG_RESULT([yes])
+
+  AC_MSG_CHECKING([for Java environment])
+  ## retrieve JAVA_HOME from Java itself if not set 
+  if test -z "${JAVA_HOME}" ; then
+    RUN_JAVA(JAVA_HOME,[-classpath ${getsp_cp} getsp java.home])
+  fi
+
+  ## the availability of JAVA_HOME will tell us whether it's supported
+  if test -z "${JAVA_HOME}" ; then
+    if test x$acx_java_env_msg != xyes; then
+      AC_MSG_RESULT([not found])
+    fi
+  else
+    AC_MSG_RESULT([in ${JAVA_HOME}])
+
+    case "${host_os}" in
+      darwin*)
+        JAVA_LIBS="-framework JavaVM"
+        JAVA_LD_PATH=
+        ;;
+      *)
+        RUN_JAVA(JAVA_LIBS, [-classpath ${getsp_cp} getsp -libs])
+        JAVA_LIBS="${JAVA_LIBS} -ljvm"
+        RUN_JAVA(JAVA_LD_PATH, [-classpath ${getsp_cp} getsp java.library.path])
+        ;;
+    esac
+    ## note that we actually don't test JAVA_LIBS - we hope that the detection
+    ## was correct. We should also test the functionality for javac.
+
+    have_java=yes
+  fi
+else
+  AC_MSG_RESULT([no])
+  AC_MSG_ERROR([Java not found. Please install JDK 1.4 or later, make sure that the binaries are on the PATH and re-try. If that doesn't work, set JAVA_HOME correspondingly.])
+fi
+
+AC_CHECK_FILE(${JAVA_HOME}/include/jni.h,
+ [JNI_H="${JAVA_HOME}/include"],
+ [AC_CHECK_FILE(${JAVA_HOME}/jni.h,
+  [JNI_H="${JAVA_HOME}"],
+  [AC_CHECK_FILE(${JAVA_HOME}/../include/jni.h,
+   [JNI_H="${JAVA_HOME}/../include"],
+   [AC_MSG_ERROR([jni headers not found. Please make sure you have a proper JDK installed.])
+  ])
+ ])
+])
+
+JAVA_INC="-I${JNI_H}"
+: ${JAVA_CFLAGS=-D_REENTRANT}
+
+# Sun's JDK needs jni_md.h in in addition to jni.h and unfortunately it's stored somewhere else ...
+# this should be become more general at some point - so far we're checking linux and solaris only
+# (well, those are presumably the only platforms supported by Sun's JDK and others don't need this
+# at least as of now - 01/2004)
+jac_found_md=no
+for mddir in . linux solaris ppc irix alpha aix hp-ux genunix cygwin win32 freebsd; do
+AC_CHECK_FILE(${JNI_H}/$mddir/jni_md.h,[JAVA_INC="${JAVA_INC} -I${JNI_H}/$mddir" jac_found_md=yes])
+if test ${jac_found_md} = yes; then break; fi
+done
+
+fi
+
+## the configure variables may contain $(JAVA_HOME) which for testing needs to be replaced by the real path
+if test `echo foo | sed -e 's:foo:bar:'` = bar; then
+   JAVA_INC0=`echo ${JAVA_INC} | sed -e 's:$(JAVA_HOME):'${JAVA_HOME}':g'`
+   JAVA_LIBS0=`echo ${JAVA_LIBS} | sed -e 's:$(JAVA_HOME):'${JAVA_HOME}':g'`
+   JAVA_LD_PATH0=`echo ${JAVA_LD_PATH} | sed -e 's:$(JAVA_HOME):'${JAVA_HOME}':g'`
+else
+   AC_MSG_WARN([sed is not working properly - the configuration may fail])
+   JAVA_INC0="${JAVA_INC}"
+   JAVA_LIBS0="${JAVA_LIBS}"
+   JAVA_LD_PATH0="${JAVA_LD_PATH}"
+fi
+
+LIBS="${LIBS} ${JAVA_LIBS0}"
+CFLAGS="${CFLAGS} ${JAVA_CFLAGS} ${JAVA_INC0}"
+
+AC_MSG_CHECKING([whether JNI programs can be compiled])
+AC_LINK_IFELSE([
+#include <jni.h>
+int main(void) {
+    jobject o;
+    return 0;
+}
+        ],[AC_MSG_RESULT(yes)],
+        [AC_MSG_ERROR([Cannot compile a simple JNI program. See config.log for details.])])
+
+LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${JAVA_LD_PATH0}
+export LD_LIBRARY_PATH
+
+AC_MSG_CHECKING([whether JNI programs can be run])
+AC_RUN_IFELSE([
+#include <jni.h>
+int main(void) {
+    jobject o;
+    return 0;
+}
+        ],[AC_MSG_RESULT(yes)],
+        [AC_MSG_ERROR([Cannot run a simple JNI program - probably your jvm library is in non-standard location or JVM is unsupported. See config.log for details.])])
+
+AC_MSG_CHECKING([JNI data types])
+AC_RUN_IFELSE([AC_LANG_SOURCE([[
+#include <jni.h>
+int main(void) {
+  return (sizeof(int)==sizeof(jint) && sizeof(long)==sizeof(long) && sizeof(jbyte)==sizeof(char) && sizeof(jshort)==sizeof(short) && sizeof(jfloat)==sizeof(float) && sizeof(jdouble)==sizeof(double))?0:1;
+}
+        ]])],[AC_MSG_RESULT([ok])],[AC_MSG_ERROR([One or more JNI types differ from the corresponding native type. You may need to use non-standard compiler flags or a different compiler in order to fix this.])],[])
+
+JNIPREFIX=lib
+CPICF=`"${RBIN}" CMD config CPICFLAGS`
+JNISO=.so
+JNILD=`"${RBIN}" CMD config SHLIB_LDFLAGS`" ${JAVA_LIBS}"
+
+# we need to adjust a few things according to OS ..
+case "${host_os}" in
+  darwin*)
+    JNISO=.jnilib
+    JNILD="-dynamiclib -framework JavaVM"
+    CPICF=-fno-common
+
+    if test -e "${R_HOME}/lib/i386" -a -e "${R_HOME}/lib/ppc" -a -e "${R_HOME}/lib/libR.dylib"; then
+       # we have an universal framework, so we will use stubs and fat lib
+       RLD="-framework R"
+       RINC="-I${R_HOME}/include"
+       # we can even cross-compile, maybe
+       if test -z "${FORCE_NATIVE}"; then
+          # find out the archs of JavaVM and build all of them
+          jarchs=`file -L /System/Library/Frameworks/JavaVM.framework/JavaVM 2>/dev/null | sed -n 's/.*for architecture //p' | sed 's:).*::' | sed 's:ppc7.*:ppc:' | tr '\n' ' '`
+	  jrarchs=''
+	  ## ok, we have Java archs, but R may not be available for all of those
+	  for a in ${jarchs}; do
+	     if test -e "${R_HOME}/lib/$a"; then jrarchs="${jrarchs} $a"; fi
+	  done
+	  ## if have have more than one arch, display info and add -arch flags
+	  if test -n "${jrarchs}"; then
+	     echo "*** building fat JNI with gcc for architectures: ${jrarchs} ***"
+	     echo "*** use FORCE_NATIVE=yes to avoid this and use R settings ***"
+	     CFLAGS=""
+	     LDFLAGS=""
+	     CC="gcc"
+	     for a in ${jrarchs}; do CC="${CC} -arch $a"; done
+	  fi
+       fi
+    fi
+    ;;
+  *)
+    ;;
+esac
+
+origCFLAGS=$CFLAGS
+CFLAGS="${CFLAGS} ${R_CFLAGS} ${RINC}"
+
+AC_MSG_CHECKING([whether Rinterface.h exports R_CStackXXX variables])
+AC_COMPILE_IFELSE([
+#define CSTACK_DEFNS
+#include <R.h>
+#include <Rinterface.h>
+int main(void) {
+    return R_CStackLimit?0:1;
+}
+        ],[AC_MSG_RESULT(yes)
+           DEFFLAGS="${DEFFLAGS} -DRIF_HAS_CSTACK"],
+        [AC_MSG_RESULT(no)])
+
+AC_MSG_CHECKING([whether Rinterface.h exports R_SignalHandlers])
+AC_COMPILE_IFELSE([
+#include <R.h>
+#include <Rinterface.h>
+int main(void) {
+    return R_SignalHandlers;
+}
+        ],[AC_MSG_RESULT(yes)
+           DEFFLAGS="${DEFFLAGS} -DRIF_HAS_RSIGHAND"],
+        [AC_MSG_RESULT(no)])
+
+CFLAGS=${origCFLAGS}
+
+AC_SUBST(JAVA_HOME)
+AC_SUBST(JAVA_PROG)
+AC_SUBST(JAVA_LD_PATH)
+AC_SUBST(JAVA_LIBS)
+AC_SUBST(JAVA_INC)
+AC_SUBST(JAVA_CFLAGS)
+AC_SUBST(JAVAC)
+AC_SUBST(JAVAH)
+AC_SUBST(JAR)
+AC_SUBST(JNILD)
+AC_SUBST(JNISO)
+AC_SUBST(JNIPREFIX)
+AC_SUBST(CPICF)
+AC_SUBST(CFLAGS)
+AC_SUBST(LDFLAGS)
+AC_SUBST(RINC)
+AC_SUBST(RLD)
+AC_SUBST(CC)
+AC_SUBST(DEFFLAGS)
+
+AC_CONFIG_FILES([src/Makefile])
+AC_CONFIG_FILES([Makefile])
+AC_CONFIG_FILES([run], [chmod +x run])
+
+AC_OUTPUT
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/configure.win b/com.oracle.truffle.r.pkgs/rJava/jri/configure.win
new file mode 100644
index 0000000000000000000000000000000000000000..40ed6962c5c40f0a06db319363ee2c23d17be7e2
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/configure.win
@@ -0,0 +1,43 @@
+#!/bin/sh
+
+# if CONFIGURED is set, then we don't attempt to run findjava
+# (useful when building inside rJava)
+if [ -z "$CONFIGURED" ]; then
+    echo "Generate Windows-specific files (src/jvm-w32) ..."
+    make -C src/win32
+
+    if [ $? != 0 ]; then
+	exit 1
+    fi
+
+    echo "Find Java..."
+# findjava honors JAVA_HOME environment variable, so we can safely overwite it 
+    if [ -e src/win32/findjava.exe ]; then
+	JAVA_HOME=`src/win32/findjava -s -f`
+	R_HOME=`src/win32/findjava -R -s -f`
+    fi
+fi
+
+if [ x$JAVA_HOME = x ]; then
+    echo "ERROR: cannot find Java Development Kit." >&2
+    echo "       Please set JAVA_HOME to specify its location manually" >&2
+    exit 1
+fi
+
+if [ x$R_HOME = x ]; then
+    echo "ERROR: cannot find R. Please set R_HOME correspondingly." >&2
+    exit 1
+fi
+
+echo "  JAVA_HOME=$JAVA_HOME"
+echo "  R_HOME=$R_HOME"
+
+echo "JAVAHOME:=$JAVA_HOME" > src/Makefile.wconf
+echo "RHOME:=$R_HOME" >> src/Makefile.wconf
+
+echo "Creating Makefiles ..."
+cp Makefile.win Makefile
+cp src/Makefile.win src/Makefile
+
+echo "Configuration done."
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/examples/rtest.java b/com.oracle.truffle.r.pkgs/rJava/jri/examples/rtest.java
new file mode 100644
index 0000000000000000000000000000000000000000..85f948006a4bd6221585f62b24ad13bcd274c907
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/examples/rtest.java
@@ -0,0 +1,238 @@
+import java.io.*;
+import java.awt.Frame;
+import java.awt.FileDialog;
+
+import java.util.Enumeration;
+
+import org.rosuda.JRI.Rengine;
+import org.rosuda.JRI.REXP;
+import org.rosuda.JRI.RList;
+import org.rosuda.JRI.RVector;
+import org.rosuda.JRI.RMainLoopCallbacks;
+
+class TextConsole implements RMainLoopCallbacks
+{
+    public void rWriteConsole(Rengine re, String text, int oType) {
+        System.out.print(text);
+    }
+    
+    public void rBusy(Rengine re, int which) {
+        System.out.println("rBusy("+which+")");
+    }
+    
+    public String rReadConsole(Rengine re, String prompt, int addToHistory) {
+        System.out.print(prompt);
+        try {
+            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
+            String s=br.readLine();
+            return (s==null||s.length()==0)?s:s+"\n";
+        } catch (Exception e) {
+            System.out.println("jriReadConsole exception: "+e.getMessage());
+        }
+        return null;
+    }
+    
+    public void rShowMessage(Rengine re, String message) {
+        System.out.println("rShowMessage \""+message+"\"");
+    }
+	
+    public String rChooseFile(Rengine re, int newFile) {
+	FileDialog fd = new FileDialog(new Frame(), (newFile==0)?"Select a file":"Select a new file", (newFile==0)?FileDialog.LOAD:FileDialog.SAVE);
+	fd.show();
+	String res=null;
+	if (fd.getDirectory()!=null) res=fd.getDirectory();
+	if (fd.getFile()!=null) res=(res==null)?fd.getFile():(res+fd.getFile());
+	return res;
+    }
+    
+    public void   rFlushConsole (Rengine re) {
+    }
+	
+    public void   rLoadHistory  (Rengine re, String filename) {
+    }			
+    
+    public void   rSaveHistory  (Rengine re, String filename) {
+    }			
+}
+
+public class rtest {
+    public static void main(String[] args) {
+	// just making sure we have the right version of everything
+	if (!Rengine.versionCheck()) {
+	    System.err.println("** Version mismatch - Java files don't match library version.");
+	    System.exit(1);
+	}
+        System.out.println("Creating Rengine (with arguments)");
+		// 1) we pass the arguments from the command line
+		// 2) we won't use the main loop at first, we'll start it later
+		//    (that's the "false" as second argument)
+		// 3) the callbacks are implemented by the TextConsole class above
+		Rengine re=new Rengine(args, false, new TextConsole());
+        System.out.println("Rengine created, waiting for R");
+		// the engine creates R is a new thread, so we should wait until it's ready
+        if (!re.waitForR()) {
+            System.out.println("Cannot load R");
+            return;
+        }
+
+		/* High-level API - do not use RNI methods unless there is no other way
+			to accomplish what you want */
+		try {
+			REXP x;
+			re.eval("data(iris)",false);
+			System.out.println(x=re.eval("iris"));
+			// generic vectors are RVector to accomodate names
+			RVector v = x.asVector();
+			if (v.getNames()!=null) {
+				System.out.println("has names:");
+				for (Enumeration e = v.getNames().elements() ; e.hasMoreElements() ;) {
+					System.out.println(e.nextElement());
+				}
+			}
+			// for compatibility with Rserve we allow casting of vectors to lists
+			RList vl = x.asList();
+			String[] k = vl.keys();
+			if (k!=null) {
+				System.out.println("and once again from the list:");
+				int i=0; while (i<k.length) System.out.println(k[i++]);
+			}			
+
+			// get boolean array
+			System.out.println(x=re.eval("iris[[1]]>mean(iris[[1]])"));
+			// R knows about TRUE/FALSE/NA, so we cannot use boolean[] this way
+			// instead, we use int[] which is more convenient (and what R uses internally anyway)
+			int[] bi = x.asIntArray();
+			{
+			    int i = 0; while (i<bi.length) { System.out.print(bi[i]==0?"F ":(bi[i]==1?"T ":"NA ")); i++; }
+			    System.out.println("");
+			}
+			
+			// push a boolean array
+			boolean by[] = { true, false, false };
+			re.assign("bool", by);
+			System.out.println(x=re.eval("bool"));
+			// asBool returns the first element of the array as RBool
+			// (mostly useful for boolean arrays of the length 1). is should return true
+			System.out.println("isTRUE? "+x.asBool().isTRUE());
+
+			// now for a real dotted-pair list:
+			System.out.println(x=re.eval("pairlist(a=1,b='foo',c=1:5)"));
+			RList l = x.asList();
+			if (l!=null) {
+				int i=0;
+				String [] a = l.keys();
+				System.out.println("Keys:");
+				while (i<a.length) System.out.println(a[i++]);
+				System.out.println("Contents:");
+				i=0;
+				while (i<a.length) System.out.println(l.at(i++));
+			}
+			System.out.println(re.eval("sqrt(36)"));
+		} catch (Exception e) {
+			System.out.println("EX:"+e);
+			e.printStackTrace();
+		}
+		
+		// Part 2 - low-level API - for illustration purposes only!
+		//System.exit(0);
+		
+        // simple assignment like a<-"hello" (env=0 means use R_GlobalEnv)
+        long xp1 = re.rniPutString("hello");
+        re.rniAssign("a", xp1, 0);
+
+        // Example: how to create a named list or data.frame
+        double da[] = {1.2, 2.3, 4.5};
+        double db[] = {1.4, 2.6, 4.2};
+        long xp3 = re.rniPutDoubleArray(da);
+        long xp4 = re.rniPutDoubleArray(db);
+        
+        // now build a list (generic vector is how that's called in R)
+        long la[] = {xp3, xp4};
+        long xp5 = re.rniPutVector(la);
+
+        // now let's add names
+        String sa[] = {"a","b"};
+        long xp2 = re.rniPutStringArray(sa);
+        re.rniSetAttr(xp5, "names", xp2);
+
+        // ok, we have a proper list now
+        // we could use assign and then eval "b<-data.frame(b)", but for now let's build it by hand:       
+        String rn[] = {"1", "2", "3"};
+        long xp7 = re.rniPutStringArray(rn);
+        re.rniSetAttr(xp5, "row.names", xp7);
+        
+        long xp6 = re.rniPutString("data.frame");
+        re.rniSetAttr(xp5, "class", xp6);
+        
+        // assign the whole thing to the "b" variable
+        re.rniAssign("b", xp5, 0);
+        
+        {
+            System.out.println("Parsing");
+            long e=re.rniParse("data(iris)", 1);
+            System.out.println("Result = "+e+", running eval");
+            long r=re.rniEval(e, 0);
+            System.out.println("Result = "+r+", building REXP");
+            REXP x=new REXP(re, r);
+            System.out.println("REXP result = "+x);
+        }
+        {
+            System.out.println("Parsing");
+            long e=re.rniParse("iris", 1);
+            System.out.println("Result = "+e+", running eval");
+            long r=re.rniEval(e, 0);
+            System.out.println("Result = "+r+", building REXP");
+            REXP x=new REXP(re, r);
+            System.out.println("REXP result = "+x);
+        }
+        {
+            System.out.println("Parsing");
+            long e=re.rniParse("names(iris)", 1);
+            System.out.println("Result = "+e+", running eval");
+            long r=re.rniEval(e, 0);
+            System.out.println("Result = "+r+", building REXP");
+            REXP x=new REXP(re, r);
+            System.out.println("REXP result = "+x);
+            String s[]=x.asStringArray();
+            if (s!=null) {
+                int i=0; while (i<s.length) { System.out.println("["+i+"] \""+s[i]+"\""); i++; }
+            }
+        }
+        {
+            System.out.println("Parsing");
+            long e=re.rniParse("rnorm(10)", 1);
+            System.out.println("Result = "+e+", running eval");
+            long r=re.rniEval(e, 0);
+            System.out.println("Result = "+r+", building REXP");
+            REXP x=new REXP(re, r);
+            System.out.println("REXP result = "+x);
+            double d[]=x.asDoubleArray();
+            if (d!=null) {
+                int i=0; while (i<d.length) { System.out.print(((i==0)?"":", ")+d[i]); i++; }
+                System.out.println("");
+            }
+            System.out.println("");
+        }
+        {
+            REXP x=re.eval("1:10");
+            System.out.println("REXP result = "+x);
+            int d[]=x.asIntArray();
+            if (d!=null) {
+                int i=0; while (i<d.length) { System.out.print(((i==0)?"":", ")+d[i]); i++; }
+                System.out.println("");
+            }
+        }
+
+        re.eval("print(1:10/3)");
+        
+	if (true) {
+	    // so far we used R as a computational slave without REPL
+	    // now we start the loop, so the user can use the console
+	    System.out.println("Now the console is yours ... have fun");
+	    re.startMainLoop();
+	} else {
+	    re.end();
+	    System.out.println("end");
+	}
+    }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/examples/rtest2.java b/com.oracle.truffle.r.pkgs/rJava/jri/examples/rtest2.java
new file mode 100644
index 0000000000000000000000000000000000000000..94e2599e54461f09742568b53a7edd2de665ca2b
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/examples/rtest2.java
@@ -0,0 +1,84 @@
+import java.io.*;
+
+import java.awt.*;
+import javax.swing.*;
+
+import org.rosuda.JRI.Rengine;
+import org.rosuda.JRI.REXP;
+import org.rosuda.JRI.RMainLoopCallbacks;
+import org.rosuda.JRI.RConsoleOutputStream;
+
+class TextConsole2 implements RMainLoopCallbacks
+{
+    JFrame f;
+	
+    public JTextArea textarea = new JTextArea();
+
+    public TextConsole2() {
+        f = new JFrame();
+        f.getContentPane().add(new JScrollPane(textarea));
+        f.setSize(new Dimension(800,600));
+        f.show();
+    }
+
+    public void rWriteConsole(Rengine re, String text, int oType) {
+        textarea.append(text);
+    }
+    
+    public void rBusy(Rengine re, int which) {
+        System.out.println("rBusy("+which+")");
+    }
+    
+    public String rReadConsole(Rengine re, String prompt, int addToHistory) {
+        System.out.print(prompt);
+        try {
+            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
+            String s=br.readLine();
+            return (s==null||s.length()==0)?s:s+"\n";
+        } catch (Exception e) {
+            System.out.println("jriReadConsole exception: "+e.getMessage());
+        }
+        return null;
+    }
+    
+    public void rShowMessage(Rengine re, String message) {
+        System.out.println("rShowMessage \""+message+"\"");
+    }
+    
+    public String rChooseFile(Rengine re, int newFile) {
+	FileDialog fd = new FileDialog(f, (newFile==0)?"Select a file":"Select a new file", (newFile==0)?FileDialog.LOAD:FileDialog.SAVE);
+	fd.show();
+	String res=null;
+	if (fd.getDirectory()!=null) res=fd.getDirectory();
+	if (fd.getFile()!=null) res=(res==null)?fd.getFile():(res+fd.getFile());
+	return res;
+    }
+    
+    public void   rFlushConsole (Rengine re) {
+	}
+    
+    public void   rLoadHistory  (Rengine re, String filename) {
+    }			
+    
+    public void   rSaveHistory  (Rengine re, String filename) {
+    }			
+}
+
+public class rtest2 {
+    public static void main(String[] args) {
+        System.out.println("Press <Enter> to continue (time to attach the debugger if necessary)");
+        try { System.in.read(); } catch(Exception e) {};
+        System.out.println("Creating Rengine (with arguments)");
+		Rengine re=new Rengine(args, true, new TextConsole2());
+        System.out.println("Rengine created, waiting for R");
+        if (!re.waitForR()) {
+            System.out.println("Cannot load R");
+            return;
+        }
+		System.out.println("re-routing stdout/err into R console");
+		System.setOut(new PrintStream(new RConsoleOutputStream(re, 0)));
+		System.setErr(new PrintStream(new RConsoleOutputStream(re, 1)));
+		
+		System.out.println("Letting go; use main loop from now on");
+    }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/mkdist b/com.oracle.truffle.r.pkgs/rJava/jri/mkdist
new file mode 100755
index 0000000000000000000000000000000000000000..22b0c68e7626e0f486bb8c1299496fa2e93238f6
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/mkdist
@@ -0,0 +1,48 @@
+#!/bin/sh
+
+PNAME=JRI
+SWD=`pwd`
+echo "Removing previous dist ..."
+rm -rf /tmp/${PNAME}
+echo "Copying package base ..."
+mkdir /tmp/${PNAME}
+cp -r . /tmp/${PNAME}
+
+rm -f /tmp/${PNAME}/mkdist
+
+cd /tmp/${PNAME}
+
+if [ -e configure ]; then
+    echo "*skipping* autoconf (configure already present)"
+else 
+    echo "Running autoconf ..."
+    rm -rf autom4te* acloc*
+    autoreconf
+#autoheader
+#autoconf
+fi
+rm -rf autom4te* acloc*
+
+echo "Compiling getsp ..."
+if [ ! -e tools/getsp.class ]; then
+    cd tools
+    javac -target 1.2 -source 1.2 getsp.java
+    cd ..
+fi
+
+echo "Removing CVS/SVN and backup stuff ..."
+rm -rf `find . -name CVS -or -name .svn -or -name \*~`
+
+echo "Updating version ..."
+VER=`sed -n -e 's/.*JRI v\([0-9.-]\{1,\}\).*/\1/p' src/jri.h`
+echo "$PNAME version ${VER}"
+# cat DESCRIPTION| sed "s/Version:.*/Version: ${VER}/" > d
+# mv d DESCRIPTION
+echo "Creating package ..."
+cd ..
+tar fcz ${PNAME}_${VER}.tar.gz ${PNAME}
+cd ${SWD}
+cp /tmp/${PNAME}_${VER}.tar.gz ..
+rm -rf /tmp/${PNAME}
+echo "Done."
+ls -l ../${PNAME}_${VER}.tar.gz
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/package-info.java b/com.oracle.truffle.r.pkgs/rJava/jri/package-info.java
new file mode 100644
index 0000000000000000000000000000000000000000..e020550890a87ec89f6c91a4e0c1c499ce8da6df
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/package-info.java
@@ -0,0 +1,5 @@
+/** 
+ * low level Java/R Interface
+ */
+package org.rosuda.JRI ;
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/run.in b/com.oracle.truffle.r.pkgs/rJava/jri/run.in
new file mode 100644
index 0000000000000000000000000000000000000000..db0276a3f4f3d764b092b0a3fde8dc214022198a
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/run.in
@@ -0,0 +1,34 @@
+#!/bin/sh
+
+R_HOME=@R_HOME@
+
+R_SHARE_DIR=@R_SHARE_DIR@
+export R_SHARE_DIR
+R_INCLUDE_DIR=@R_INCLUDE_DIR@
+export R_INCLUDE_DIR
+R_DOC_DIR=@R_DOC_DIR@
+export R_DOC_DIR
+
+JRI_LD_PATH=${R_HOME}/lib:${R_HOME}/bin:@JAVA_LD_PATH@
+if test -z "$LD_LIBRARY_PATH"; then
+  LD_LIBRARY_PATH=$JRI_LD_PATH
+else
+  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$JRI_LD_PATH
+fi
+JAVA=@JAVA_PROG@
+
+: ${CLASSPATH=.:examples}
+
+export R_HOME
+export LD_LIBRARY_PATH
+
+if [ -z "$1" ]; then
+    echo ""
+    echo " Usage: run <class> [...]"
+    echo ""
+    echo " For example: ./run rtest"
+    echo " Set CLASSPATH variable if other than .:examples is desired"
+    echo ""
+else
+    ${JAVA} -Djava.library.path=.:@JAVA_LD_PATH@ -cp ${CLASSPATH}:src/JRI.jar:JRI.jar $*
+fi
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/src/Makefile.all b/com.oracle.truffle.r.pkgs/rJava/jri/src/Makefile.all
new file mode 100644
index 0000000000000000000000000000000000000000..3e9c66fdc90580d27649743a21779cc8f46682c9
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/src/Makefile.all
@@ -0,0 +1,50 @@
+# JRI - Java/R Interface      experimental!
+#--------------------------------------------------------------------------
+
+JRI_JSRC=$(wildcard ../*.java)
+TARGETS=$(JNIPREFIX)jri$(JNISO) JRI.jar
+
+# we need to force JDK 1.4 for compatibility (or 1.6 for J9)
+JFLAGS+=-target 1.6 -source 1.6
+
+all: $(TARGETS)
+
+JRI.jar: $(JRI_JSRC) $(JNIPREFIX)jri$(JNISO)
+	$(JAVAC) $(JFLAGS) -d . $(JRI_JSRC)
+	$(JAR) fc $@ org $(JNIPREFIX)jri$(JNISO)
+
+org_rosuda_JRI_Rengine.h: org/rosuda/JRI/Rengine.class
+	$(JAVAH) -d . -classpath . org.rosuda.JRI.Rengine
+
+Rcallbacks.o: Rcallbacks.c Rcallbacks.h globals.h org_rosuda_JRI_Rengine.h
+	$(CC) -c -o $@ $< $(CFLAGS) $(CPICF) $(JAVAINC) $(RINC)
+
+Rinit.o: Rinit.c Rinit.h Rcallbacks.h
+	$(CC) -c -o $@ $< $(CFLAGS) $(CPICF) $(RINC)
+
+globals.o: globals.c globals.h
+	$(CC) -c -o $@ $< $(CFLAGS) $(CPICF) $(JAVAINC)
+
+rjava.o: rjava.c rjava.h
+	$(CC) -c -o $@ $< $(CFLAGS) $(CPICF) $(JAVAINC)
+
+Rengine.o: Rengine.c org_rosuda_JRI_Rengine.h globals.h Rcallbacks.h Rinit.h
+	$(CC) -c -o $@ Rengine.c $(CFLAGS) $(CPICF) $(JAVAINC) $(RINC)
+
+jri.o: jri.c
+	$(CC) -c -o $@ jri.c $(CFLAGS) $(CPICF) $(JAVAINC) $(RINC)
+
+$(JNIPREFIX)jri$(JNISO): Rengine.o jri.o Rcallbacks.o Rinit.o globals.o rjava.o $(JRIDEPS)
+	$(CC) -o $@ $^ $(LDFLAGS) $(JNILD) $(RLD)
+
+win32/libjvm.dll.a:
+	make -C win32 libjvm.dll.a
+
+org/rosuda/JRI/Rengine.class org/rosuda/JRI/REXP.class org/rosuda/JRI/Mutex.class: $(JRI_JSRC)
+	$(JAVAC) $(JFLAGS) -d . $^
+
+clean:
+	rm -rf $(TARGETS) org *.o *~ org_rosuda_JRI_Rengine.h *$(JNISO) *.class *~
+
+.PHONY: clean all
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/src/Makefile.in b/com.oracle.truffle.r.pkgs/rJava/jri/src/Makefile.in
new file mode 100644
index 0000000000000000000000000000000000000000..ec91aaef62dd19abbb2045e9031649ba0fa10945
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/src/Makefile.in
@@ -0,0 +1,25 @@
+# JRI - Java/R Interface      experimental!
+#--------------------------------------------------------------------------
+
+#--- comment out the following for non-debug version
+CFLAGS+=-g
+
+CC=@CC@
+CFLAGS+=-Iinclude @DEFFLAGS@ @CFLAGS@ @JAVA_CFLAGS@
+LDFLAGS+=@LDFLAGS@
+
+CC=@CC@
+RHOME=@R_HOME@
+JAVAC=@JAVAC@
+JAVAH=@JAVAH@
+JAVAINC=@JAVA_INC@
+JAR=@JAR@
+
+RINC=@RINC@ -I@R_INCLUDE_DIR@
+RLD=@RLD@
+JNILD=@JNILD@
+JNISO=@JNISO@
+JNIPREFIX=@JNIPREFIX@
+CPICF=@CPICF@
+
+include Makefile.all
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/src/Makefile.win b/com.oracle.truffle.r.pkgs/rJava/jri/src/Makefile.win
new file mode 100644
index 0000000000000000000000000000000000000000..a443119a0a338b4c29b1a595713d123c80cde739
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/src/Makefile.win
@@ -0,0 +1,6 @@
+# Windows-specific part of the Makefile
+
+include $(R_HOME)/etc$(R_ARCH)/Makeconf
+include Makefile.wconf
+include ../Makevars.win
+include Makefile.all
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/src/Rcallbacks.c b/com.oracle.truffle.r.pkgs/rJava/jri/src/Rcallbacks.c
new file mode 100644
index 0000000000000000000000000000000000000000..fccb68819d768535bced77c9350343e3dfb2b54d
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/src/Rcallbacks.c
@@ -0,0 +1,408 @@
+#include <stdio.h>
+#include <ctype.h>
+
+#include "jri.h"
+#include "globals.h"
+#include "Rdecl.h"
+#include "Rcallbacks.h"
+
+#include "org_rosuda_JRI_Rengine.h"
+#include <R_ext/Parse.h>
+
+#ifndef Win32
+#include <R_ext/eventloop.h>
+#endif
+
+
+#ifdef Win32
+#include <R_ext/RStartup.h>
+#else
+/* from Defn.h (do we still need it? Re_CleanUp is commented out ...)
+   extern Rboolean R_Interactive; */
+#endif
+
+#if R_VERSION < R_Version(2,6,0)
+#ifndef checkArity
+#define checkArity               Rf_checkArity
+#endif
+#else
+#define checkArity(X,Y)
+#endif
+
+#ifndef errorcall
+#define errorcall                Rf_errorcall
+#endif
+
+/* this method is used rather for debugging purposes - it finds the correct JNIEnv for the current thread. we still have some threading issues to solve, becuase eenv!=env should never happen (uncontrolled), because concurrency issues arise */
+static JavaVM *jvm=0;
+
+JNIEnv *checkEnvironment()
+{
+    JNIEnv *env;
+    jsize l;
+    jint res;
+    
+    if (!jvm) { /* we're hoping that the JVM pointer won't change :P we fetch it just once */
+        res= JNI_GetCreatedJavaVMs(&jvm, 1, &l);
+        if (res!=0) {
+            fprintf(stderr, "JNI_GetCreatedJavaVMs failed! (%d)\n",(int)res); return 0;
+        }
+        if (l<1) {
+            fprintf(stderr, "JNI_GetCreatedJavaVMs said there's no JVM running!\n"); return 0;
+        }
+    }
+    res = (*jvm)->AttachCurrentThread(jvm, (void*) &env, 0);
+    if (res!=0) {
+        fprintf(stderr, "AttachCurrentThread failed! (%d)\n",(int)res); return 0;
+    }
+#ifdef JRI_DEBUG
+    if (eenv!=env)
+        fprintf(stderr, "Warning! eenv=%x, but env=%x - different environments encountered!\n", eenv, env);
+#endif
+    return env;
+}
+
+int Re_ReadConsole(RCCONST char *prompt, unsigned char *buf, int len, int addtohistory)
+{
+	jstring r,s;
+	jmethodID mid;
+    JNIEnv *lenv=checkEnvironment();
+	
+    if (!lenv || !engineObj) return -1;
+	
+	jri_checkExceptions(lenv, 1);
+	mid=(*lenv)->GetMethodID(eenv, engineClass, "jriReadConsole", "(Ljava/lang/String;I)Ljava/lang/String;");
+#ifdef JRI_DEBUG
+	printf("jriReadconsole mid=%x\n", mid);
+#endif
+	jri_checkExceptions(lenv, 0);
+	if (!mid) return -1;
+		
+	s=(*lenv)->NewStringUTF(eenv, prompt);
+	r=(jstring) (*lenv)->CallObjectMethod(lenv, engineObj, mid, s, addtohistory);
+	jri_checkExceptions(lenv, 1);
+	(*lenv)->DeleteLocalRef(lenv, s);
+	jri_checkExceptions(lenv, 0);
+	if (r) {
+		const char *c=(*lenv)->GetStringUTFChars(lenv, r, 0);
+		if (!c) return -1;
+		{
+			int l=strlen(c);
+			strncpy((char*)buf, c, (l>len-1)?len-1:l);
+			buf[(l>len-1)?len-1:l]=0;
+#ifdef JRI_DEBUG
+			printf("Re_ReadConsole succeeded: \"%s\"\n",buf);
+#endif
+		}
+		(*lenv)->ReleaseStringUTFChars(lenv, r, c);
+		(*lenv)->DeleteLocalRef(lenv, r);
+		return 1;
+    }
+    return -1;
+}
+
+void Re_Busy(int which)
+{
+	jmethodID mid;
+    JNIEnv *lenv=checkEnvironment();
+    jri_checkExceptions(lenv, 1);
+    mid=(*lenv)->GetMethodID(lenv, engineClass, "jriBusy", "(I)V");
+    jri_checkExceptions(lenv, 0);
+#ifdef JRI_DEBUG
+	printf("jriBusy mid=%x\n", mid);
+#endif
+	if (!mid) return;
+	(*lenv)->CallVoidMethod(lenv, engineObj, mid, which);
+    jri_checkExceptions(lenv, 1);
+}
+
+void Re_WriteConsoleEx(RCCONST char *buf, int len, int oType)
+{
+    JNIEnv *lenv=checkEnvironment();
+    jri_checkExceptions(lenv, 1);
+    {
+      jstring s=(*lenv)->NewStringUTF(lenv, buf);
+      jmethodID mid=(*lenv)->GetMethodID(lenv, engineClass, "jriWriteConsole", "(Ljava/lang/String;I)V");
+      jri_checkExceptions(lenv, 0);
+#ifdef JRI_DEBUG
+      printf("jriWriteConsole mid=%x\n", mid);
+#endif
+      if (!mid) return;
+      (*lenv)->CallVoidMethod(lenv, engineObj, mid, s, oType);
+      jri_checkExceptions(lenv, 1);
+      (*lenv)->DeleteLocalRef(lenv, s);
+    }
+}
+
+/* old-style WriteConsole (for old R versions only) */
+void Re_WriteConsole(RCCONST char *buf, int len)
+{
+    Re_WriteConsoleEx(buf, len, 0);
+}
+
+/* Indicate that input is coming from the console */
+void Re_ResetConsole()
+{
+}
+
+/* Stdio support to ensure the console file buffer is flushed */
+void Re_FlushConsole()
+{
+    JNIEnv *lenv=checkEnvironment();
+    jri_checkExceptions(lenv, 1);
+    {
+      jmethodID mid=(*lenv)->GetMethodID(lenv, engineClass, "jriFlushConsole", "()V");
+      jri_checkExceptions(lenv, 0);
+#ifdef JRI_DEBUG
+      printf("jriFlushConsole mid=%x\n", mid);
+#endif
+      if (!mid) return;
+      (*lenv)->CallVoidMethod(lenv, engineObj, mid);
+      jri_checkExceptions(lenv, 1);
+    }
+}
+
+/* Reset stdin if the user types EOF on the console. */
+void Re_ClearerrConsole()
+{
+}
+
+int Re_ChooseFile(int new, char *buf, int len)
+{
+    JNIEnv *lenv=checkEnvironment();
+	
+    if (lenv && engineObj) {
+		jmethodID mid;
+		jri_checkExceptions(lenv, 1);
+		mid=(*lenv)->GetMethodID(eenv, engineClass, "jriChooseFile", "(I)Ljava/lang/String;");
+#ifdef JRI_DEBUG
+		printf("jriChooseFile mid=%x\n", mid);
+#endif
+		jri_checkExceptions(lenv, 0);
+		if (mid) {
+			jstring r=(jstring) (*lenv)->CallObjectMethod(lenv, engineObj, mid, new);
+			jri_checkExceptions(lenv, 1);
+			if (r) {
+				int slen=0;
+				const char *c=(*lenv)->GetStringUTFChars(lenv, r, 0);
+				if (c) {
+					slen=strlen(c);
+					strncpy(buf, c, (slen>len-1)?len-1:slen);
+					buf[(slen>len-1)?len-1:slen]=0;
+#ifdef JRI_DEBUG
+					printf("Re_ChooseFile succeeded: \"%s\"\n",buf);
+#endif
+				}
+				(*lenv)->ReleaseStringUTFChars(lenv, r, c);
+				(*lenv)->DeleteLocalRef(lenv, r);
+				jri_checkExceptions(lenv, 0);
+				return slen;
+			} else return 0;
+		}
+    }
+	
+	/* "native" fallback if there's no such method */
+	{
+		int namelen;
+		char *bufp;
+		R_ReadConsole("Enter file name: ", (unsigned char *)buf, len, 0);
+		namelen = strlen(buf);
+		bufp = &buf[namelen - 1];
+		while (bufp >= buf && isspace((int)*bufp))
+			*bufp-- = '\0';
+		return strlen(buf);
+	}
+}
+
+void Re_ShowMessage(RCCONST char *buf)
+{
+	jstring s;
+	jmethodID mid;
+    JNIEnv *lenv=checkEnvironment();
+	
+    jri_checkExceptions(lenv, 1);
+    s=(*lenv)->NewStringUTF(lenv, buf);
+    mid=(*lenv)->GetMethodID(lenv, engineClass, "jriShowMessage", "(Ljava/lang/String;)V");
+    jri_checkExceptions(lenv, 0);
+#ifdef JGR_DEBUG
+    printf("jriShowMessage mid=%x\n", mid);
+#endif
+    if (mid)
+        (*lenv)->CallVoidMethod(eenv, engineObj, mid, s);
+    jri_checkExceptions(lenv, 0);
+    if (s) (*lenv)->DeleteLocalRef(eenv, s);
+}
+
+void Re_read_history(char *buf)
+{
+}
+
+void Re_loadhistory(SEXP call, SEXP op, SEXP args, SEXP env)
+{
+	jmethodID mid;
+	jstring s;
+    JNIEnv *lenv=checkEnvironment();
+	
+    jri_checkExceptions(lenv, 1);
+    mid=(*lenv)->GetMethodID(lenv, engineClass, "jriLoadHistory", "(Ljava/lang/String;)V");
+    jri_checkExceptions(lenv, 0);
+#ifdef JRI_DEBUG
+	printf("jriLoadHistory mid=%x\n", mid);
+#endif
+	if (!mid) {
+#ifdef JRI_DEBUG
+		printf("can't find jriLoadHistory method\n");
+#endif
+		return;
+	}
+
+	{
+		SEXP sfile;
+		const char *p;
+
+		checkArity(op, args);
+		sfile = CAR(args);
+		if (!isString(sfile) || LENGTH(sfile) < 1)
+			errorcall(call, "invalid file argument");
+		p = R_ExpandFileName((char*)CHAR(STRING_ELT(sfile, 0)));
+		if(strlen(p) > PATH_MAX - 1)
+			errorcall(call, "file argument is too long");
+		s=(*lenv)->NewStringUTF(lenv, p);
+	}
+	(*lenv)->CallVoidMethod(lenv, engineObj, mid, s);
+    jri_checkExceptions(lenv, 1);
+	if (s)
+		(*lenv)->DeleteLocalRef(lenv, s);
+}
+
+void Re_savehistory(SEXP call, SEXP op, SEXP args, SEXP env)
+{
+	jmethodID mid;
+	jstring s;
+    JNIEnv *lenv=checkEnvironment();
+	
+    jri_checkExceptions(lenv, 1);
+    mid=(*lenv)->GetMethodID(lenv, engineClass, "jriSaveHistory", "(Ljava/lang/String;)V");
+    jri_checkExceptions(lenv, 0);
+#ifdef JRI_DEBUG
+	printf("jriSaveHistory mid=%x\n", mid);
+#endif
+	if (!mid)
+		errorcall(call, "can't find jriSaveHistory method");		
+
+	{
+		SEXP sfile;
+		const char *p;
+		
+		checkArity(op, args);
+		sfile = CAR(args);
+		if (!isString(sfile) || LENGTH(sfile) < 1)
+			errorcall(call, "invalid file argument");
+		p = R_ExpandFileName(CHAR(STRING_ELT(sfile, 0)));
+		if(strlen(p) > PATH_MAX - 1)
+			errorcall(call, "file argument is too long");	
+		s=(*lenv)->NewStringUTF(lenv, p);
+	}
+	(*lenv)->CallVoidMethod(lenv, engineObj, mid, s);
+    jri_checkExceptions(lenv, 1);
+	if (s)
+		(*lenv)->DeleteLocalRef(lenv, s);
+	
+	/*
+    strcpy(file, p);
+        write_history(file);
+        history_truncate_file(file, R_HistorySize);
+     */
+}
+
+
+/*
+ R_CleanUp is invoked at the end of the session to give the user the
+ option of saving their data.
+ If ask == SA_SAVEASK the user should be asked if possible (and this
+                                                            option should not occur in non-interactive use).
+ If ask = SA_SAVE or SA_NOSAVE the decision is known.
+ If ask = SA_DEFAULT use the SaveAction set at startup.
+ In all these cases run .Last() unless quitting is cancelled.
+ If ask = SA_SUICIDE, no save, no .Last, possibly other things.
+ */
+
+/*
+void Re_CleanUp(SA_TYPE saveact, int status, int runLast)
+{
+    unsigned char buf[1024];
+    char * tmpdir;
+
+    if(saveact == SA_DEFAULT)
+        saveact = SaveAction;
+
+    if(saveact == SA_SAVEASK) {
+        if(R_Interactive) {
+qask:
+            R_ClearerrConsole();
+            R_FlushConsole();
+            R_ReadConsole("Save workspace image? [y/n/c]: ",
+                          buf, 128, 0);
+            switch (buf[0]) {
+                case 'y':
+                case 'Y':
+                    saveact = SA_SAVE;
+                    break;
+                case 'n':
+                case 'N':
+                    saveact = SA_NOSAVE;
+                    break;
+                case 'c':
+                case 'C':
+                    jump_to_toplevel();
+                    break;
+                default:
+                    goto qask;
+            }
+        } else
+            saveact = SaveAction;
+    }
+    switch (saveact) {
+        case SA_SAVE:
+            if(runLast) R_dot_Last();
+            if(R_DirtyImage) R_SaveGlobalEnv();
+                 stifle_history(R_HistorySize);
+                 write_history(R_HistoryFile);
+                 break;
+        case SA_NOSAVE:
+            if(runLast) R_dot_Last();
+            break;
+        case SA_SUICIDE:
+        default:
+            break;
+    }
+    R_RunExitFinalizers();
+    CleanEd();
+    if(saveact != SA_SUICIDE) KillAllDevices();
+    if((tmpdir = getenv("R_SESSION_TMPDIR"))) {
+        snprintf((char *)buf, 1024, "rm -rf %s", tmpdir);
+        R_system((char *)buf);
+    }
+    if(saveact != SA_SUICIDE && R_CollectWarnings)
+        PrintWarnings();
+    fpu_setup(FALSE);
+
+    exit(status);
+}
+
+void Rstd_Suicide(char *s)
+{
+    REprintf("Fatal error: %s\n", s);
+    R_CleanUp(SA_SUICIDE, 2, 0);
+}
+
+*/
+int Re_ShowFiles(int nfile, 		/* number of files */
+                 RCCONST char **file,	/* array of filenames */
+                 RCCONST char **headers,/* the `headers' args of file.show. Printed before each file. */
+                 RCCONST char *wtitle,  /* title for window = `title' arg of file.show */
+                 Rboolean del,	        /* should files be deleted after use? */
+                 RCCONST char *pager)	/* pager to be used */
+{
+    return 1;
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/src/Rcallbacks.h b/com.oracle.truffle.r.pkgs/rJava/jri/src/Rcallbacks.h
new file mode 100644
index 0000000000000000000000000000000000000000..9bd75a8d2a9260f279ceef371b7fc2214bdbcabe
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/src/Rcallbacks.h
@@ -0,0 +1,30 @@
+#ifndef __R_CALLBACKS__H__
+#define __R_CALLBACKS__H__
+
+#include <R.h>
+#include <Rinternals.h>
+#include <Rversion.h>
+
+/* functions provided as R callbacks */
+
+#if R_VERSION < R_Version(2,7,0)
+#define RCCONST
+#else
+#define RCCONST const
+#endif
+
+int  Re_ReadConsole(RCCONST char *prompt, unsigned char *buf, int len, int addtohistory);
+void Re_Busy(int which);
+void Re_WriteConsole(RCCONST char *buf, int len);
+void Re_WriteConsoleEx(RCCONST char *buf, int len, int oType);
+void Re_ResetConsole();
+void Re_FlushConsole();
+void Re_ClearerrConsole();
+int  Re_ChooseFile(int new, char *buf, int len);
+void Re_ShowMessage(RCCONST char *buf);
+void Re_read_history(char *buf);
+void Re_loadhistory(SEXP call, SEXP op, SEXP args, SEXP env);
+void Re_savehistory(SEXP call, SEXP op, SEXP args, SEXP env);
+int  Re_ShowFiles(int nfile, RCCONST char **file, RCCONST char **headers, RCCONST char *wtitle, Rboolean del, RCCONST char *pager);
+
+#endif
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/src/Rdecl.h b/com.oracle.truffle.r.pkgs/rJava/jri/src/Rdecl.h
new file mode 100644
index 0000000000000000000000000000000000000000..48910f2ad7b798060892d0238664a4d414a38185
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/src/Rdecl.h
@@ -0,0 +1,12 @@
+#ifndef __RDECL_H__
+#define __RDECL_H__
+
+/* declarations from R internals or other include files */
+/* last update: R 2.4.0 */
+
+void run_Rmainloop(void); /* main/main.c */
+int  R_ReadConsole(char*, unsigned char*, int, int); /* include/Defn.h */
+void Rf_checkArity(SEXP, SEXP); /* include/Defn.h */
+int  Rf_initialize_R(int ac, char **av); /* include/Rembedded.h */
+
+#endif
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/src/Rengine.c b/com.oracle.truffle.r.pkgs/rJava/jri/src/Rengine.c
new file mode 100644
index 0000000000000000000000000000000000000000..4a053def69d986107dc8e3d279a1dfc74f71dcba
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/src/Rengine.c
@@ -0,0 +1,660 @@
+/* Rengine - implements native rni methods called from the Rengine class */
+#include <stdio.h>
+
+#include "jri.h"
+#include "org_rosuda_JRI_Rengine.h"
+#include "rjava.h"
+#include <Rversion.h>
+#include <R_ext/Parse.h>
+#ifndef WIN32 /* this is for interrupt handing since GD uses R_interrupts_pending */
+#include <R_ext/GraphicsEngine.h>
+/* Before R 2.7.0 R_interrupts_pending was not included, though */
+#if R_VERSION < R_Version(2,7,0)
+LibExtern int R_interrupts_pending;
+#endif
+#endif
+
+/* the # of arguments to R_ParseVector changed since R 2.5.0 */
+#if R_VERSION < R_Version(2,5,0)
+#define RS_ParseVector R_ParseVector
+#else
+#define RS_ParseVector(A,B,C) R_ParseVector(A,B,C,R_NilValue)
+#endif
+
+#include "Rcallbacks.h"
+#include "Rinit.h"
+#include "globals.h"
+#include "Rdecl.h"
+
+#ifdef Win32
+#include <windows.h>
+#ifdef _MSC_VER
+__declspec(dllimport) int UserBreak;
+#else
+#ifndef WIN64
+#define UserBreak     (*_imp__UserBreak)
+#endif
+extern int UserBreak;
+#endif
+#else
+/* for R_runHandlers */
+#include <R_ext/eventloop.h>
+#include <signal.h>
+#include <unistd.h>
+#endif
+
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniGetVersion
+(JNIEnv *env, jclass this)
+{
+    return (jlong) JRI_API;
+}
+
+JNIEXPORT jint JNICALL Java_org_rosuda_JRI_Rengine_rniSetupR
+  (JNIEnv *env, jobject this, jobjectArray a)
+{
+      int initRes;
+      char *fallbackArgv[]={"Rengine",0};
+      char **argv=fallbackArgv;
+      int argc=1;
+      
+#ifdef JRI_DEBUG
+      printf("rniSetupR\n");
+#endif
+	  
+      engineObj=(*env)->NewGlobalRef(env, this);
+      engineClass=(*env)->NewGlobalRef(env, (*env)->GetObjectClass(env, engineObj));
+      eenv=env;
+      
+      if (a) { /* retrieve the content of the String[] and construct argv accordingly */
+          int len = (int)(*env)->GetArrayLength(env, a);
+          if (len>0) {              
+              int i=0;
+              argv=(char**) malloc(sizeof(char*)*(len+2));
+              argv[0]=fallbackArgv[0];
+              while (i < len) {
+                  jobject o=(*env)->GetObjectArrayElement(env, a, i);
+                  i++;
+                  if (o) {
+                      const char *c;
+                      c=(*env)->GetStringUTFChars(env, o, 0);
+                      if (!c)
+                          argv[i]="";
+                      else {
+			  argv[i] = strdup(c);
+                          (*env)->ReleaseStringUTFChars(env, o, c);
+                      }
+                  } else
+                      argv[i]="";
+              }
+              argc=len+1;
+              argv[argc]=0;
+          }
+      }
+
+      if (argc==2 && !strcmp(argv[1],"--zero-init")) {/* special case for direct embedding (exp!) */
+	initRinside();
+	return 0;
+      }
+      
+      initRes=initR(argc, argv);
+      /* we don't release the argv in case R still needs it later (even if it shouldn't), but it's not really a significant leak */
+      
+      return initRes;
+}
+
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniParse
+  (JNIEnv *env, jobject this, jstring str, jint parts)
+{
+      ParseStatus ps;
+      SEXP pstr, cv;
+
+      PROTECT(cv=jri_getString(env, str));
+#ifdef JRI_DEBUG
+      printf("parsing \"%s\"\n", CHAR(STRING_ELT(cv,0)));
+#endif
+      pstr=RS_ParseVector(cv, parts, &ps);
+#ifdef JRI_DEBUG
+      printf("parse status=%d, result=%x, type=%d\n", ps, (int) pstr, (pstr!=0)?TYPEOF(pstr):0);
+#endif
+      UNPROTECT(1);
+
+      return SEXP2L(pstr);
+}
+
+/** 
+ * Evaluates one expression or a list of expressions
+ *
+ * @param exp long reflection of the expression to evaluate
+ * @param rho long reflection of the environment where to evaluate
+ * 
+ * @return 0 if an evaluation error ocurred or exp is 0
+ */
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniEval
+  (JNIEnv *env, jobject this, jlong exp, jlong rho)
+{
+      SEXP es = R_NilValue, exps = L2SEXP(exp);
+      SEXP eval_env = L2SEXP(rho);
+      int er = 0;
+      int i = 0, l;
+
+      /* invalid (NULL) expression (parse error, ... ) */
+      if (!exp) return 0;
+
+      if (TYPEOF(exps) == EXPRSXP) { 
+      	  /* if the object is a list of exps, eval them one by one */
+          l = LENGTH(exps);
+          while (i < l) {
+              es = R_tryEval(VECTOR_ELT(exps,i), eval_env, &er);
+              
+              /* an error occured, no need to continue */
+              if (er) return 0;
+              i++;
+          }
+      } else
+          es = R_tryEval(exps, eval_env, &er);
+      
+      /* er is just a flag - on error return 0 */
+      if (er) return 0;
+      
+      return SEXP2L(es);
+}
+
+struct safeAssign_s {
+    SEXP sym, val, rho;
+};
+
+static void safeAssign(void *data) {
+    struct safeAssign_s *s = (struct safeAssign_s*) data;
+    defineVar(s->sym, s->val, s->rho);
+}
+
+JNIEXPORT jboolean JNICALL Java_org_rosuda_JRI_Rengine_rniAssign
+(JNIEnv *env, jobject this, jstring symName, jlong valL, jlong rhoL)
+{
+    struct safeAssign_s s;
+  
+    s.sym = jri_installString(env, symName);
+    if (!s.sym || s.sym == R_NilValue) return JNI_FALSE;
+
+    s.rho = rhoL ? L2SEXP(rhoL) : R_GlobalEnv;
+    s.val = valL ? L2SEXP(valL) : R_NilValue;
+   
+    /* we have to use R_ToplevelExec because defineVar may fail on locked bindings */
+    return R_ToplevelExec(safeAssign, (void*) &s) ? JNI_TRUE : JNI_FALSE;
+}
+
+JNIEXPORT void JNICALL Java_org_rosuda_JRI_Rengine_rniProtect
+(JNIEnv *env, jobject this, jlong exp)
+{
+	PROTECT(L2SEXP(exp));
+}
+
+JNIEXPORT void JNICALL Java_org_rosuda_JRI_Rengine_rniUnprotect
+(JNIEnv *env, jobject this, jint count)
+{
+	UNPROTECT(count);
+}
+
+JNIEXPORT void JNICALL Java_org_rosuda_JRI_Rengine_rniRelease
+(JNIEnv *env, jobject this, jlong exp)
+{
+	if (exp) R_ReleaseObject(L2SEXP(exp));
+}
+
+JNIEXPORT void JNICALL Java_org_rosuda_JRI_Rengine_rniPreserve
+(JNIEnv *env, jobject this, jlong exp)
+{
+	if (exp) R_PreserveObject(L2SEXP(exp));
+}
+
+JNIEXPORT void JNICALL Java_org_rosuda_JRI_Rengine_rniPrintValue
+(JNIEnv *env, jobject this, jlong exp)
+{
+	Rf_PrintValue(exp ? L2SEXP(exp) : R_NilValue);
+}
+
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniParentEnv
+(JNIEnv *env, jobject this, jlong exp)
+{
+  return SEXP2L(ENCLOS(exp ? L2SEXP(exp) : R_GlobalEnv));
+}
+
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniFindVar
+(JNIEnv *env, jobject this, jstring symName, jlong rho)
+{
+	SEXP sym = jri_installString(env, symName);
+	if (!sym || sym == R_NilValue) return 0;
+
+	return SEXP2L(Rf_findVar(sym, rho ? L2SEXP(rho) : R_GlobalEnv));
+}
+
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniListEnv
+(JNIEnv *env, jobject this, jlong rho, jboolean all)
+{
+	return SEXP2L(R_lsInternal(rho ? L2SEXP(rho) : R_GlobalEnv, all));
+}
+
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniSpecialObject
+(JNIEnv *env, jobject this, jint which)
+{
+  switch (which) {
+  case 0: return SEXP2L(R_NilValue);
+  case 1: return SEXP2L(R_GlobalEnv);
+  case 2: return SEXP2L(R_EmptyEnv);
+  case 3: return SEXP2L(R_BaseEnv);
+  case 4: return SEXP2L(R_UnboundValue);
+  case 5: return SEXP2L(R_MissingArg);
+  case 6: return SEXP2L(R_NaString);
+  case 7: return SEXP2L(R_BlankString);
+  }
+  return 0;
+}
+
+JNIEXPORT jobject JNICALL Java_org_rosuda_JRI_Rengine_rniXrefToJava
+(JNIEnv *env, jobject this, jlong exp)
+{
+	SEXP xp = L2SEXP(exp);
+	if (TYPEOF(xp) != EXTPTRSXP) return 0;
+	return (jobject) EXTPTR_PTR(xp);
+}
+
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniJavaToXref
+(JNIEnv *env, jobject this, jobject o)
+{
+  /* this is pretty much from Rglue.c of rJava */
+  jobject go = (*env)->NewGlobalRef(env, o);
+  return SEXP2L(R_MakeExternalPtr(go, R_NilValue, R_NilValue));
+}
+
+JNIEXPORT jstring JNICALL Java_org_rosuda_JRI_Rengine_rniGetString
+  (JNIEnv *env, jobject this, jlong exp)
+{
+      return jri_putString(env, L2SEXP(exp), 0);
+}
+
+
+JNIEXPORT jobjectArray JNICALL Java_org_rosuda_JRI_Rengine_rniGetStringArray
+  (JNIEnv *env, jobject this, jlong exp)
+{
+      return jri_putStringArray(env, L2SEXP(exp));
+}
+
+JNIEXPORT jintArray JNICALL Java_org_rosuda_JRI_Rengine_rniGetIntArray
+  (JNIEnv *env, jobject this, jlong exp)
+{
+      return jri_putIntArray(env, L2SEXP(exp));
+}
+
+JNIEXPORT jbyteArray JNICALL Java_org_rosuda_JRI_Rengine_rniGetRawArray
+  (JNIEnv *env, jobject this, jlong exp)
+{
+      return jri_putByteArray(env, L2SEXP(exp));
+}
+
+JNIEXPORT jintArray JNICALL Java_org_rosuda_JRI_Rengine_rniGetBoolArrayI
+  (JNIEnv *env, jobject this, jlong exp)
+{
+      return jri_putBoolArrayI(env, L2SEXP(exp));
+}
+
+JNIEXPORT jintArray JNICALL Java_org_rosuda_JRI_Rengine_rniGetDoubleArray
+  (JNIEnv *env, jobject this, jlong exp)
+{
+      return jri_putDoubleArray(env, L2SEXP(exp));
+}
+
+JNIEXPORT jlongArray JNICALL Java_org_rosuda_JRI_Rengine_rniGetVector
+(JNIEnv *env, jobject this, jlong exp)
+{
+    return jri_putSEXPLArray(env, L2SEXP(exp));
+}
+
+JNIEXPORT jint JNICALL Java_org_rosuda_JRI_Rengine_rniExpType
+  (JNIEnv *env, jobject this, jlong exp)
+{
+    return exp ? TYPEOF(L2SEXP(exp)) : 0;
+}
+
+JNIEXPORT void JNICALL Java_org_rosuda_JRI_Rengine_rniIdle
+  (JNIEnv *env, jobject this)
+{
+#ifdef Win32
+	if(!UserBreak)R_ProcessEvents();
+#else
+    R_runHandlers(R_InputHandlers, R_checkActivity(0, 1));
+#endif
+}
+
+JNIEXPORT void JNICALL Java_org_rosuda_JRI_Rengine_rniRunMainLoop
+  (JNIEnv *env, jobject this)
+{
+      run_Rmainloop();
+}
+
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniPutString
+(JNIEnv *env, jobject this, jstring s)
+{
+    return SEXP2L(jri_getString(env, s));
+}
+
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniPutStringArray
+(JNIEnv *env, jobject this, jobjectArray a)
+{
+    return SEXP2L(jri_getStringArray(env, a));
+}
+
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniPutIntArray
+(JNIEnv *env, jobject this, jintArray a)
+{
+    return SEXP2L(jri_getIntArray(env, a));
+}
+
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniPutRawArray
+(JNIEnv *env, jobject this, jbyteArray a)
+{
+    return SEXP2L(jri_getByteArray(env, a));
+}
+
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniPutBoolArrayI
+(JNIEnv *env, jobject this, jintArray a)
+{
+    return SEXP2L(jri_getBoolArrayI(env, a));
+}
+
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniPutBoolArray
+(JNIEnv *env, jobject this, jbooleanArray a)
+{
+    return SEXP2L(jri_getBoolArray(env, a));
+}
+
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniPutDoubleArray
+(JNIEnv *env, jobject this, jdoubleArray a)
+{
+    return SEXP2L(jri_getDoubleArray(env, a));
+}
+
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniPutVector
+(JNIEnv *env, jobject this, jlongArray a)
+{
+    return SEXP2L(jri_getSEXPLArray(env, a));
+}
+
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniGetAttr
+(JNIEnv *env, jobject this, jlong exp, jstring name)
+{
+    SEXP an = jri_installString(env, name);
+    if (!an || an==R_NilValue || exp==0 || L2SEXP(exp)==R_NilValue) return 0;
+    {
+        SEXP a = getAttrib(L2SEXP(exp), an);
+        return (a==R_NilValue)?0:SEXP2L(a);
+    }
+}
+
+JNIEXPORT jobjectArray JNICALL Java_org_rosuda_JRI_Rengine_rniGetAttrNames
+(JNIEnv *env, jobject this, jlong exp)
+{
+    SEXP o = L2SEXP(exp);
+    SEXP att = ATTRIB(o), ah = att;
+    unsigned int ac = 0;
+    jobjectArray sa;
+    if (att == R_NilValue) return 0;
+    /* count the number of attributes */
+    while (ah != R_NilValue) {
+	ac++;
+	ah = CDR(ah);
+    }
+    /* allocate Java array */
+    sa = (*env)->NewObjectArray(env, ac, (*env)->FindClass(env, "java/lang/String"), 0);
+    if (!sa) return 0;
+    ac = 0;
+    ah = att;
+    /* iterate again and set create the strings */
+    while (ah != R_NilValue) {
+	SEXP t = TAG(ah);
+	if (t != R_NilValue) {
+	    jobject s = (*env)->NewStringUTF(env, CHAR_UTF8(PRINTNAME(t)));
+	    (*env)->SetObjectArrayElement(env, sa, ac, s);
+	}
+	ac++;
+	ah = CDR(ah);
+    }
+    return sa;
+}
+
+JNIEXPORT void JNICALL Java_org_rosuda_JRI_Rengine_rniSetAttr
+(JNIEnv *env, jobject this, jlong exp, jstring aName, jlong attr)
+{
+    SEXP an = jri_installString(env, aName);
+    if (!an || an==R_NilValue || exp==0 || L2SEXP(exp)==R_NilValue) return;
+
+    setAttrib(L2SEXP(exp), an, (attr==0)?R_NilValue:L2SEXP(attr));
+	
+	/* BTW: we don't need to adjust the object bit for "class", setAttrib does that already */
+
+    /* this is not official API, but whoever uses this should know what he's doing
+       it's ok for directly constructing attr lists, and that's what it should be used for
+       SET_ATTRIB(L2SEXP(exp), (attr==0)?R_NilValue:L2SEXP(attr)); */
+    
+}
+
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniInstallSymbol
+(JNIEnv *env, jobject this, jstring s)
+{
+    return SEXP2L(jri_installString(env, s));
+}
+
+JNIEXPORT jstring JNICALL Java_org_rosuda_JRI_Rengine_rniGetSymbolName
+(JNIEnv *env, jobject this, jlong exp)
+{
+	return jri_putSymbolName(env, L2SEXP(exp));
+}
+
+JNIEXPORT jboolean JNICALL Java_org_rosuda_JRI_Rengine_rniInherits
+(JNIEnv *env, jobject this, jlong exp, jstring s)
+{
+	jboolean res = 0;
+	const char *c;
+	c=(*env)->GetStringUTFChars(env, s, 0);
+	if (c) {
+		if (inherits(L2SEXP(exp), (char*)c)) res = 1;
+		(*env)->ReleaseStringUTFChars(env, s, c);
+	}
+	return res;
+}
+
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniCons
+(JNIEnv *env, jobject this, jlong head, jlong tail, jlong tag, jboolean lang)
+{
+  SEXP l;
+  if (lang)
+    l = LCONS((head==0)?R_NilValue:L2SEXP(head), (tail==0)?R_NilValue:L2SEXP(tail));
+  else
+    l = CONS((head==0)?R_NilValue:L2SEXP(head), (tail==0)?R_NilValue:L2SEXP(tail));
+  
+  if (tag) SET_TAG(l, L2SEXP(tag));
+  return SEXP2L(l);
+}
+
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniCAR
+(JNIEnv *env, jobject this, jlong exp)
+{
+    if (exp) {
+        SEXP r = CAR(L2SEXP(exp));
+        return (r==R_NilValue)?0:SEXP2L(r);
+    }
+    return 0;
+}
+
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniCDR
+(JNIEnv *env, jobject this, jlong exp)
+{
+    if (exp) {
+        SEXP r = CDR(L2SEXP(exp));
+        return (r==R_NilValue)?0:SEXP2L(r);
+    }
+    return 0;
+}
+
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniTAG
+(JNIEnv *env, jobject this, jlong exp)
+{
+    if (exp) {
+        SEXP r = TAG(L2SEXP(exp));
+        return (r==R_NilValue)?0:SEXP2L(r);
+    }
+    return 0;
+}
+
+/* creates a list from SEXPs provided in long[] */
+JNIEXPORT jlong JNICALL Java_org_rosuda_JRI_Rengine_rniPutList
+(JNIEnv *env, jobject this, jlongArray o)
+{
+    SEXP t=R_NilValue;
+    int l,i=0;
+    jlong *ap;
+    
+    if (!o) return 0;
+    l=(int)(*env)->GetArrayLength(env, o);
+    if (l<1) return SEXP2L(CONS(R_NilValue, R_NilValue));
+    ap=(jlong*)(*env)->GetLongArrayElements(env, o, 0);
+    if (!ap) return 0;
+    
+    while(i<l) {
+        t=CONS((ap[i]==0)?R_NilValue:L2SEXP(ap[i]), t);
+        i++;
+    }
+    (*env)->ReleaseLongArrayElements(env, o, ap, 0);    
+    
+    return SEXP2L(t);
+}
+
+/* retrieves a list (shallow copy) and returns the SEXPs in long[] */
+JNIEXPORT jlongArray JNICALL Java_org_rosuda_JRI_Rengine_rniGetList
+(JNIEnv *env, jobject this, jlong exp)
+{
+    SEXP e=L2SEXP(exp);
+    
+    if (exp==0 || e==R_NilValue) return 0;
+
+    {
+        unsigned len=0;
+        SEXP t=e;
+        
+        while (t!=R_NilValue) { t=CDR(t); len++; };
+        
+        {
+            jlongArray da=(*env)->NewLongArray(env,len);
+            jlong *dae;
+        
+            if (!da) return 0;
+        
+            if (len>0) {
+                int i=0;
+                dae=(*env)->GetLongArrayElements(env, da, 0);
+                if (!dae) {
+                    (*env)->DeleteLocalRef(env,da);
+                    jri_error("rniGetList: newLongArray.GetLongArrayElements failed");
+                    return 0;
+                }
+
+                t=e;
+                while (t!=R_NilValue && i<len) {
+                    dae[i]=(CAR(t)==R_NilValue)?0:SEXP2L(CAR(t));
+                    i++; t=CDR(t);
+                }
+                
+                (*env)->ReleaseLongArrayElements(env, da, dae, 0);
+            }
+            
+            return da;
+        }
+    }
+    
+}
+
+/* by default those are disabled as it's a problem on Win32 ... */
+#ifdef JRI_ENV_CALLS
+
+JNIEXPORT void JNICALL Java_org_rosuda_JRI_Rengine_rniSetEnv
+(JNIEnv *env, jclass this, jstring key, jstring val) {
+    const char *cKey, *cVal;
+    if (!key || !val) return;
+    cKey=(*env)->GetStringUTFChars(env, key, 0);
+    cVal=(*env)->GetStringUTFChars(env, val, 0);
+    if (!cKey || !cVal) {
+        jri_error("rniSetEnv: can't retrieve key/value content");
+        return;
+    }
+#ifdef Win32
+    SetEnvironmentVariable(cKey, cVal);
+#else
+    setenv(cKey, cVal, 1);
+#endif
+    (*env)->ReleaseStringUTFChars(env, key, cKey);
+    (*env)->ReleaseStringUTFChars(env, val, cVal);
+}
+
+JNIEXPORT jstring JNICALL Java_org_rosuda_JRI_Rengine_rniGetEnv
+(JNIEnv *env, jclass this, jstring key) {
+    const char *cKey, *cVal;
+    if (!key) return;
+    cKey=(*env)->GetStringUTFChars(env, key, 0);
+    if (!cKey) {
+        jri_error("rniSetEnv: can't retrieve key/value content");
+        return;
+    }
+    cVal=getenv(cKey);
+    (*env)->ReleaseStringUTFChars(env, key, cKey);
+    if (!cVal) return 0;
+    return (*env)->NewStringUTF(env, cVal);
+}
+
+#endif
+
+JNIEXPORT jint JNICALL Java_org_rosuda_JRI_Rengine_rniSetupRJava
+(JNIEnv *env, jobject this, jint _in, jint _out) {
+  RJava_setup(_in, _out);
+  return 0;
+}
+
+JNIEXPORT jint JNICALL Java_org_rosuda_JRI_Rengine_rniRJavaLock
+(JNIEnv *env, jobject this) {
+  return RJava_request_lock();
+}
+
+JNIEXPORT jint JNICALL Java_org_rosuda_JRI_Rengine_rniRJavaUnlock
+(JNIEnv *env, jobject this) {
+  return RJava_clear_lock();
+}
+
+JNIEXPORT void JNICALL Java_org_rosuda_JRI_Rengine_rniPrint
+(JNIEnv *env, jobject this, jstring s, jint oType) {
+  if (s) {
+    const char *c = (*env)->GetStringUTFChars(env, s, 0);
+    if (c) {
+      if (oType)
+	REprintf("%s", c);
+      else
+	Rprintf("%s", c);
+    }
+    (*env)->ReleaseStringUTFChars(env, s, c);
+  }
+}
+
+JNIEXPORT jint JNICALL Java_org_rosuda_JRI_Rengine_rniStop
+(JNIEnv *env, jobject this, jint flag) {
+#ifdef Win32
+    UserBreak=1;
+#else
+    /* there are three choices now:
+       0 = cooperative (requires external interrupt of ReadConsole!)
+       1 = SIGINT for compatibility with old rniStop()
+       2 = R's onintr but that one works *only* if used on the R thread (which renders is essentially useless unless used in some synchronous interrupt handler). */
+    if (flag == 0) R_interrupts_pending = 1;
+    else if (flag == 1)  kill(getpid(), SIGINT);
+    else Rf_onintr();
+#endif
+    return 0;
+}
+
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/src/Rinit.c b/com.oracle.truffle.r.pkgs/rJava/jri/src/Rinit.c
new file mode 100644
index 0000000000000000000000000000000000000000..9caf7d4fb5b54cc2178baebe8b8f09d342fd438a
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/src/Rinit.c
@@ -0,0 +1,292 @@
+#include <R.h>
+#include <Rinternals.h>
+#include "Rinit.h"
+#include "Rcallbacks.h"
+#include "Rdecl.h"
+
+/*-------------------------------------------------------------------*
+ * UNIX initialization (includes Darwin/Mac OS X)                    *
+ *-------------------------------------------------------------------*/
+
+#ifndef Win32
+
+#define R_INTERFACE_PTRS 1
+#define CSTACK_DEFNS 1
+#include <Rinterface.h>
+/* and SaveAction is not officially exported */
+extern SA_TYPE SaveAction;
+
+
+int initR(int argc, char **argv) {
+    structRstart rp;
+    Rstart Rp = &rp;
+    /* getenv("R_HOME","/Library/Frameworks/R.framework/Resources",1); */
+    if (!getenv("R_HOME")) {
+        fprintf(stderr, "R_HOME is not set. Please set all required environment variables before running this program.\n");
+        return -1;
+    }
+
+    /* this is probably unnecessary, but we could set any other parameters here */
+    R_DefParams(Rp);
+    Rp->NoRenviron = 0;
+    R_SetParams(Rp);
+
+#ifdef RIF_HAS_RSIGHAND
+    R_SignalHandlers=0;
+#endif
+    {
+      int stat=Rf_initialize_R(argc, argv);
+      if (stat<0) {
+        printf("Failed to initialize embedded R! (stat=%d)\n",stat);
+        return -1;
+      }
+    }
+
+#ifdef RIF_HAS_RSIGHAND
+    R_SignalHandlers=0;
+#endif
+    /* disable stack checking, because threads will thow it off */
+    R_CStackLimit = (uintptr_t) -1;
+
+#ifdef JGR_DEBUG
+    printf("R primary initialization done. Setting up parameters.\n");
+#endif
+
+    R_Outputfile = NULL;
+    R_Consolefile = NULL;
+    R_Interactive = 1;
+    SaveAction = SA_SAVEASK;
+
+    /* ptr_R_Suicide = Re_Suicide; */
+    /* ptr_R_CleanUp = Re_CleanUp; */
+    ptr_R_ShowMessage = Re_ShowMessage;
+    ptr_R_ReadConsole = Re_ReadConsole;
+    ptr_R_WriteConsole = NULL;
+    ptr_R_WriteConsoleEx = Re_WriteConsoleEx;
+    ptr_R_ResetConsole = Re_ResetConsole;
+    ptr_R_FlushConsole = Re_FlushConsole;
+    ptr_R_ClearerrConsole = Re_ClearerrConsole;
+    ptr_R_Busy = Re_Busy;
+    ptr_R_ShowFiles = Re_ShowFiles;
+    ptr_R_ChooseFile = Re_ChooseFile;
+	ptr_R_loadhistory = Re_loadhistory;
+    ptr_R_savehistory = Re_savehistory;
+
+#ifdef JGR_DEBUG
+	printf("Setting up R event loop\n");
+#endif
+
+    setup_Rmainloop();
+
+#ifdef JGR_DEBUG
+    printf("R initialized.\n");
+#endif
+
+    return 0;
+}
+
+void initRinside() {
+    /* disable stack checking, because threads will thow it off */
+    R_CStackLimit = (uintptr_t) -1;
+}
+
+#else
+
+/*-------------------------------------------------------------------*
+ * Windows initialization is different and uses Startup.h            *
+ *-------------------------------------------------------------------*/
+
+#define NONAMELESSUNION
+#include <windows.h>
+#include <winreg.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+/* before we include RStatup.h we need to work around a bug in it for Win64:
+   it defines wrong R_size_t if R_SIZE_T_DEFINED is not set */
+#if defined(WIN64) && ! defined(R_SIZE_T_DEFINED)
+#include <stdint.h>
+#define R_size_t uintptr_t
+#define R_SIZE_T_DEFINED 1
+#endif
+
+#include "R_ext/RStartup.h"
+
+#ifndef WIN64
+/* according to fixed/config.h Windows has uintptr_t, my windows hasn't */
+#if !defined(HAVE_UINTPTR_T) && !defined(uintptr_t) && !defined(_STDINT_H)
+typedef unsigned uintptr_t;
+#endif
+#endif
+extern __declspec(dllimport) uintptr_t R_CStackLimit; /* C stack limit */
+extern __declspec(dllimport) uintptr_t R_CStackStart; /* Initial stack address */
+
+/* for signal-handling code */
+/* #include "psignal.h" - it's not included, so just get SIGBREAK */
+#define	SIGBREAK 21	/* to readers pgrp upon background tty read */
+
+/* one way to allow user interrupts: called in ProcessEvents */
+#ifdef _MSC_VER
+__declspec(dllimport) int UserBreak;
+#else
+#ifndef WIN64
+#define UserBreak     (*_imp__UserBreak)
+#endif
+extern int UserBreak;
+#endif
+
+/* calls into the R DLL */
+extern char *getDLLVersion();
+extern void R_DefParams(Rstart);
+extern void R_SetParams(Rstart);
+extern void setup_term_ui(void);
+extern void ProcessEvents(void);
+extern void end_Rmainloop(void), R_ReplDLLinit(void);
+extern int R_ReplDLLdo1();
+extern void run_Rmainloop(void);
+
+void myCallBack()
+{
+    /* called during i/o, eval, graphics in ProcessEvents */
+}
+
+#ifndef YES
+#define YES    1
+#endif
+#ifndef NO
+#define NO    -1
+#endif
+#ifndef CANCEL
+#define CANCEL 0
+#endif
+
+int myYesNoCancel(char *s)
+{
+    char  ss[128];
+    unsigned char a[3];
+
+    sprintf(ss, "%s [y/n/c]: ", s);
+    Re_ReadConsole(ss, a, 3, 0);
+    switch (a[0]) {
+    case 'y':
+    case 'Y':
+	return YES;
+    case 'n':
+    case 'N':
+	return NO;
+    default:
+	return CANCEL;
+    }
+}
+
+static void my_onintr(int sig)
+{
+    UserBreak = 1;
+}
+
+static char Rversion[25], RUser[MAX_PATH], RHome[MAX_PATH];
+
+int initR(int argc, char **argv)
+{
+    structRstart rp;
+    Rstart Rp = &rp;
+    char *p;
+    char rhb[MAX_PATH+10];
+    DWORD t, s = MAX_PATH;
+    HKEY k;
+    int cvl;
+
+    sprintf(Rversion, "%s.%s", R_MAJOR, R_MINOR);
+    cvl=strlen(R_MAJOR)+2;
+    if(strncmp(getDLLVersion(), Rversion, cvl) != 0) {
+        char msg[512];
+	sprintf(msg, "Error: R.DLL version does not match (DLL: %s, expecting: %s)\n", getDLLVersion(), Rversion);
+	fprintf(stderr, msg);
+	MessageBox(0, msg, "Version mismatch", MB_OK|MB_ICONERROR);
+	return -1;
+    }
+
+    R_DefParams(Rp);
+    if(getenv("R_HOME")) {
+	strcpy(RHome, getenv("R_HOME"));
+    } else { /* fetch R_HOME from the registry - try preferred architecture first */
+#ifdef WIN64
+      const char *pref_path = "SOFTWARE\\R-core\\R64";
+#else
+      const char *pref_path = "SOFTWARE\\R-core\\R32";
+#endif
+      if ((RegOpenKeyEx(HKEY_LOCAL_MACHINE, pref_path, 0, KEY_QUERY_VALUE, &k) != ERROR_SUCCESS ||
+	   RegQueryValueEx(k, "InstallPath", 0, &t, (LPBYTE) RHome, &s) != ERROR_SUCCESS) &&
+	  (RegOpenKeyEx(HKEY_CURRENT_USER, pref_path, 0, KEY_QUERY_VALUE, &k) != ERROR_SUCCESS ||
+           RegQueryValueEx(k, "InstallPath", 0, &t, (LPBYTE) RHome, &s) != ERROR_SUCCESS) &&
+	  (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\R-core\\R", 0, KEY_QUERY_VALUE, &k) != ERROR_SUCCESS ||
+	   RegQueryValueEx(k, "InstallPath", 0, &t, (LPBYTE) RHome, &s) != ERROR_SUCCESS) &&
+	  (RegOpenKeyEx(HKEY_CURRENT_USER, "SOFTWARE\\R-core\\R", 0, KEY_QUERY_VALUE, &k) != ERROR_SUCCESS ||
+           RegQueryValueEx(k, "InstallPath", 0, &t, (LPBYTE) RHome, &s) != ERROR_SUCCESS)) {
+	fprintf(stderr, "R_HOME must be set or R properly installed (\\Software\\R-core\\R\\InstallPath registry entry must exist).\n");
+	MessageBox(0, "R_HOME must be set or R properly installed (\\Software\\R-core\\R\\InstallPath registry entry must exist).\n", "Can't find R home", MB_OK|MB_ICONERROR);
+	return -2;
+      }
+      sprintf(rhb,"R_HOME=%s",RHome);
+      putenv(rhb);
+    }
+    /* on Win32 this should set R_Home (in R_SetParams) as well */
+    Rp->rhome = RHome;
+    /*
+     * try R_USER then HOME then working directory
+     */
+    if (getenv("R_USER")) {
+	strcpy(RUser, getenv("R_USER"));
+    } else if (getenv("HOME")) {
+	strcpy(RUser, getenv("HOME"));
+    } else if (getenv("HOMEDIR")) {
+	strcpy(RUser, getenv("HOMEDIR"));
+	strcat(RUser, getenv("HOMEPATH"));
+    } else
+	GetCurrentDirectory(MAX_PATH, RUser);
+    p = RUser + (strlen(RUser) - 1);
+    if (*p == '/' || *p == '\\') *p = '\0';
+    Rp->home = RUser;
+    Rp->ReadConsole = Re_ReadConsole;
+    Rp->WriteConsole = NULL;
+    Rp->WriteConsoleEx = Re_WriteConsoleEx;
+
+    Rp->Busy = Re_Busy;
+    Rp->ShowMessage = Re_ShowMessage;
+    Rp->YesNoCancel = myYesNoCancel;
+    Rp->CallBack = myCallBack;
+    Rp->CharacterMode = LinkDLL;
+
+    Rp->R_Quiet = FALSE;
+    Rp->R_Interactive = TRUE;
+    Rp->RestoreAction = SA_RESTORE;
+    Rp->SaveAction = SA_SAVEASK;
+    /* process common command line options */
+    R_common_command_line(&argc, argv, Rp);
+    /* what is left should be assigned to args */
+    R_set_command_line_arguments(argc, argv);
+
+    R_SetParams(Rp); /* so R_ShowMessage is set */
+    R_SizeFromEnv(Rp);
+    R_SetParams(Rp);
+
+    /* R_SetParams implicitly calls R_SetWin32 which sets the
+       stack start/limit which we need to override */
+    R_CStackLimit = (uintptr_t) -1;
+
+    FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
+
+    signal(SIGBREAK, my_onintr);
+    setup_term_ui();
+    setup_Rmainloop();
+
+    return 0;
+}
+
+void initRinside() {
+    /* disable stack checking, because threads will thow it off */
+    R_CStackLimit = (uintptr_t) -1;
+}
+
+#endif
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/src/Rinit.h b/com.oracle.truffle.r.pkgs/rJava/jri/src/Rinit.h
new file mode 100644
index 0000000000000000000000000000000000000000..b3cc2f0511b1bcf542eb09a2873a3b510f07cd15
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/src/Rinit.h
@@ -0,0 +1,7 @@
+#ifndef __R_INIT__H__
+#define __R_INIT__H__
+
+int initR(int argc, char **argv);
+void initRinside();
+
+#endif
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/src/config.h.in b/com.oracle.truffle.r.pkgs/rJava/jri/src/config.h.in
new file mode 100644
index 0000000000000000000000000000000000000000..260ad1dff7a5d3e658f7bdf9e34c8724921f2fe4
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/src/config.h.in
@@ -0,0 +1,19 @@
+/* src/config.h.in.  Generated from configure.ac by autoheader.  */
+
+/* Define to the address where bug reports for this package should be sent. */
+#undef PACKAGE_BUGREPORT
+
+/* Define to the full name of this package. */
+#undef PACKAGE_NAME
+
+/* Define to the full name and version of this package. */
+#undef PACKAGE_STRING
+
+/* Define to the one symbol short name of this package. */
+#undef PACKAGE_TARNAME
+
+/* Define to the version of this package. */
+#undef PACKAGE_VERSION
+
+/* Define to 1 if you have the ANSI C header files. */
+#undef STDC_HEADERS
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/src/globals.c b/com.oracle.truffle.r.pkgs/rJava/jri/src/globals.c
new file mode 100644
index 0000000000000000000000000000000000000000..6e26ae6f8f8ad580da44ade91740ffb9f4d4c725
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/src/globals.c
@@ -0,0 +1,5 @@
+#include <jni.h>
+
+jobject engineObj;
+jclass engineClass;
+JNIEnv *eenv;
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/src/globals.h b/com.oracle.truffle.r.pkgs/rJava/jri/src/globals.h
new file mode 100644
index 0000000000000000000000000000000000000000..766acd603b5fd46591ff11ad4587bd43808cb15c
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/src/globals.h
@@ -0,0 +1,10 @@
+#ifndef __GLOBALS__H__
+#define __GLOBALS__H__
+
+#include <jni.h>
+
+extern jobject engineObj;
+extern jclass engineClass;
+extern JNIEnv *eenv;
+
+#endif
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/src/h2ic b/com.oracle.truffle.r.pkgs/rJava/jri/src/h2ic
new file mode 100755
index 0000000000000000000000000000000000000000..9aca879067ec988c7cb639cf6385e99c7d252243
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/src/h2ic
@@ -0,0 +1,40 @@
+#!/usr/bin/perl
+
+$fn=shift;
+
+print "#include \"$fn\"\n#include <stdlib.h>\n\n";
+
+open IN, $fn;
+$fn=~s/\..*?$//;
+$fn=$1 if ($fn=~/\/([^\/]+)$/);
+$pre=$fn;
+while (<IN>) {
+    if (/^JNIEXPORT ([a-z]+) JNICALL ([a-zA-Z0-9_]+)/) {
+	$ret=$1; $fn=$2;
+	$a=<IN>;
+	if ($a=~/\((JNIEnv.*)\)/) {
+	    $par=$1;
+	    @p=split /,/,$par; $i=0; undef @pc;
+	    foreach (@p) { $_.=" par$i"; push @pc, "par$i"; $i++; }
+	    $parn=join ',',@p;
+	    $parc=join ', ',@pc;
+	    $rc = ($ret eq 'void')?'':'return ';
+	    print "typedef $ret(*c_${fn}_t)($par);\nc_${fn}_t Call_$fn;\n";
+	    print "JNIEXPORT $ret JNICALL $fn\n  ($parn) {\n    $rc Call_$fn($parc);\n  }\n\n";
+	    push @fnl, $fn;
+	}
+    }
+}
+
+print "void Setup_$pre(void **ptrs) {\n";
+$i=0;
+foreach (@fnl) { print "Call_$_ = (c_${_}_t) ptrs[$i];\n"; $i++; }
+print "}\n\n";
+
+$i=0;
+print "void **GetRef_$pre() {
+  void **ptrs = (void**) malloc(sizeof(void*) * ( $#fnl + 2 ) );
+";
+foreach (@fnl) { print "ptrs[$i] = (void*) Call_$_;\n"; $i++; }
+print "ptrs[$i] = (void*) 0;\nreturn ptrs;\n}\n";
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/src/jri.c b/com.oracle.truffle.r.pkgs/rJava/jri/src/jri.c
new file mode 100644
index 0000000000000000000000000000000000000000..3913c07a3add5e9ffe739450dd6a6ed0f844cc11
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/src/jri.c
@@ -0,0 +1,524 @@
+#define USE_RINTERNALS 1  /* for efficiency */
+
+#include "jri.h"
+#include <jni.h>
+#include <R.h>
+#include <Rdefines.h>
+#include <Rversion.h>
+#include <R_ext/Parse.h>
+
+#include <stdarg.h>
+
+/* debugging output (enable with -DRJ_DEBUG) */
+#ifdef RJ_DEBUG
+static void rjprintf(char *fmt, ...) {
+  va_list v;
+  va_start(v,fmt);
+  vprintf(fmt,v);
+  va_end(v);
+}
+#define _dbg(X) X
+#else
+#define _dbg(X)
+#endif
+
+void jri_error(char *fmt, ...) {
+    va_list v;
+    va_start(v,fmt);
+    vprintf(fmt,v);
+    va_end(v);
+}
+
+/* profiling code (enable with -DRJ_PROFILE) */
+#ifdef RJ_PROFILE
+#include <sys/time.h>
+
+static long time_ms() {
+#ifdef Win32
+  return 0; /* in Win32 we have no gettimeofday :( */
+#else
+  struct timeval tv;
+  gettimeofday(&tv,0);
+  return (tv.tv_usec/1000)+(tv.tv_sec*1000);
+#endif
+}
+
+long profilerTime;
+
+#define profStart() profilerTime=time_ms()
+static void profReport(char *fmt, ...) {
+  long npt=time_ms();
+  va_list v;
+  va_start(v,fmt);
+  vprintf(fmt,v);
+  va_end(v);
+  printf(" %ld ms\n",npt-profilerTime);
+  profilerTime=npt;
+}
+#define _prof(X) X
+#else
+#define profStart()
+#define _prof(X)
+#endif
+
+jstring jri_putString(JNIEnv *env, SEXP e, int ix) {
+    return (TYPEOF(e) != STRSXP || LENGTH(e) <= ix || STRING_ELT(e, ix) == R_NaString) ? 0 : (*env)->NewStringUTF(env, CHAR_UTF8(STRING_ELT(e, ix)));
+}
+
+jarray jri_putStringArray(JNIEnv *env, SEXP e)
+{
+    if (TYPEOF(e) != STRSXP) return 0;
+    {
+        int j = 0;
+        jobjectArray sa = (*env)->NewObjectArray(env, LENGTH(e), (*env)->FindClass(env, "java/lang/String"), 0);
+        if (!sa) { jri_error("Unable to create string array."); return 0; }
+        while (j < LENGTH(e)) {
+	    SEXP elt = STRING_ELT(e, j);
+	    jobject s = (elt == R_NaString) ? 0 : (*env)->NewStringUTF(env, CHAR_UTF8(STRING_ELT(e,j)));
+            _dbg(if (s) rjprintf (" [%d] \"%s\"\n",j,CHAR_UTF8(STRING_ELT(e,j))); else rjprintf(" [%d] NA\n", j));
+            (*env)->SetObjectArrayElement(env, sa, j, s);
+            j++;
+        }
+        return sa;
+    }
+}
+
+jarray jri_putIntArray(JNIEnv *env, SEXP e)
+{
+    if (TYPEOF(e)!=INTSXP) return 0;
+    _dbg(rjprintf(" integer vector of length %d\n",LENGTH(e)));
+    {
+        unsigned len=LENGTH(e);
+        jintArray da=(*env)->NewIntArray(env,len);
+        jint *dae;
+
+        if (!da) {
+            jri_error("newIntArray.new(%d) failed",len);
+            return 0;
+        }
+        
+        if (len>0) {
+            dae=(*env)->GetIntArrayElements(env, da, 0);
+            if (!dae) {
+                (*env)->DeleteLocalRef(env,da);
+                jri_error("newIntArray.GetIntArrayElements failed");
+                return 0;
+            }
+            memcpy(dae,INTEGER(e),sizeof(jint)*len);
+            (*env)->ReleaseIntArrayElements(env, da, dae, 0);
+        }
+        return da;
+    }
+}
+
+jarray jri_putByteArray(JNIEnv *env, SEXP e)
+{
+    if (TYPEOF(e) != RAWSXP) return 0;
+    _dbg(rjprintf(" raw vector of length %d\n", LENGTH(e)));
+    {
+        unsigned len = LENGTH(e);
+        jbyteArray da = (*env)->NewByteArray(env,len);
+        jbyte *dae;
+
+        if (!da) {
+            jri_error("newByteArray.new(%d) failed",len);
+            return 0;
+        }
+        
+        if (len > 0) {
+            dae = (*env)->GetByteArrayElements(env, da, 0);
+            if (!dae) {
+                (*env)->DeleteLocalRef(env, da);
+                jri_error("newByteArray.GetByteArrayElements failed");
+                return 0;
+            }
+            memcpy(dae, RAW(e), len);
+            (*env)->ReleaseByteArrayElements(env, da, dae, 0);
+        }
+        return da;
+    }
+}
+
+jarray jri_putBoolArrayI(JNIEnv *env, SEXP e)
+{
+    if (TYPEOF(e)!=LGLSXP) return 0;
+    _dbg(rjprintf(" integer vector of length %d\n",LENGTH(e)));
+    {
+        unsigned len=LENGTH(e);
+        jintArray da=(*env)->NewIntArray(env,len);
+        jint *dae;
+
+        if (!da) {
+            jri_error("newIntArray.new(%d) failed",len);
+            return 0;
+        }
+        
+        if (len>0) {
+            dae=(*env)->GetIntArrayElements(env, da, 0);
+            if (!dae) {
+                (*env)->DeleteLocalRef(env,da);
+                jri_error("newIntArray.GetIntArrayElements failed");
+                return 0;
+            }
+            memcpy(dae,INTEGER(e),sizeof(jint)*len);
+            (*env)->ReleaseIntArrayElements(env, da, dae, 0);
+        }
+        return da;
+    }
+}
+
+jarray jri_putSEXPLArray(JNIEnv *env, SEXP e)
+{
+    _dbg(rjprintf(" general vector of length %d\n",LENGTH(e)));
+    {
+        unsigned len=LENGTH(e);
+        jlongArray da=(*env)->NewLongArray(env,len);
+        jlong *dae;
+        
+        if (!da) {
+            jri_error("newLongArray.new(%d) failed",len);
+            return 0;
+        }
+        
+        if (len>0) {
+            int i=0;
+            
+            dae=(*env)->GetLongArrayElements(env, da, 0);
+            if (!dae) {
+                (*env)->DeleteLocalRef(env,da);
+                jri_error("newLongArray.GetLongArrayElements failed");
+                return 0;
+            }
+            while (i<len) {
+                dae[i] = SEXP2L(VECTOR_ELT(e, i));
+                i++;
+            }
+            (*env)->ReleaseLongArrayElements(env, da, dae, 0);
+        }
+        return da;
+    }
+}
+
+jarray jri_putDoubleArray(JNIEnv *env, SEXP e)
+{
+    if (TYPEOF(e)!=REALSXP) return 0;
+    _dbg(rjprintf(" real vector of length %d\n",LENGTH(e)));
+    {
+        unsigned len=LENGTH(e);
+        jdoubleArray da=(*env)->NewDoubleArray(env,len);
+        jdouble *dae;
+
+        if (!da) {
+            jri_error("newDoubleArray.new(%d) failed",len);
+            return 0;
+        }
+        if (len>0) {
+            dae=(*env)->GetDoubleArrayElements(env, da, 0);
+            if (!dae) {
+                (*env)->DeleteLocalRef(env,da);
+                jri_error("newDoubleArray.GetDoubleArrayElements failed");
+                return 0;
+            }
+            memcpy(dae,REAL(e),sizeof(jdouble)*len);
+            (*env)->ReleaseDoubleArrayElements(env, da, dae, 0);
+        }
+        return da;
+    }
+}
+
+/** jobjRefInt object : string */
+SEXP jri_getString(JNIEnv *env, jstring s) {
+    SEXP r;
+    const char *c;
+    
+    if (!s) return ScalarString(R_NaString);
+    profStart();
+    c = (*env)->GetStringUTFChars(env, s, 0);
+    if (!c) {
+	jri_error("jri_getString: can't retrieve string content");
+	return R_NilValue;
+    }
+    PROTECT(r = allocVector(STRSXP,1));
+    SET_STRING_ELT(r, 0, mkCharUTF8(c));
+    UNPROTECT(1);
+    (*env)->ReleaseStringUTFChars(env, s, c);
+    _prof(profReport("jri_getString:"));
+    return r;
+}
+
+SEXP jri_installString(JNIEnv *env, jstring s) {
+    SEXP r;
+    const char *c;
+    
+    if (!s) return R_NilValue;
+    profStart();
+    c=(*env)->GetStringUTFChars(env, s, 0);
+    if (!c) {
+        jri_error("jri_getString: can't retrieve string content");
+        return R_NilValue;
+    }
+    r = install(c);
+    (*env)->ReleaseStringUTFChars(env, s, c);
+    _prof(profReport("jri_getString:"));
+    return r;
+}
+
+jstring jri_putSymbolName(JNIEnv *env, SEXP e) {
+    SEXP pn;
+    if (TYPEOF(e)!=SYMSXP) return 0;
+    pn=PRINTNAME(e);
+    return (TYPEOF(pn)!=CHARSXP)?0:(*env)->NewStringUTF(env, CHAR_UTF8(pn));
+}
+
+/** calls .toString() of the object and returns the corresponding string java object */
+jstring jri_callToString(JNIEnv *env, jobject o) {
+  jclass cls;
+  jmethodID mid;
+
+  cls=(*env)->GetObjectClass(env,o);
+  if (!cls) {
+      jri_error("RtoString: can't determine class of the object");
+      return 0;
+  }
+  mid=(*env)->GetMethodID(env, cls, "toString", "()Ljava/lang/String;");
+  if (!mid) {
+      jri_error("RtoString: toString not found for the object");
+      return 0;
+  }
+  return (jstring)(*env)->CallObjectMethod(env, o, mid);  
+}
+
+/* FIXME: this should never be used as 64-bit platforms can't stuff a
+   pointer in any R type (save for raw which must be interpreted
+   accordingly) */
+SEXP jri_getObjectArray(JNIEnv *env, jarray o) {
+  SEXP ar;
+  int l,i;
+
+  profStart();
+  _dbg(rjprintf(" jarray %d\n",o));
+  if (!o) return R_NilValue;
+  l=(int)(*env)->GetArrayLength(env, o);
+  _dbg(rjprintf("convert object array of length %d\n",l));
+  if (l<1) return R_NilValue;
+  PROTECT(ar=allocVector(INTSXP,l));
+  i=0;
+  while (i < l) { /* to avoid warnings we cast ptr -> ljong -> int
+		     with loss of precision */
+    INTEGER(ar)[i] = (int)(jlong)(*env)->GetObjectArrayElement(env, o, i);
+    i++;
+  }
+  UNPROTECT(1);
+  _prof(profReport("RgetObjectArrayCont[%d]:",o));
+  return ar;
+}
+
+/** get contents of the object array in the form of int* */
+SEXP jri_getStringArray(JNIEnv *env, jarray o) {
+    SEXP ar;
+    int l, i;
+    const char *c;
+
+    profStart();
+    _dbg(rjprintf(" jarray %d\n",o));
+    if (!o) return R_NilValue;
+    l = (int)(*env)->GetArrayLength(env, o);
+    _dbg(rjprintf("convert string array of length %d\n",l));
+    PROTECT(ar = allocVector(STRSXP,l));
+    for (i = 0; i < l; i++) {
+	jobject sobj = (*env)->GetObjectArrayElement(env, o, i);
+	c = 0;
+	if (sobj) {
+	    /* we could (should?) check the type here ...
+	       if (!(*env)->IsInstanceOf(env, sobj, javaStringClass)) {
+	       printf(" not a String\n");
+	       } else
+	    */
+	    c = (*env)->GetStringUTFChars(env, sobj, 0);
+	}
+	if (!c)
+	    SET_STRING_ELT(ar, i, R_NaString); /* this is probably redundant since the vector is pre-filled with NAs, but just in case ... */
+	else {
+	    SET_STRING_ELT(ar, i, mkCharUTF8(c));
+	    (*env)->ReleaseStringUTFChars(env, sobj, c);
+	}
+    }
+    UNPROTECT(1);
+    _prof(profReport("RgetStringArrayCont[%d]:",o));
+    return ar;
+}
+
+/** get contents of the integer array object (int) */
+SEXP jri_getIntArray(JNIEnv *env, jarray o) {
+  SEXP ar;
+  int l;
+  jint *ap;
+
+  profStart();
+  _dbg(rjprintf(" jarray %d\n",o));
+  if (!o) return R_NilValue;
+  l=(int)(*env)->GetArrayLength(env, o);
+  _dbg(rjprintf("convert int array of length %d\n",l));
+  if (l<1) return R_NilValue;
+  ap=(jint*)(*env)->GetIntArrayElements(env, o, 0);
+  if (!ap) {
+      jri_error("RgetIntArrayCont: can't fetch array contents");
+      return 0;
+  }
+  PROTECT(ar=allocVector(INTSXP,l));
+  memcpy(INTEGER(ar),ap,sizeof(jint)*l);
+  UNPROTECT(1);
+  (*env)->ReleaseIntArrayElements(env, o, ap, 0);
+  _prof(profReport("RgetIntArrayCont[%d]:",o));
+  return ar;
+}
+
+/** get contents of the integer array object (int) */
+SEXP jri_getByteArray(JNIEnv *env, jarray o) {
+  SEXP ar;
+  int l;
+  jbyte *ap;
+
+  profStart();
+  _dbg(rjprintf(" jarray %d\n",o));
+  if (!o) return R_NilValue;
+  l = (int)(*env)->GetArrayLength(env, o);
+  _dbg(rjprintf("convert byte array of length %d\n",l));
+  if (l < 1) return R_NilValue;
+  ap = (jbyte*)(*env)->GetByteArrayElements(env, o, 0);
+  if (!ap) {
+      jri_error("jri_getByteArray: can't fetch array contents");
+      return 0;
+  }
+  ar = allocVector(RAWSXP, l);
+  memcpy(RAW(ar), ap, l);
+  (*env)->ReleaseByteArrayElements(env, o, ap, 0);
+  _prof(profReport("RgetByteArrayCont[%d]:",o));
+  return ar;
+}
+
+/** get contents of the integer array object (int) into a logical R vector */
+SEXP jri_getBoolArrayI(JNIEnv *env, jarray o) {
+  SEXP ar;
+  int l;
+  jint *ap;
+
+  profStart();
+  _dbg(rjprintf(" jarray %d\n",o));
+  if (!o) return R_NilValue;
+  l=(int)(*env)->GetArrayLength(env, o);
+  _dbg(rjprintf("convert int array of length %d into R bool\n",l));
+  if (l<1) return R_NilValue;
+  ap=(jint*)(*env)->GetIntArrayElements(env, o, 0);
+  if (!ap) {
+      jri_error("RgetBoolArrayICont: can't fetch array contents");
+      return 0;
+  }
+  PROTECT(ar=allocVector(LGLSXP,l));
+  memcpy(LOGICAL(ar),ap,sizeof(jint)*l);
+  UNPROTECT(1);
+  (*env)->ReleaseIntArrayElements(env, o, ap, 0);
+  _prof(profReport("RgetBoolArrayICont[%d]:",o));
+  return ar;
+}
+
+/** get contents of the boolean array object into a logical R vector */
+SEXP jri_getBoolArray(JNIEnv *env, jarray o) {
+  SEXP ar;
+  int l;
+  jboolean *ap;
+
+  profStart();
+  _dbg(rjprintf(" jarray %d\n",o));
+  if (!o) return R_NilValue;
+  l=(int)(*env)->GetArrayLength(env, o);
+  _dbg(rjprintf("convert boolean array of length %d into R bool\n",l));
+  if (l<1) return R_NilValue;
+  ap=(jboolean*)(*env)->GetBooleanArrayElements(env, o, 0);
+  if (!ap) {
+      jri_error("RgetBoolArrayCont: can't fetch array contents");
+      return 0;
+  }
+  PROTECT(ar=allocVector(LGLSXP,l));
+  {
+    int i=0;
+    int *lgl = LOGICAL(ar);
+    while (i<l) { lgl[i]=ap[i]?1:0; i++; }
+  }
+  UNPROTECT(1);
+  (*env)->ReleaseBooleanArrayElements(env, o, ap, 0);
+  _prof(profReport("RgetBoolArrayCont[%d]:",o));
+  return ar;
+}
+
+SEXP jri_getSEXPLArray(JNIEnv *env, jarray o) {
+    SEXP ar;
+    int l,i=0;
+    jlong *ap;
+    
+    profStart();
+    _dbg(rjprintf(" jarray %d\n",o));
+    if (!o) return R_NilValue;
+    l=(int)(*env)->GetArrayLength(env, o);
+    _dbg(rjprintf("convert SEXPL array of length %d\n",l));
+    if (l<1) return R_NilValue;
+    ap=(jlong*)(*env)->GetLongArrayElements(env, o, 0);
+    if (!ap) {
+        jri_error("getSEXPLArray: can't fetch array contents");
+        return 0;
+    }
+    PROTECT(ar=allocVector(VECSXP,l));
+    while (i<l) {
+        SET_VECTOR_ELT(ar, i, L2SEXP(ap[i]));
+        i++;
+    }
+    UNPROTECT(1);
+    (*env)->ReleaseLongArrayElements(env, o, ap, 0);
+    _prof(profReport("jri_getSEXPLArray[%d]:",o));
+    return ar;
+}
+
+/** get contents of the double array object (int) */
+SEXP jri_getDoubleArray(JNIEnv *env, jarray o) {
+  SEXP ar;
+  int l;
+  jdouble *ap;
+
+  profStart();
+  _dbg(rjprintf(" jarray %d\n",o));
+  if (!o) return R_NilValue;
+  l=(int)(*env)->GetArrayLength(env, o);
+  _dbg(rjprintf("convert double array of length %d\n",l));
+  if (l<1) return R_NilValue;
+  ap=(jdouble*)(*env)->GetDoubleArrayElements(env, o, 0);
+  if (!ap) {
+      jri_error("RgetDoubleArrayCont: can't fetch array contents");
+      return 0;
+  }
+  PROTECT(ar=allocVector(REALSXP,l));
+  memcpy(REAL(ar),ap,sizeof(jdouble)*l);
+  UNPROTECT(1);
+  (*env)->ReleaseDoubleArrayElements(env, o, ap, 0);
+  _prof(profReport("RgetDoubleArrayCont[%d]:",o));
+  return ar;
+}
+
+#if R_VERSION >= R_Version(2,7,0)
+/* returns string from a CHARSXP making sure that the result is in UTF-8 */
+const char *jri_char_utf8(SEXP s) {
+        if (Rf_getCharCE(s) == CE_UTF8) return CHAR(s);
+        return Rf_reEnc(CHAR(s), getCharCE(s), CE_UTF8, 1); /* subst. invalid chars: 1=hex, 2=., 3=?, other=skip */
+}
+#endif
+
+void jri_checkExceptions(JNIEnv *env, int describe)
+{
+    jthrowable t=(*env)->ExceptionOccurred(env);
+    if (t) {
+#ifndef JRI_DEBUG
+        if (describe)
+#endif
+            (*env)->ExceptionDescribe(env);
+        (*env)->ExceptionClear(env);
+    }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/src/jri.h b/com.oracle.truffle.r.pkgs/rJava/jri/src/jri.h
new file mode 100644
index 0000000000000000000000000000000000000000..05dae0fe5a533ecf5a537a6bcb4b8f9eba226274
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/src/jri.h
@@ -0,0 +1,96 @@
+#ifndef __JRI_H__
+#define __JRI_H__
+
+#include <jni.h>
+#include <R.h>
+#include <Rinternals.h>
+#include <Rdefines.h>
+#include <Rversion.h>
+
+/* the viewpoint is from R, i.e. "get" means "Java->R" whereas "put" means "R->Java" */
+
+#define JRI_VERSION 0x0505 /* JRI v0.5-5 */
+#define JRI_API     0x010a /* API-version 1.10 */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+    
+  /* jlong can always hold a pointer 
+     to avoid warnings we go ptr->ulong->jlong */
+#define SEXP2L(s) ((jlong)(s))
+#ifdef WIN64
+#define L2SEXP(s) ((SEXP)((jlong)(s)))
+#else
+#define L2SEXP(s) ((SEXP)((jlong)((unsigned long)(s))))
+#endif
+
+jstring jri_callToString(JNIEnv *env, jobject o);
+
+SEXP jri_getDoubleArray(JNIEnv *env, jarray o);
+SEXP jri_getIntArray(JNIEnv *env, jarray o);
+SEXP jri_getByteArray(JNIEnv *env, jarray o);
+SEXP jri_getBoolArrayI(JNIEnv *env, jarray o);
+SEXP jri_getBoolArray(JNIEnv *env, jarray o);
+SEXP jri_getObjectArray(JNIEnv *env, jarray o);
+SEXP jri_getString(JNIEnv *env, jstring s);
+SEXP jri_getStringArray(JNIEnv *env, jarray o);
+SEXP jri_getSEXPLArray(JNIEnv *env, jarray o);
+
+SEXP jri_installString(JNIEnv *env, jstring s); /* as Rf_install, just for Java strings */
+
+jarray  jri_putDoubleArray(JNIEnv *env, SEXP e);
+jarray  jri_putIntArray(JNIEnv *env, SEXP e);
+jarray  jri_putBoolArrayI(JNIEnv *env, SEXP e);
+jarray  jri_putByteArray(JNIEnv *env, SEXP e);
+jstring jri_putString(JNIEnv *env, SEXP e, int ix); /* ix=index, 0=1st */
+jarray  jri_putStringArray(JNIEnv *env, SEXP e);
+jarray jri_putSEXPLArray(JNIEnv *env, SEXP e); /* SEXPs are strored as "long"s */
+
+jstring jri_putSymbolName(JNIEnv *env, SEXP e);
+
+void jri_checkExceptions(JNIEnv *env, int describe);
+
+void jri_error(char *fmt, ...);
+
+/* define mkCharUTF8 in a compatible fashion */
+#if R_VERSION < R_Version(2,7,0)
+#define mkCharUTF8(X) mkChar(X)
+#define CHAR_UTF8(X) CHAR(X)
+#else
+#define mkCharUTF8(X) mkCharCE(X, CE_UTF8)
+#define CHAR_UTF8(X) jri_char_utf8(X)
+const char *jri_char_utf8(SEXP);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+/*
+   API version changes:
+ -----------------------
+   1.3 (initial public API version)
+ [ 1.4 never publicly released - added put/getenv but was abandoned ]
+   1.5 JRI 0.3-0
+       + rniGetTAG
+       + rniInherits
+       + rniGetSymbolName
+       + rniInstallSymbol
+       + rniJavaToXref, rniXrefToJava
+   1.6 JRI 0.3-2
+       + rniPutBoolArray, rniPutBoolArrayI, rniGetBoolArrayI
+   1.7 JRI 0.3-7
+       + rniCons(+2 args)
+   1.8 JRI 0.4-0
+       + rniPrint
+   1.9 JRI 0.4-3
+       + rniPreserve, rniRelease
+       + rniParentEnv, rniFindVar, rniListEnv
+       + rniSpecialObject(0-7)
+       + rniPrintValue
+    1.10 JRI 0.5-1
+       * rniAssign returns jboolean instead of void
+*/
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/src/rjava.c b/com.oracle.truffle.r.pkgs/rJava/jri/src/rjava.c
new file mode 100644
index 0000000000000000000000000000000000000000..c66f52f908d48069ccee3f3577659515416b1815
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/src/rjava.c
@@ -0,0 +1,56 @@
+#include "rjava.h"
+#include <unistd.h>
+
+#ifdef _WIN64
+typedef long long ptrlong;
+#else
+typedef long ptrlong;
+#endif
+
+int ipcout;
+int resin;
+int *rjctrl = 0;
+
+typedef void(callbackfn)(void *);
+
+int RJava_request_lock() {
+  ptrlong buf[4];
+  int n;
+  if (rjctrl && *rjctrl) return 2;
+
+  buf[0] = IPCC_LOCK_REQUEST;
+  write(ipcout, buf, sizeof(ptrlong));
+  n = read(resin, buf, sizeof(ptrlong));
+  return (n > 0 && buf[0] == IPCC_LOCK_GRANTED) ? 1 : 0;
+}
+
+int RJava_clear_lock() {
+  ptrlong buf[4];
+  buf[0] = IPCC_CLEAR_LOCK;
+  write(ipcout, buf, sizeof(ptrlong));
+  return 1;
+}
+
+void RJava_request_callback(callbackfn *fn, void *data) {
+  ptrlong buf[4];
+  buf[0] = IPCC_CALL_REQUEST;
+  buf[1] = (ptrlong) fn;
+  buf[2] = (ptrlong) data;
+  write(ipcout, buf, sizeof(ptrlong) * 3);
+}
+
+void RJava_setup(int _in, int _out) {
+  /* ptrlong buf[4]; */
+  ipcout = _out;
+  resin = _in;
+}
+
+void RJava_init_ctrl() {
+  ptrlong buf[4];
+  buf[0] = IPCC_CONTROL_ADDR;
+  write(ipcout, buf, sizeof(ptrlong));
+  read(resin, buf, sizeof(ptrlong) * 2);
+  if (buf[0] == IPCC_CONTROL_ADDR) {
+    rjctrl= (int*) buf[1];
+  }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/src/rjava.h b/com.oracle.truffle.r.pkgs/rJava/jri/src/rjava.h
new file mode 100644
index 0000000000000000000000000000000000000000..ba6c84df1a40f17f341f17264d4157652254aa38
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/src/rjava.h
@@ -0,0 +1,20 @@
+#ifndef __CALLBACK_H__
+#define __CALLBACK_H__
+
+#define RJavaActivity 16
+
+/* all IPC messages are long-alligned */
+#define IPCC_LOCK_REQUEST 1
+#define IPCC_LOCK_GRANTED 2 /* reponse on IPCC_LOCK_REQUEST */
+#define IPCC_CLEAR_LOCK   3
+#define IPCC_CALL_REQUEST 4 /* pars: <fn-ptr> <data-ptr> */
+#define IPCC_CONTROL_ADDR 5 /* ipc: request, res: <ctrl-ptr> */
+
+int RJava_request_lock();
+int RJava_clear_lock();
+/* void RJava_request_callback(callbackfn *fn, void *data); */
+void RJava_setup(int _in, int _out);
+void RJava_init_ctrl();
+
+#endif
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/src/win32/Makefile b/com.oracle.truffle.r.pkgs/rJava/jri/src/win32/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..3fbfdcbe4731b4ab0403415ede1fa0f972f8b602
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/src/win32/Makefile
@@ -0,0 +1,33 @@
+# helper tools and libs for building and running rJava for Windows
+# Author: Simon Urbanek
+
+include $(R_HOME)/etc$(R_ARCH)/Makeconf
+
+TARGETS=libjvm.dll.a findjava.exe
+
+# libjvm.dll.a    - wrapper lib for jvm.dll from Java
+# findjava.exe    - helper tool to find the current JDK from the registry
+
+all: $(TARGETS)
+
+ifeq ($(strip $(shell $(R_HOME)/bin/R --slave -e 'cat(.Machine$$sizeof.pointer)')),8)
+JVMDEF=jvm64.def
+else
+JVMDEF=jvm.def
+endif
+
+libjvm.dll.a: $(JVMDEF)
+	$(DLLTOOL) --input-def $^ --kill-at --dllname jvm.dll --output-lib $@
+
+# compile findjava.exe from source - no magic here, no special libs necessary
+findjava.o: findjava.c
+	$(CC) -O2 -c -o $@ $^
+
+findjava.exe: findjava.o
+	$(CC) -s -o $@ $^
+
+# just cleanup everything
+clean:
+	rm -f *.o *~ $(TARGETS)
+
+.PHONY: all clean
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/src/win32/findjava.c b/com.oracle.truffle.r.pkgs/rJava/jri/src/win32/findjava.c
new file mode 100644
index 0000000000000000000000000000000000000000..6c8415882d13d5609c3ed4a5499aed608e99d392
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/src/win32/findjava.c
@@ -0,0 +1,97 @@
+#include <windows.h>
+#include <winreg.h>
+#include <stdio.h>
+
+static char RegStrBuf[32768], dbuf[32768];
+
+int main(int argc, char **argv) {
+  int i=0, doit=0;
+  DWORD t,s=32767;
+  HKEY k;
+  HKEY root=HKEY_LOCAL_MACHINE;
+  char *javakey="Software\\JavaSoft\\Java Runtime Environment";
+
+  if (argc>1 && argv[1][0]=='-' && argv[1][1]=='R') {
+    if (getenv("R_HOME")) {
+      strcpy(RegStrBuf,getenv("R_HOME"));
+    } else {
+      javakey="Software\\R-core\\R"; s=32767;
+      if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,javakey,0,KEY_QUERY_VALUE,&k)!=ERROR_SUCCESS ||
+	  RegQueryValueEx(k,"InstallPAth",0,&t,RegStrBuf,&s)!=ERROR_SUCCESS) {
+	if (RegOpenKeyEx(HKEY_CURRENT_USER,javakey,0,KEY_QUERY_VALUE,&k)!=ERROR_SUCCESS ||
+	    RegQueryValueEx(k,"InstallPath",0,&t,RegStrBuf,&s)!=ERROR_SUCCESS) {
+	  fprintf(stderr, "ERROR*> R - can't open registry keys.\n");
+	  return -1;
+	}
+      }
+    }
+  } else
+  /* JAVA_HOME can override our detection - but we still post-process it */
+  if (getenv("JAVA_HOME")) {
+    strcpy(RegStrBuf,getenv("JAVA_HOME"));
+  } else {
+
+#ifdef FINDJRE
+    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,javakey,0,KEY_QUERY_VALUE,&k)!=ERROR_SUCCESS ||
+	RegQueryValueEx(k,"CurrentVersion",0,&t,RegStrBuf,&s)!=ERROR_SUCCESS) {
+#endif
+      javakey="Software\\JavaSoft\\Java Development Kit"; s=32767;
+      if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,javakey,0,KEY_QUERY_VALUE,&k)!=ERROR_SUCCESS ||
+	  RegQueryValueEx(k,"CurrentVersion",0,&t,RegStrBuf,&s)!=ERROR_SUCCESS) {
+	fprintf(stderr, "ERROR*> JavaSoft\\{JRE|JDK} can't open registry keys.\n");
+	/* MessageBox(wh, "Can't find Sun's Java runtime.\nPlease install Sun's J2SE JRE or JDK 1.4.2 or later (see http://java.sun.com/).","Can't find Sun's Java",MB_OK|MB_ICONERROR); */
+	return -1;
+      }
+#ifdef FINDJRE
+    }
+#endif
+    RegCloseKey(k); s=32767;
+
+    strcpy(dbuf,javakey);
+    strcat(dbuf,"\\");
+    strcat(dbuf,RegStrBuf);
+    javakey=(char*) malloc(strlen(dbuf)+1);
+    strcpy(javakey, dbuf);
+    
+    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,javakey,0,KEY_QUERY_VALUE,&k)!=ERROR_SUCCESS ||
+	RegQueryValueEx(k,"JavaHome",0,&t,RegStrBuf,&s)!=ERROR_SUCCESS) {
+      fprintf(stderr, "There's no JavaHome value in the JDK/JRE registry key.\n");
+      /* MessageBox(wh, "Can't find Java home path. Maybe your JRE is too old.\nPlease install Sun's J2SE JRE or SDK 1.4.2 (see http://java.sun.com/).","Can't find Sun's Java",MB_OK|MB_ICONERROR); */
+      return -1;
+    }
+    RegCloseKey(k);
+  }
+  
+  /*--- post-processing according to supplied flags --*/
+
+  /* -a = automagic, i.e. use short name only if the name contains spaces */
+  i=1;
+  while (i<argc) if (!strcmp(argv[i++],"-a")) { doit=1; break; };
+  if (doit) {
+    int hasws=0;
+    char *c=dbuf;
+    while (*c) { if (*c==' '||*c=='\t') { hasws=1; break; } c++; };
+    if (!hasws) doit=0;
+  }
+
+  /* -s = short name */
+  if (!doit) {
+    i=1;
+    while (i<argc) if (!strcmp(argv[i++],"-s")) { doit=1; break; };
+  }
+  strcpy(dbuf, RegStrBuf);
+  if (doit)
+    GetShortPathName(RegStrBuf, dbuf, 32768);
+
+  /* -f = forward slashes */
+  doit=0; i=1;
+  while (i<argc) if (!strcmp(argv[i++],"-f")) { doit=1; break; };
+  if (doit) {
+    char *c=dbuf;
+    while (*c) { if (*c=='\\') *c='/'; c++; };
+  }
+
+  puts(dbuf);
+  return 0;
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/src/win32/jvm.def b/com.oracle.truffle.r.pkgs/rJava/jri/src/win32/jvm.def
new file mode 100644
index 0000000000000000000000000000000000000000..b27b1bc8b44cc5b931161ba2c5f6ed0a0224b84b
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/src/win32/jvm.def
@@ -0,0 +1,6 @@
+LIBRARY     JVM.DLL
+
+EXPORTS
+    JNI_CreateJavaVM@12
+    JNI_GetCreatedJavaVMs@12
+    JNI_GetDefaultJavaVMInitArgs@4
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/src/win32/jvm64.def b/com.oracle.truffle.r.pkgs/rJava/jri/src/win32/jvm64.def
new file mode 100755
index 0000000000000000000000000000000000000000..343b82fe4d3557169aae994d8101a2086de44b20
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/src/win32/jvm64.def
@@ -0,0 +1,6 @@
+LIBRARY     JVM.DLL
+
+EXPORTS
+    JNI_CreateJavaVM
+    JNI_GetCreatedJavaVMs
+    JNI_GetDefaultJavaVMInitArgs
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/tools/config.guess b/com.oracle.truffle.r.pkgs/rJava/jri/tools/config.guess
new file mode 100755
index 0000000000000000000000000000000000000000..b79252d6b1034cbcce18ed21d4ed21a405f987e9
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/tools/config.guess
@@ -0,0 +1,1558 @@
+#! /bin/sh
+# Attempt to guess a canonical system name.
+#   Copyright 1992-2013 Free Software Foundation, Inc.
+
+timestamp='2013-06-10'
+
+# 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 3 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, see <http://www.gnu.org/licenses/>.
+#
+# 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.  This Exception is an additional permission under section 7
+# of the GNU General Public License, version 3 ("GPLv3").
+#
+# Originally written by Per Bothner.
+#
+# You can get the latest version of this script from:
+# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
+#
+# Please send patches with a ChangeLog entry to config-patches@gnu.org.
+
+
+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 1992-2013 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
+
+case "${UNAME_SYSTEM}" in
+Linux|GNU|GNU/*)
+	# If the system lacks a compiler, then just pick glibc.
+	# We could probably try harder.
+	LIBC=gnu
+
+	eval $set_cc_for_build
+	cat <<-EOF > $dummy.c
+	#include <features.h>
+	#if defined(__UCLIBC__)
+	LIBC=uclibc
+	#elif defined(__dietlibc__)
+	LIBC=dietlibc
+	#else
+	LIBC=gnu
+	#endif
+	EOF
+	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'`
+	;;
+esac
+
+# 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 tuples: *-*-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 ;;
+	    sh5el) machine=sh5le-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 -q __ELF__
+		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 ;;
+    *:Bitrig:*:*)
+	UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'`
+	echo ${UNAME_MACHINE_ARCH}-unknown-bitrig${UNAME_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'`
+	# Reset EXIT trap before exiting to avoid spurious non-zero exit code.
+	exitcode=$?
+	trap '' 0
+	exit $exitcode ;;
+    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 ;;
+    s390x:SunOS:*:*)
+	echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    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:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*)
+	echo i386-pc-auroraux${UNAME_RELEASE}
+	exit ;;
+    i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*)
+	eval $set_cc_for_build
+	SUN_ARCH="i386"
+	# If there is a compiler, see if it is configured for 64-bit objects.
+	# Note that the Sun cc does not turn __LP64__ into 1 like gcc does.
+	# This test works for both compilers.
+	if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
+	    if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \
+		(CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
+		grep IS_64BIT_ARCH >/dev/null
+	    then
+		SUN_ARCH="x86_64"
+	    fi
+	fi
+	echo ${SUN_ARCH}-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:*:[4567])
+	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 -q __LP64__
+	    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:*:*)
+	UNAME_PROCESSOR=`/usr/bin/uname -p`
+	case ${UNAME_PROCESSOR} in
+	    amd64)
+		echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+	    *)
+		echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+	esac
+	exit ;;
+    i*:CYGWIN*:*)
+	echo ${UNAME_MACHINE}-pc-cygwin
+	exit ;;
+    *:MINGW64*:*)
+	echo ${UNAME_MACHINE}-pc-mingw64
+	exit ;;
+    *:MINGW*:*)
+	echo ${UNAME_MACHINE}-pc-mingw32
+	exit ;;
+    i*:MSYS*:*)
+	echo ${UNAME_MACHINE}-pc-msys
+	exit ;;
+    i*:windows32*:*)
+	# uname -m includes "-pc" on this system.
+	echo ${UNAME_MACHINE}-mingw32
+	exit ;;
+    i*:PW*:*)
+	echo ${UNAME_MACHINE}-pc-pw32
+	exit ;;
+    *:Interix*:*)
+	case ${UNAME_MACHINE} in
+	    x86)
+		echo i586-pc-interix${UNAME_RELEASE}
+		exit ;;
+	    authenticamd | genuineintel | EM64T)
+		echo x86_64-unknown-interix${UNAME_RELEASE}
+		exit ;;
+	    IA64)
+		echo ia64-unknown-interix${UNAME_RELEASE}
+		exit ;;
+	esac ;;
+    [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*)
+	echo i${UNAME_MACHINE}-pc-mks
+	exit ;;
+    8664:Windows_NT:*)
+	echo x86_64-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-${LIBC}`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/[-(].*//'`-${LIBC}
+	exit ;;
+    i*86:Minix:*:*)
+	echo ${UNAME_MACHINE}-pc-minix
+	exit ;;
+    aarch64:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    aarch64_be:Linux:*:*)
+	UNAME_MACHINE=aarch64_be
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	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 -q ld.so.1
+	if test "$?" = 0 ; then LIBC="gnulibc1" ; fi
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    arc:Linux:*:* | arceb:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    arm*:Linux:*:*)
+	eval $set_cc_for_build
+	if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \
+	    | grep -q __ARM_EABI__
+	then
+	    echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	else
+	    if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \
+		| grep -q __ARM_PCS_VFP
+	    then
+		echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabi
+	    else
+		echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabihf
+	    fi
+	fi
+	exit ;;
+    avr32*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    cris:Linux:*:*)
+	echo ${UNAME_MACHINE}-axis-linux-${LIBC}
+	exit ;;
+    crisv32:Linux:*:*)
+	echo ${UNAME_MACHINE}-axis-linux-${LIBC}
+	exit ;;
+    frv:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    hexagon:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    i*86:Linux:*:*)
+	echo ${UNAME_MACHINE}-pc-linux-${LIBC}
+	exit ;;
+    ia64:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    m32r*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    m68*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    mips:Linux:*:* | mips64:Linux:*:*)
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+	#undef CPU
+	#undef ${UNAME_MACHINE}
+	#undef ${UNAME_MACHINE}el
+	#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
+	CPU=${UNAME_MACHINE}el
+	#else
+	#if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
+	CPU=${UNAME_MACHINE}
+	#else
+	CPU=
+	#endif
+	#endif
+EOF
+	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'`
+	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; }
+	;;
+    or1k:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    or32:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    padre:Linux:*:*)
+	echo sparc-unknown-linux-${LIBC}
+	exit ;;
+    parisc64:Linux:*:* | hppa64:Linux:*:*)
+	echo hppa64-unknown-linux-${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-${LIBC} ;;
+	  PA8*) echo hppa2.0-unknown-linux-${LIBC} ;;
+	  *)    echo hppa-unknown-linux-${LIBC} ;;
+	esac
+	exit ;;
+    ppc64:Linux:*:*)
+	echo powerpc64-unknown-linux-${LIBC}
+	exit ;;
+    ppc:Linux:*:*)
+	echo powerpc-unknown-linux-${LIBC}
+	exit ;;
+    ppc64le:Linux:*:*)
+	echo powerpc64le-unknown-linux-${LIBC}
+	exit ;;
+    ppcle:Linux:*:*)
+	echo powerpcle-unknown-linux-${LIBC}
+	exit ;;
+    s390:Linux:*:* | s390x:Linux:*:*)
+	echo ${UNAME_MACHINE}-ibm-linux-${LIBC}
+	exit ;;
+    sh64*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    sh*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    sparc:Linux:*:* | sparc64:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    tile*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    vax:Linux:*:*)
+	echo ${UNAME_MACHINE}-dec-linux-${LIBC}
+	exit ;;
+    x86_64:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    xtensa*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	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.[02]*:*)
+	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 i586.
+	# Note: whatever this is, it MUST be the same as what config.sub
+	# prints for the "djgpp" host, or else GDB configury will decide that
+	# this is a cross-build.
+	echo i586-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; } ;;
+    NCR*:*:4.2:* | MPRAS*:*:4.2:*)
+	OS_REL='.3'
+	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; }
+	/bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \
+	    && { echo i586-ncr-sysv4.3${OS_REL}; 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.[02]*:*)
+	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 ;;
+    BePC:Haiku:*:*)	# Haiku running on Intel PC compatible.
+	echo i586-pc-haiku
+	exit ;;
+    x86_64:Haiku:*:*)
+	echo x86_64-unknown-haiku
+	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 ;;
+    SX-7:SUPER-UX:*:*)
+	echo sx7-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-8:SUPER-UX:*:*)
+	echo sx8-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-8R:SUPER-UX:*:*)
+	echo sx8r-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
+	eval $set_cc_for_build
+	if test "$UNAME_PROCESSOR" = unknown ; then
+	    UNAME_PROCESSOR=powerpc
+	fi
+	if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
+	    if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
+		(CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
+		grep IS_64BIT_ARCH >/dev/null
+	    then
+		case $UNAME_PROCESSOR in
+		    i386) UNAME_PROCESSOR=x86_64 ;;
+		    powerpc) UNAME_PROCESSOR=powerpc64 ;;
+		esac
+	    fi
+	fi
+	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 ;;
+    NEO-?:NONSTOP_KERNEL:*:*)
+	echo neo-tandem-nsk${UNAME_RELEASE}
+	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 ;;
+    i*86:AROS:*:*)
+	echo ${UNAME_MACHINE}-pc-aros
+	exit ;;
+    x86_64:VMkernel:*:*)
+	echo ${UNAME_MACHINE}-unknown-esx
+	exit ;;
+esac
+
+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://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
+and
+  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
+
+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/com.oracle.truffle.r.pkgs/rJava/jri/tools/config.sub b/com.oracle.truffle.r.pkgs/rJava/jri/tools/config.sub
new file mode 100755
index 0000000000000000000000000000000000000000..9633db704678e91ad221adc4f30a22ce0bc61e1b
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/tools/config.sub
@@ -0,0 +1,1791 @@
+#! /bin/sh
+# Configuration validation subroutine script.
+#   Copyright 1992-2013 Free Software Foundation, Inc.
+
+timestamp='2013-08-10'
+
+# 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 3 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, see <http://www.gnu.org/licenses/>.
+#
+# 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.  This Exception is an additional permission under section 7
+# of the GNU General Public License, version 3 ("GPLv3").
+
+
+# Please send patches with a ChangeLog entry to config-patches@gnu.org.
+#
+# 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.
+
+# You can get the latest version of this script from:
+# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
+
+# 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 1992-2013 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-android* | linux-dietlibc | linux-newlib* | \
+  linux-musl* | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \
+  knetbsd*-gnu* | netbsd*-gnu* | \
+  kopensolaris*-gnu* | \
+  storm-chaos* | os2-emx* | rtmk-nova*)
+    os=-$maybe_os
+    basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
+    ;;
+  android-linux)
+    os=-linux-android
+    basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown
+    ;;
+  *)
+    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 | -microblaze*)
+		os=
+		basic_machine=$1
+		;;
+	-bluegene*)
+		os=-cnk
+		;;
+	-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*178)
+		os=-lynxos178
+		;;
+	-lynx*5)
+		os=-lynxos5
+		;;
+	-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 \
+	| aarch64 | aarch64_be \
+	| alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
+	| alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
+	| am33_2.0 \
+	| arc | arceb \
+	| arm | arm[bl]e | arme[lb] | armv[2-8] | armv[3-8][lb] | armv7[arm] \
+	| avr | avr32 \
+	| be32 | be64 \
+	| bfin \
+	| c4x | c8051 | clipper \
+	| d10v | d30v | dlx | dsp16xx \
+	| epiphany \
+	| fido | fr30 | frv \
+	| h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
+	| hexagon \
+	| i370 | i860 | i960 | ia64 \
+	| ip2k | iq2000 \
+	| le32 | le64 \
+	| lm32 \
+	| m32c | m32r | m32rle | m68000 | m68k | m88k \
+	| maxq | mb | microblaze | microblazeel | mcore | mep | metag \
+	| mips | mipsbe | mipseb | mipsel | mipsle \
+	| mips16 \
+	| mips64 | mips64el \
+	| mips64octeon | mips64octeonel \
+	| mips64orion | mips64orionel \
+	| mips64r5900 | mips64r5900el \
+	| mips64vr | mips64vrel \
+	| mips64vr4100 | mips64vr4100el \
+	| mips64vr4300 | mips64vr4300el \
+	| mips64vr5000 | mips64vr5000el \
+	| mips64vr5900 | mips64vr5900el \
+	| mipsisa32 | mipsisa32el \
+	| mipsisa32r2 | mipsisa32r2el \
+	| mipsisa64 | mipsisa64el \
+	| mipsisa64r2 | mipsisa64r2el \
+	| mipsisa64sb1 | mipsisa64sb1el \
+	| mipsisa64sr71k | mipsisa64sr71kel \
+	| mipsr5900 | mipsr5900el \
+	| mipstx39 | mipstx39el \
+	| mn10200 | mn10300 \
+	| moxie \
+	| mt \
+	| msp430 \
+	| nds32 | nds32le | nds32be \
+	| nios | nios2 | nios2eb | nios2el \
+	| ns16k | ns32k \
+	| open8 \
+	| or1k | or32 \
+	| pdp10 | pdp11 | pj | pjl \
+	| powerpc | powerpc64 | powerpc64le | powerpcle \
+	| pyramid \
+	| rl78 | rx \
+	| score \
+	| sh | sh[1234] | sh[24]a | sh[24]aeb | 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 \
+	| tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \
+	| ubicom32 \
+	| v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \
+	| we32k \
+	| x86 | xc16x | xstormy16 | xtensa \
+	| z8k | z80)
+		basic_machine=$basic_machine-unknown
+		;;
+	c54x)
+		basic_machine=tic54x-unknown
+		;;
+	c55x)
+		basic_machine=tic55x-unknown
+		;;
+	c6x)
+		basic_machine=tic6x-unknown
+		;;
+	m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | picochip)
+		basic_machine=$basic_machine-unknown
+		os=-none
+		;;
+	m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)
+		;;
+	ms1)
+		basic_machine=mt-unknown
+		;;
+
+	strongarm | thumb | xscale)
+		basic_machine=arm-unknown
+		;;
+	xgate)
+		basic_machine=$basic_machine-unknown
+		os=-none
+		;;
+	xscaleeb)
+		basic_machine=armeb-unknown
+		;;
+
+	xscaleel)
+		basic_machine=armel-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-* \
+	| aarch64-* | aarch64_be-* \
+	| alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
+	| alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
+	| alphapca5[67]-* | alpha64pca5[67]-* | arc-* | arceb-* \
+	| arm-*  | armbe-* | armle-* | armeb-* | armv*-* \
+	| avr-* | avr32-* \
+	| be32-* | be64-* \
+	| bfin-* | bs2000-* \
+	| c[123]* | c30-* | [cjt]90-* | c4x-* \
+	| c8051-* | clipper-* | craynv-* | cydra-* \
+	| d10v-* | d30v-* | dlx-* \
+	| elxsi-* \
+	| f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \
+	| h8300-* | h8500-* \
+	| hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
+	| hexagon-* \
+	| i*86-* | i860-* | i960-* | ia64-* \
+	| ip2k-* | iq2000-* \
+	| le32-* | le64-* \
+	| lm32-* \
+	| m32c-* | m32r-* | m32rle-* \
+	| m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
+	| m88110-* | m88k-* | maxq-* | mcore-* | metag-* \
+	| microblaze-* | microblazeel-* \
+	| mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
+	| mips16-* \
+	| mips64-* | mips64el-* \
+	| mips64octeon-* | mips64octeonel-* \
+	| mips64orion-* | mips64orionel-* \
+	| mips64r5900-* | mips64r5900el-* \
+	| mips64vr-* | mips64vrel-* \
+	| mips64vr4100-* | mips64vr4100el-* \
+	| mips64vr4300-* | mips64vr4300el-* \
+	| mips64vr5000-* | mips64vr5000el-* \
+	| mips64vr5900-* | mips64vr5900el-* \
+	| mipsisa32-* | mipsisa32el-* \
+	| mipsisa32r2-* | mipsisa32r2el-* \
+	| mipsisa64-* | mipsisa64el-* \
+	| mipsisa64r2-* | mipsisa64r2el-* \
+	| mipsisa64sb1-* | mipsisa64sb1el-* \
+	| mipsisa64sr71k-* | mipsisa64sr71kel-* \
+	| mipsr5900-* | mipsr5900el-* \
+	| mipstx39-* | mipstx39el-* \
+	| mmix-* \
+	| mt-* \
+	| msp430-* \
+	| nds32-* | nds32le-* | nds32be-* \
+	| nios-* | nios2-* | nios2eb-* | nios2el-* \
+	| none-* | np1-* | ns16k-* | ns32k-* \
+	| open8-* \
+	| orion-* \
+	| pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
+	| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \
+	| pyramid-* \
+	| rl78-* | romp-* | rs6000-* | rx-* \
+	| sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | 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-* | sv1-* | sx?-* \
+	| tahoe-* \
+	| tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
+	| tile*-* \
+	| tron-* \
+	| ubicom32-* \
+	| v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \
+	| vax-* \
+	| we32k-* \
+	| x86-* | x86_64-* | xc16x-* | xps100-* \
+	| xstormy16-* | xtensa*-* \
+	| ymp-* \
+	| z8k-* | z80-*)
+		;;
+	# Recognize the basic CPU types without company name, with glob match.
+	xtensa*)
+		basic_machine=$basic_machine-unknown
+		;;
+	# 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
+		;;
+	aros)
+		basic_machine=i386-pc
+		os=-aros
+		;;
+	aux)
+		basic_machine=m68k-apple
+		os=-aux
+		;;
+	balance)
+		basic_machine=ns32k-sequent
+		os=-dynix
+		;;
+	blackfin)
+		basic_machine=bfin-unknown
+		os=-linux
+		;;
+	blackfin-*)
+		basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'`
+		os=-linux
+		;;
+	bluegene*)
+		basic_machine=powerpc-ibm
+		os=-cnk
+		;;
+	c54x-*)
+		basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	c55x-*)
+		basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	c6x-*)
+		basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	c90)
+		basic_machine=c90-cray
+		os=-unicos
+		;;
+	cegcc)
+		basic_machine=arm-unknown
+		os=-cegcc
+		;;
+	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
+		;;
+	cr16 | cr16-*)
+		basic_machine=cr16-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
+		;;
+	dicos)
+		basic_machine=i686-pc
+		os=-dicos
+		;;
+	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*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
+		;;
+	m68knommu)
+		basic_machine=m68k-unknown
+		os=-linux
+		;;
+	m68knommu-*)
+		basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'`
+		os=-linux
+		;;
+	m88k-omron*)
+		basic_machine=m88k-omron
+		;;
+	magnum | m3230)
+		basic_machine=mips-mips
+		os=-sysv
+		;;
+	merlin)
+		basic_machine=ns32k-utek
+		os=-sysv
+		;;
+	microblaze*)
+		basic_machine=microblaze-xilinx
+		;;
+	mingw64)
+		basic_machine=x86_64-pc
+		os=-mingw64
+		;;
+	mingw32)
+		basic_machine=i686-pc
+		os=-mingw32
+		;;
+	mingw32ce)
+		basic_machine=arm-unknown
+		os=-mingw32ce
+		;;
+	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-/'`
+		;;
+	msys)
+		basic_machine=i686-pc
+		os=-msys
+		;;
+	mvs)
+		basic_machine=i370-ibm
+		os=-mvs
+		;;
+	nacl)
+		basic_machine=le32-unknown
+		os=-nacl
+		;;
+	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
+		;;
+	neo-tandem)
+		basic_machine=neo-tandem
+		;;
+	nse-tandem)
+		basic_machine=nse-tandem
+		;;
+	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
+		;;
+	parisc)
+		basic_machine=hppa-unknown
+		os=-linux
+		;;
+	parisc-*)
+		basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'`
+		os=-linux
+		;;
+	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 | ppcbe)	basic_machine=powerpc-unknown
+		;;
+	ppc-* | ppcbe-*)
+		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 | rdos64)
+		basic_machine=x86_64-pc
+		os=-rdos
+		;;
+	rdos32)
+		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
+		;;
+	sh5el)
+		basic_machine=sh5le-unknown
+		;;
+	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
+		;;
+	strongarm-* | thumb-*)
+		basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	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
+		;;
+	tile*)
+		basic_machine=$basic_machine-unknown
+		os=-linux-gnu
+		;;
+	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
+		;;
+	xscale-* | xscalee[bl]-*)
+		basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'`
+		;;
+	ymp)
+		basic_machine=ymp-cray
+		os=-unicos
+		;;
+	z8k-*-coff)
+		basic_machine=z8k-unknown
+		os=-sim
+		;;
+	z80-*-coff)
+		basic_machine=z80-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[24]aeb | 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.
+	-auroraux)
+		os=-auroraux
+		;;
+	-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* | -cnk* | -sunos | -sunos[34]*\
+	      | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \
+	      | -sym* | -kopensolaris* | -plan9* \
+	      | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
+	      | -aos* | -aros* \
+	      | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
+	      | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
+	      | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \
+	      | -bitrig* | -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* | -cegcc* \
+	      | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
+	      | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \
+	      | -linux-newlib* | -linux-musl* | -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* | -drops* | -es*)
+	# 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
+		;;
+	-zvmoe)
+		os=-zvmoe
+		;;
+	-dicos*)
+		os=-dicos
+		;;
+	-nacl*)
+		;;
+	-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
+		;;
+	c8051-*)
+		os=-elf
+		;;
+	hexagon-*)
+		os=-elf
+		;;
+	tic54x-*)
+		os=-coff
+		;;
+	tic55x-*)
+		os=-coff
+		;;
+	tic6x-*)
+		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
+		;;
+	m68*-cisco)
+		os=-aout
+		;;
+	mep-*)
+		os=-elf
+		;;
+	mips*-cisco)
+		os=-elf
+		;;
+	mips*-*)
+		os=-elf
+		;;
+	or1k-*)
+		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
+				;;
+			-cnk*|-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/com.oracle.truffle.r.pkgs/rJava/jri/tools/getsp.java b/com.oracle.truffle.r.pkgs/rJava/jri/tools/getsp.java
new file mode 100644
index 0000000000000000000000000000000000000000..76b293d9b904eac2a02bc8eeaff466b97d1a3ff8
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/tools/getsp.java
@@ -0,0 +1,32 @@
+public class getsp {
+    public static void main(String[] args) {
+	if (args!=null && args.length>0) {
+	    if (args[0].compareTo("-test")==0) {
+		System.out.println("Test1234OK");
+	    } else
+	    if (args[0].compareTo("-libs")==0) {
+		String prefix="-L";
+		if (args.length>1) prefix=args[1];
+		String lp=System.getProperty("java.library.path");
+		// we're not using StringTokenizer in case the JVM is very crude
+		int i=0,j,k=0;
+		String r=null;
+		String pss=System.getProperty("path.separator");
+		char ps=':';
+		if (pss!=null && pss.length()>0) ps=pss.charAt(0);
+		j=lp.length();
+		while (i<=j) {
+		    if (i==j || lp.charAt(i)==ps) {
+			String lib=lp.substring(k,i);
+			k=i+1;
+			if (lib.compareTo(".")!=0)
+			    r=(r==null)?(prefix+lib):(r+" "+prefix+lib);
+		    }
+		    i++;
+		}
+		if (r!=null) System.out.println(r);
+	    } else
+		System.out.println(System.getProperty(args[0]));
+	}
+    }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/tools/install-sh b/com.oracle.truffle.r.pkgs/rJava/jri/tools/install-sh
new file mode 100755
index 0000000000000000000000000000000000000000..377bb8687ffe16bfc79ea25c8667cabf72aaf2c2
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/tools/install-sh
@@ -0,0 +1,527 @@
+#!/bin/sh
+# install - install a program, script, or datafile
+
+scriptversion=2011-11-20.07; # UTC
+
+# This originates from X11R5 (mit/util/scripts/install.sh), which was
+# later released in X11R6 (xc/config/util/install.sh) with the
+# following copyright and license.
+#
+# Copyright (C) 1994 X Consortium
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to
+# deal in the Software without restriction, including without limitation the
+# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+# sell copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
+# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
+# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+# Except as contained in this notice, the name of the X Consortium shall not
+# be used in advertising or otherwise to promote the sale, use or other deal-
+# ings in this Software without prior written authorization from the X Consor-
+# tium.
+#
+#
+# FSF changes to this file are in the public domain.
+#
+# Calling this script install-sh is preferred over install.sh, to prevent
+# 'make' implicit rules from creating a file called install from it
+# when there is no Makefile.
+#
+# This script is compatible with the BSD install script, but was written
+# from scratch.
+
+nl='
+'
+IFS=" ""	$nl"
+
+# set DOITPROG to echo to test this script
+
+# Don't use :- since 4.3BSD and earlier shells don't like it.
+doit=${DOITPROG-}
+if test -z "$doit"; then
+  doit_exec=exec
+else
+  doit_exec=$doit
+fi
+
+# Put in absolute file names if you don't have them in your path;
+# or use environment vars.
+
+chgrpprog=${CHGRPPROG-chgrp}
+chmodprog=${CHMODPROG-chmod}
+chownprog=${CHOWNPROG-chown}
+cmpprog=${CMPPROG-cmp}
+cpprog=${CPPROG-cp}
+mkdirprog=${MKDIRPROG-mkdir}
+mvprog=${MVPROG-mv}
+rmprog=${RMPROG-rm}
+stripprog=${STRIPPROG-strip}
+
+posix_glob='?'
+initialize_posix_glob='
+  test "$posix_glob" != "?" || {
+    if (set -f) 2>/dev/null; then
+      posix_glob=
+    else
+      posix_glob=:
+    fi
+  }
+'
+
+posix_mkdir=
+
+# Desired mode of installed file.
+mode=0755
+
+chgrpcmd=
+chmodcmd=$chmodprog
+chowncmd=
+mvcmd=$mvprog
+rmcmd="$rmprog -f"
+stripcmd=
+
+src=
+dst=
+dir_arg=
+dst_arg=
+
+copy_on_change=false
+no_target_directory=
+
+usage="\
+Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
+   or: $0 [OPTION]... SRCFILES... DIRECTORY
+   or: $0 [OPTION]... -t DIRECTORY SRCFILES...
+   or: $0 [OPTION]... -d DIRECTORIES...
+
+In the 1st form, copy SRCFILE to DSTFILE.
+In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
+In the 4th, create DIRECTORIES.
+
+Options:
+     --help     display this help and exit.
+     --version  display version info and exit.
+
+  -c            (ignored)
+  -C            install only if different (preserve the last data modification time)
+  -d            create directories instead of installing files.
+  -g GROUP      $chgrpprog installed files to GROUP.
+  -m MODE       $chmodprog installed files to MODE.
+  -o USER       $chownprog installed files to USER.
+  -s            $stripprog installed files.
+  -t DIRECTORY  install into DIRECTORY.
+  -T            report an error if DSTFILE is a directory.
+
+Environment variables override the default commands:
+  CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
+  RMPROG STRIPPROG
+"
+
+while test $# -ne 0; do
+  case $1 in
+    -c) ;;
+
+    -C) copy_on_change=true;;
+
+    -d) dir_arg=true;;
+
+    -g) chgrpcmd="$chgrpprog $2"
+	shift;;
+
+    --help) echo "$usage"; exit $?;;
+
+    -m) mode=$2
+	case $mode in
+	  *' '* | *'	'* | *'
+'*	  | *'*'* | *'?'* | *'['*)
+	    echo "$0: invalid mode: $mode" >&2
+	    exit 1;;
+	esac
+	shift;;
+
+    -o) chowncmd="$chownprog $2"
+	shift;;
+
+    -s) stripcmd=$stripprog;;
+
+    -t) dst_arg=$2
+	# Protect names problematic for 'test' and other utilities.
+	case $dst_arg in
+	  -* | [=\(\)!]) dst_arg=./$dst_arg;;
+	esac
+	shift;;
+
+    -T) no_target_directory=true;;
+
+    --version) echo "$0 $scriptversion"; exit $?;;
+
+    --)	shift
+	break;;
+
+    -*)	echo "$0: invalid option: $1" >&2
+	exit 1;;
+
+    *)  break;;
+  esac
+  shift
+done
+
+if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
+  # When -d is used, all remaining arguments are directories to create.
+  # When -t is used, the destination is already specified.
+  # Otherwise, the last argument is the destination.  Remove it from $@.
+  for arg
+  do
+    if test -n "$dst_arg"; then
+      # $@ is not empty: it contains at least $arg.
+      set fnord "$@" "$dst_arg"
+      shift # fnord
+    fi
+    shift # arg
+    dst_arg=$arg
+    # Protect names problematic for 'test' and other utilities.
+    case $dst_arg in
+      -* | [=\(\)!]) dst_arg=./$dst_arg;;
+    esac
+  done
+fi
+
+if test $# -eq 0; then
+  if test -z "$dir_arg"; then
+    echo "$0: no input file specified." >&2
+    exit 1
+  fi
+  # It's OK to call 'install-sh -d' without argument.
+  # This can happen when creating conditional directories.
+  exit 0
+fi
+
+if test -z "$dir_arg"; then
+  do_exit='(exit $ret); exit $ret'
+  trap "ret=129; $do_exit" 1
+  trap "ret=130; $do_exit" 2
+  trap "ret=141; $do_exit" 13
+  trap "ret=143; $do_exit" 15
+
+  # Set umask so as not to create temps with too-generous modes.
+  # However, 'strip' requires both read and write access to temps.
+  case $mode in
+    # Optimize common cases.
+    *644) cp_umask=133;;
+    *755) cp_umask=22;;
+
+    *[0-7])
+      if test -z "$stripcmd"; then
+	u_plus_rw=
+      else
+	u_plus_rw='% 200'
+      fi
+      cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
+    *)
+      if test -z "$stripcmd"; then
+	u_plus_rw=
+      else
+	u_plus_rw=,u+rw
+      fi
+      cp_umask=$mode$u_plus_rw;;
+  esac
+fi
+
+for src
+do
+  # Protect names problematic for 'test' and other utilities.
+  case $src in
+    -* | [=\(\)!]) src=./$src;;
+  esac
+
+  if test -n "$dir_arg"; then
+    dst=$src
+    dstdir=$dst
+    test -d "$dstdir"
+    dstdir_status=$?
+  else
+
+    # Waiting for this to be detected by the "$cpprog $src $dsttmp" command
+    # might cause directories to be created, which would be especially bad
+    # if $src (and thus $dsttmp) contains '*'.
+    if test ! -f "$src" && test ! -d "$src"; then
+      echo "$0: $src does not exist." >&2
+      exit 1
+    fi
+
+    if test -z "$dst_arg"; then
+      echo "$0: no destination specified." >&2
+      exit 1
+    fi
+    dst=$dst_arg
+
+    # If destination is a directory, append the input filename; won't work
+    # if double slashes aren't ignored.
+    if test -d "$dst"; then
+      if test -n "$no_target_directory"; then
+	echo "$0: $dst_arg: Is a directory" >&2
+	exit 1
+      fi
+      dstdir=$dst
+      dst=$dstdir/`basename "$src"`
+      dstdir_status=0
+    else
+      # Prefer dirname, but fall back on a substitute if dirname fails.
+      dstdir=`
+	(dirname "$dst") 2>/dev/null ||
+	expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	     X"$dst" : 'X\(//\)[^/]' \| \
+	     X"$dst" : 'X\(//\)$' \| \
+	     X"$dst" : 'X\(/\)' \| . 2>/dev/null ||
+	echo X"$dst" |
+	    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+		   s//\1/
+		   q
+		 }
+		 /^X\(\/\/\)[^/].*/{
+		   s//\1/
+		   q
+		 }
+		 /^X\(\/\/\)$/{
+		   s//\1/
+		   q
+		 }
+		 /^X\(\/\).*/{
+		   s//\1/
+		   q
+		 }
+		 s/.*/./; q'
+      `
+
+      test -d "$dstdir"
+      dstdir_status=$?
+    fi
+  fi
+
+  obsolete_mkdir_used=false
+
+  if test $dstdir_status != 0; then
+    case $posix_mkdir in
+      '')
+	# Create intermediate dirs using mode 755 as modified by the umask.
+	# This is like FreeBSD 'install' as of 1997-10-28.
+	umask=`umask`
+	case $stripcmd.$umask in
+	  # Optimize common cases.
+	  *[2367][2367]) mkdir_umask=$umask;;
+	  .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
+
+	  *[0-7])
+	    mkdir_umask=`expr $umask + 22 \
+	      - $umask % 100 % 40 + $umask % 20 \
+	      - $umask % 10 % 4 + $umask % 2
+	    `;;
+	  *) mkdir_umask=$umask,go-w;;
+	esac
+
+	# With -d, create the new directory with the user-specified mode.
+	# Otherwise, rely on $mkdir_umask.
+	if test -n "$dir_arg"; then
+	  mkdir_mode=-m$mode
+	else
+	  mkdir_mode=
+	fi
+
+	posix_mkdir=false
+	case $umask in
+	  *[123567][0-7][0-7])
+	    # POSIX mkdir -p sets u+wx bits regardless of umask, which
+	    # is incompatible with FreeBSD 'install' when (umask & 300) != 0.
+	    ;;
+	  *)
+	    tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
+	    trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0
+
+	    if (umask $mkdir_umask &&
+		exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1
+	    then
+	      if test -z "$dir_arg" || {
+		   # Check for POSIX incompatibilities with -m.
+		   # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
+		   # other-writable bit of parent directory when it shouldn't.
+		   # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
+		   ls_ld_tmpdir=`ls -ld "$tmpdir"`
+		   case $ls_ld_tmpdir in
+		     d????-?r-*) different_mode=700;;
+		     d????-?--*) different_mode=755;;
+		     *) false;;
+		   esac &&
+		   $mkdirprog -m$different_mode -p -- "$tmpdir" && {
+		     ls_ld_tmpdir_1=`ls -ld "$tmpdir"`
+		     test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
+		   }
+		 }
+	      then posix_mkdir=:
+	      fi
+	      rmdir "$tmpdir/d" "$tmpdir"
+	    else
+	      # Remove any dirs left behind by ancient mkdir implementations.
+	      rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null
+	    fi
+	    trap '' 0;;
+	esac;;
+    esac
+
+    if
+      $posix_mkdir && (
+	umask $mkdir_umask &&
+	$doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
+      )
+    then :
+    else
+
+      # The umask is ridiculous, or mkdir does not conform to POSIX,
+      # or it failed possibly due to a race condition.  Create the
+      # directory the slow way, step by step, checking for races as we go.
+
+      case $dstdir in
+	/*) prefix='/';;
+	[-=\(\)!]*) prefix='./';;
+	*)  prefix='';;
+      esac
+
+      eval "$initialize_posix_glob"
+
+      oIFS=$IFS
+      IFS=/
+      $posix_glob set -f
+      set fnord $dstdir
+      shift
+      $posix_glob set +f
+      IFS=$oIFS
+
+      prefixes=
+
+      for d
+      do
+	test X"$d" = X && continue
+
+	prefix=$prefix$d
+	if test -d "$prefix"; then
+	  prefixes=
+	else
+	  if $posix_mkdir; then
+	    (umask=$mkdir_umask &&
+	     $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
+	    # Don't fail if two instances are running concurrently.
+	    test -d "$prefix" || exit 1
+	  else
+	    case $prefix in
+	      *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
+	      *) qprefix=$prefix;;
+	    esac
+	    prefixes="$prefixes '$qprefix'"
+	  fi
+	fi
+	prefix=$prefix/
+      done
+
+      if test -n "$prefixes"; then
+	# Don't fail if two instances are running concurrently.
+	(umask $mkdir_umask &&
+	 eval "\$doit_exec \$mkdirprog $prefixes") ||
+	  test -d "$dstdir" || exit 1
+	obsolete_mkdir_used=true
+      fi
+    fi
+  fi
+
+  if test -n "$dir_arg"; then
+    { test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
+    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
+    { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
+      test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
+  else
+
+    # Make a couple of temp file names in the proper directory.
+    dsttmp=$dstdir/_inst.$$_
+    rmtmp=$dstdir/_rm.$$_
+
+    # Trap to clean up those temp files at exit.
+    trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
+
+    # Copy the file name to the temp name.
+    (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&
+
+    # and set any options; do chmod last to preserve setuid bits.
+    #
+    # If any of these fail, we abort the whole thing.  If we want to
+    # ignore errors from any of these, just make sure not to ignore
+    # errors from the above "$doit $cpprog $src $dsttmp" command.
+    #
+    { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
+    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
+    { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
+    { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
+
+    # If -C, don't bother to copy if it wouldn't change the file.
+    if $copy_on_change &&
+       old=`LC_ALL=C ls -dlL "$dst"	2>/dev/null` &&
+       new=`LC_ALL=C ls -dlL "$dsttmp"	2>/dev/null` &&
+
+       eval "$initialize_posix_glob" &&
+       $posix_glob set -f &&
+       set X $old && old=:$2:$4:$5:$6 &&
+       set X $new && new=:$2:$4:$5:$6 &&
+       $posix_glob set +f &&
+
+       test "$old" = "$new" &&
+       $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
+    then
+      rm -f "$dsttmp"
+    else
+      # Rename the file to the real destination.
+      $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
+
+      # The rename failed, perhaps because mv can't rename something else
+      # to itself, or perhaps because mv is so ancient that it does not
+      # support -f.
+      {
+	# Now remove or move aside any old file at destination location.
+	# We try this two ways since rm can't unlink itself on some
+	# systems and the destination file might be busy for other
+	# reasons.  In this case, the final cleanup might fail but the new
+	# file should still install successfully.
+	{
+	  test ! -f "$dst" ||
+	  $doit $rmcmd -f "$dst" 2>/dev/null ||
+	  { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
+	    { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
+	  } ||
+	  { echo "$0: cannot unlink or rename $dst" >&2
+	    (exit 1); exit 1
+	  }
+	} &&
+
+	# Now rename the file to the real destination.
+	$doit $mvcmd "$dsttmp" "$dst"
+      }
+    fi || exit 1
+
+    trap '' 0
+  fi
+done
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-time-zone: "UTC"
+# time-stamp-end: "; # UTC"
+# End:
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/tools/mkinstalldirs b/com.oracle.truffle.r.pkgs/rJava/jri/tools/mkinstalldirs
new file mode 100755
index 0000000000000000000000000000000000000000..8ab885ec92d9e1ce51e4bca32745b24c2bf0a596
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/tools/mkinstalldirs
@@ -0,0 +1,99 @@
+#! /bin/sh
+# mkinstalldirs --- make directory hierarchy
+# Author: Noah Friedman <friedman@prep.ai.mit.edu>
+# Created: 1993-05-16
+# Public domain
+
+errstatus=0
+dirmode=""
+
+usage="\
+Usage: mkinstalldirs [-h] [--help] [-m mode] dir ..."
+
+# process command line arguments
+while test $# -gt 0 ; do
+   case "${1}" in
+     -h | --help | --h* )			# -h for help
+	echo "${usage}" 1>&2; exit 0 ;;
+     -m )					# -m PERM arg
+	shift
+	test $# -eq 0 && { echo "${usage}" 1>&2; exit 1; }
+	dirmode="${1}"
+	shift ;;
+     -- ) shift; break ;;			# stop option processing
+     -* ) echo "${usage}" 1>&2; exit 1 ;;	# unknown option
+     * )  break ;;				# first non-opt arg
+   esac
+done
+
+for file
+do
+  if test -d "$file"; then
+    shift
+  else
+    break
+  fi
+done
+
+case $# in
+0) exit 0 ;;
+esac
+
+case $dirmode in
+'')
+  if mkdir -p -- . 2>/dev/null; then
+    echo "mkdir -p -- $*"
+    exec mkdir -p -- "$@"
+  fi ;;
+*)
+  if mkdir -m "$dirmode" -p -- . 2>/dev/null; then
+    echo "mkdir -m $dirmode -p -- $*"
+    exec mkdir -m "$dirmode" -p -- "$@"
+  fi ;;
+esac
+
+for file
+do
+   set fnord `echo ":$file" | sed -ne 's/^:\//#/;s/^://;s/\// /g;s/^#/\//;p'`
+   shift
+
+   pathcomp=
+   for d
+   do
+     pathcomp="$pathcomp$d"
+     case "$pathcomp" in
+       -* ) pathcomp=./$pathcomp ;;
+     esac
+
+     if test ! -d "$pathcomp"; then
+	echo "mkdir $pathcomp"
+
+	mkdir "$pathcomp" || lasterr=$?
+
+	if test ! -d "$pathcomp"; then
+	  errstatus=$lasterr
+	else
+	  if test ! -z "$dirmode"; then
+	     echo "chmod $dirmode $pathcomp"
+
+	     lasterr=""
+	     chmod "$dirmode" "$pathcomp" || lasterr=$?
+
+	     if test ! -z "$lasterr"; then
+	       errstatus=$lasterr
+	     fi
+	  fi
+	fi
+     fi
+
+     pathcomp="$pathcomp/"
+   done
+done
+
+exit $errstatus
+
+# Local Variables:
+# mode: shell-script
+# sh-indentation: 3
+# End:
+# mkinstalldirs ends here
diff --git a/com.oracle.truffle.r.pkgs/rJava/jri/version b/com.oracle.truffle.r.pkgs/rJava/jri/version
new file mode 100755
index 0000000000000000000000000000000000000000..e0c3078265a9de3621edcbaf91a70b147e7014a2
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/jri/version
@@ -0,0 +1,8 @@
+#!/bin/sh
+
+VER=`awk -v ORS= '/JRI v/ { print substr($6,2) }' src/jri.h`
+if test "$1" == "-f"; then 
+    echo "JRI_${VER}.tar.gz"
+else
+    echo "${VER}"
+fi
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/Exceptions.Rd b/com.oracle.truffle.r.pkgs/rJava/man/Exceptions.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..e0907a2146f080b834e543fda365ea66d731de5f
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/Exceptions.Rd
@@ -0,0 +1,55 @@
+\name{Exceptions}
+\alias{Exceptions}
+\alias{$.Throwable}
+\alias{$<-.Throwable}
+\title{Exception handling}
+\description{R handling of java exception}
+\usage{
+	\S3method{$}{Throwable}(x, name )
+	\S3method{$}{Throwable}(x, name ) <- value
+}
+\arguments{
+	\item{x}{condition}
+	\item{name}{...}
+	\item{value}{...}
+}
+\details{
+	Java exceptions are mapped to R conditions that are relayed by the
+	\code{\link{stop}} function. 
+	
+	The R condition contains the actual exception object as the 
+	\code{jobj} item.
+	
+	The class name of the R condition is made of a vector 
+	of simple java class names, the class names without their package
+	path. This allows the R code to use direct handlers similar to 
+	direct exception handlers in java. See the example below. 
+}
+\examples{
+\dontshow{.jinit()}
+
+Integer <- J("java.lang.Integer")
+tryCatch( Integer$parseInt( "10.." ), NumberFormatException = function(e){
+	e$jobj$printStackTrace() 
+} )
+
+# the dollar method is also implemented for Throwable conditions, 
+# so that syntactic sugar can be used on condition objects
+# however, in the example below e is __not__ a jobjRef object reference
+tryCatch( Integer$parseInt( "10.." ), NumberFormatException = function(e){
+	e$printStackTrace() 
+} )
+
+
+\dontshow{
+tryCatch( Integer$parseInt( "10.." ), NumberFormatException = function(e){
+	classes <- class( e )
+	stopifnot( "NumberFormatException" \%in\% classes )
+	stopifnot( "Exception" \%in\% classes )
+	stopifnot( "Object" \%in\% classes )
+	stopifnot( "error" \%in\% classes )
+	stopifnot( "condition" \%in\% classes )
+} )
+}
+
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/J.Rd b/com.oracle.truffle.r.pkgs/rJava/man/J.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..fa5a3e2b16bc100f19d107089996323c85277161
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/J.Rd
@@ -0,0 +1,76 @@
+\name{J}
+\alias{J}
+\title{
+High level API for accessing Java
+}
+\description{
+\code{J} creates a Java class reference or calls a Java method
+}
+\usage{
+J(class, method, ...)
+}
+\arguments{
+  \item{class}{
+    java object reference or fully qualified class name in JNI
+    notation (e.g "java/lang/String" ) or standard java notation (e.g
+    "java.lang.String")
+  }
+  \item{method}{
+    if present then \code{J} results in a method call, otherwise it
+    just creates a class name reference.
+  }
+  \item{\dots}{
+    optional parameters that will be passed to the method (if the
+    \code{method} argument is present)
+  }
+}
+\details{
+\code{J} is the high-level access to Java.
+
+If the \code{method} argument is missing then \code{code} must be a
+class name and \code{J} creates a class name reference that can be
+used either in a call to \code{new} to create a new Java object
+(e.g. \code{new(J("java.lang.String"), "foo")}) or with \code{$}
+operator to call a static method
+(e.g. \code{J("java.lang.Double")$parseDouble("10.2")}.)
+
+If the \code{method} argument is present then it must be a string
+vector of length one which defines the method to be called on the
+object.
+}
+\value{
+  If \code{method} is missing the the returned value is an object of
+  the class \code{jclassName}. Otherwise the value is the result of
+  the method invocation. In the latter case Java exceptions may be
+  thrown and the function doesn't return.
+}
+\note{
+\code{J} is a high-level API which is slower than \code{\link{.jnew}}
+or \code{\link{.jcall}} since it has to use reflection to find the
+most suitable method.
+}
+\seealso{
+\code{\link{.jcall}}, \code{\link{.jnew}}
+}
+\examples{
+\dontshow{.jinit()}
+
+if (!nzchar(Sys.getenv("NOAWT"))) {
+  f <- new(J("java.awt.Frame"), "Hello")
+  f$setVisible(TRUE)
+}
+
+J("java.lang.Double")$parseDouble("10.2")
+J("java.lang.Double", "parseDouble", "10.2" )
+
+Double <- J("java.lang.Double")
+Double$parseDouble( "10.2")
+
+# String[] strings = new String[]{ "string", "array" } ;
+  strings <- .jarray( c("string", "array") )
+# this uses the JList( Object[] ) constructor 
+# even though the "strings" parameter is a String[] 
+  l <- new( J("javax.swing.JList"), strings)
+
+}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/accessOp.Rd b/com.oracle.truffle.r.pkgs/rJava/man/accessOp.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..a51155d8c857dab587a9321b0825cb8319dbd47a
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/accessOp.Rd
@@ -0,0 +1,83 @@
+\name{JavaAccess}
+\alias{$,jobjRef-method}
+\alias{$,jclassName-method}
+\alias{$<-,jobjRef-method}
+\alias{$<-,jclassName-method}
+\alias{names,jobjRef-method}
+\alias{names,jclassName-method}
+\alias{names,jarrayRef-method}
+\alias{names,jrectRef-method}
+\alias{.DollarNames.jobjRef}
+\alias{.DollarNames.jclassName}
+\alias{.DollarNames.jarrayRef}
+\alias{.DollarNames.jrectRef}
+
+\title{
+  Field/method operator for Java objects
+}
+\description{
+  The \code{$} operator for \code{jobjRef} Java object references provides convenience access to object attributes and calling Java methods.
+}
+\usage{
+	\S3method{.DollarNames}{jobjRef}   (x, pattern = "" )
+	\S3method{.DollarNames}{jarrayRef} (x, pattern = "" )
+	\S3method{.DollarNames}{jrectRef}  (x, pattern = "" )
+	\S3method{.DollarNames}{jclassName}(x, pattern = "" )
+}
+\arguments{
+	\item{x}{object to complete}
+	\item{pattern}{pattern}
+}
+\section{Methods}{
+  \describe{
+    \item{\code{$}}{\code{signature(x = "jobjRef")}: ... }
+    \item{\code{$}}{\code{signature(x = "jclassName")}: ... }
+    \item{\code{$<-}}{\code{signature(x = "jobjRef")}: ... }
+    \item{\code{$<-}}{\code{signature(x = "jclassName")}: ... }
+    \item{\code{names}}{\code{signature(x = "jobjRef")}: ... }
+    \item{\code{names}}{\code{signature(x = "jarrayRef")}: ... }
+    \item{\code{names}}{\code{signature(x = "jrectRef")}: ... }
+    \item{\code{names}}{\code{signature(x = "jclassName")}: ... }
+	 }
+}
+\details{
+  rJava provies two levels of API: low-level JNI-API in the form of \code{\link{.jcall}} function and high-level reflection API based on the \code{$} operator. The former is very fast, but inflexible. The latter is a convenient way to use Java-like programming at the cost of performance. The reflection API is build around the \code{$} operator on \code{\link{jobjRef-class}} objects that allows to access Java attributes and call object methods.
+
+ \code{$} returns either the value of the attribute or calls a method, depending on which name matches first.
+
+ \code{$<-} assigns a value to the corresponding Java attribute.
+
+ \code{names} and \code{.DollarNames} returns all fields and methods associated with the object. 
+ Method names are followed by \code{(} or \code{()} depending on arity. 
+ This use of names is mainly useful for code completion, it is not intended to be used programmatically.
+
+ This is just a convenience API. Internally all calls are mapped into \code{\link{.jcall}} calls, therefore the calling conventions and returning objects use the same rules. For time-critical Java calls \code{\link{.jcall}} should be used directly.
+}
+\seealso{
+  \code{\link{J}}, \code{\link{.jcall}}, \code{\link{.jnew}}, \code{\link{jobjRef-class}}
+}
+\examples{
+\dontshow{.jinit()}
+
+v <- new(J("java.lang.String"), "Hello World!")
+v$length()
+v$indexOf("World")
+names(v)
+
+\dontshow{
+stopifnot( v$length() == 12L )
+stopifnot( v$indexOf("World") == 6L ) 
+}
+
+J("java.lang.String")$valueOf(10)
+
+Double <- J("java.lang.Double")
+# the class pseudo field - instance of Class for the associated class
+# similar to java Double.class
+Double$class 
+\dontshow{
+	stopifnot( Double$class$getName() == "java.lang.Double" )
+}
+
+}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/aslist.Rd b/com.oracle.truffle.r.pkgs/rJava/man/aslist.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..a23e34e4abf2fba7c3136f5d3bdf3d1c4145dad2
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/aslist.Rd
@@ -0,0 +1,59 @@
+\name{aslist}
+\alias{as.list.jobjRef}
+\alias{as.list.jarrayRef}
+\alias{as.list.jrectRef}
+\title{
+Converts java objects or arrays to R lists
+}
+\description{
+	\code{as.list} is implemented for java objects and java arrays
+	to facilitate using \code{lapply} calls over elements of a java array
+	or items of an Iterator associated with an Iterable object
+	
+	For java array references, \code{as.list} is mapped to
+	\code{\link{.jevalArray}}
+	
+	For java objects that implement the Iterable interface, 
+	the list is created by iterating over the associated iterator
+}
+\usage{
+\S3method{as.list}{jobjRef}(x, ...)
+\S3method{as.list}{jarrayRef}(x, ...)
+}
+\arguments{
+  \item{x}{java array or Iterable java object}
+  \item{\dots}{ignored}
+}
+\value{
+An R list, or vector.
+}
+\note{
+The function is not intended to be called directly. It is implemented
+so that java arrays or Iterable java objects can be used as the first 
+argument of \code{\link{lapply}}
+}
+\seealso{
+	\code{\link{.jevalArray}}, \code{\link{lapply}}
+}
+\examples{
+\dontshow{.jinit()}
+  # lapplying over a java array
+  a <- .jarray( list( 
+	.jnew( "java/awt/Point", 10L, 10L ), 
+	.jnew( "java/awt/Point", 30L, 30L )
+  ) )
+  lapply( a, function(point){ 
+	with(point, { 
+		(x + y ) ^ 2
+	} )
+  } )
+
+# lapply over a Vector (implements Iterable)
+v <- .jnew("java/util/Vector")
+v$add( "foo" )
+v$add( .jnew("java/lang/Double", 10.2 ) )
+sapply( v, function(item) item$getClass()$getName() )
+
+}
+\keyword{ programming }
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/clone.Rd b/com.oracle.truffle.r.pkgs/rJava/man/clone.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..5a43481617fee868da07054f5921b2d276b9c0b6
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/clone.Rd
@@ -0,0 +1,51 @@
+\name{clone}
+\alias{clone}
+\alias{clone,jobjRef-method}
+\alias{clone,jarrayRef-method}
+\alias{clone,jrectRef-method}
+
+\title{
+Object cloner
+}
+\description{
+Generic function to clone objects
+}
+\usage{
+clone(x, ...)
+}
+\section{Methods}{
+  \describe{
+    \item{clone}{\code{signature(x = "jobjRef")}: clone a java object reference (must implement Cloneable) }
+    \item{clone}{\code{signature(x = "jarrayRef")}: clone a java rugged array (not yet implemented) }
+    \item{clone}{\code{signature(x = "jrectRef")}: clone a java rectangular array (not yet implemented) }
+  }
+}
+
+\arguments{
+  \item{x}{An object to clone}
+  \item{\dots}{Further arguments, ignored}
+}
+\value{
+A clone of the object
+}
+\section{Warning}{
+	The implementation of clone for java object references uses
+	the clone method of the Object class. The reading of its description
+	in the java help page is \emph{strongly} recommended. 
+}
+
+\examples{
+\dontshow{.jinit()}
+
+  p1 <- .jnew("java/awt/Point" )
+  p2 <- clone( p1 )
+  p2$move( 10L, 10L )
+  p1$getX() 
+
+  # check that p1 and p2 are not references to the same java object
+  stopifnot( p1$getX() == 0 )
+  stopifnot( p2$getX() == 10 )
+
+}
+\keyword{ programming }
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/instanceof.Rd b/com.oracle.truffle.r.pkgs/rJava/man/instanceof.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..39fd12efa70e2f84abd0e65ff58b1997848bfa91
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/instanceof.Rd
@@ -0,0 +1,61 @@
+\name{.jinstanceof}
+\Rdversion{1.1}
+\alias{\%instanceof\%}
+\alias{.jinstanceof}
+\title{
+Is a java object an instance of a given java class
+}
+\description{
+Is a java object an instance of a given java class
+}
+\usage{
+o \%instanceof\% cl
+.jinstanceof( o, cl )
+}
+\arguments{
+  \item{o}{java object reference}
+  \item{cl}{java class. This can be a character vector of length one
+  giving the name of the class, or another java object, or an instance
+  of the Class class, or a object of class \code{jclassName}.}
+}
+\value{
+TRUE if o is an instance of cl
+}
+\author{
+Romain Francois <francoisromain@free.fr>
+}
+\examples{
+\dontshow{
+.jinit()
+}
+Double <- J("java.lang.Double")
+d <- new( Double, "10.2" )
+
+# character
+d \%instanceof\% "java.lang.Double"
+d \%instanceof\% "java.lang.Number"
+
+# jclassName
+d \%instanceof\% Double
+
+# instance of Class
+Double.class <- Double@jobj
+d \%instanceof\% Double.class
+
+# other object
+other.double <- new( Double, 10.2 )
+d \%instanceof\% other.double
+
+\dontshow{
+% simple unit tests
+stopifnot( d \%instanceof\% "java.lang.Double" )
+stopifnot( d \%instanceof\% "java.lang.Number" )
+stopifnot( d \%instanceof\% "java.lang.Object" )
+stopifnot( d \%instanceof\% Double.class )
+stopifnot( d \%instanceof\% other.double )
+stopifnot( d \%instanceof\% Double )
+}
+
+}
+\keyword{ interface }
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jarray.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jarray.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..ac531b4930fc19bb02eca57713534738b50bf6a1
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jarray.Rd
@@ -0,0 +1,100 @@
+\name{jarray}
+\alias{.jarray}
+\alias{.jevalArray}
+\title{
+  Java array handling functions
+}
+\description{
+  \code{.jarray} takes a vector (or a list of Java references) as its
+  argument, creates a Java array containing the elements of the vector
+  (or list) and returns a reference to such newly created array.
+
+  \code{.jevalArray} takes a reference to a Java array and returns its
+  contents (if possible).
+}
+\usage{
+.jarray(x, contents.class = NULL, dispatch = FALSE)
+.jevalArray(obj, rawJNIRefSignature = NULL, silent = FALSE, simplify = FALSE)
+}
+\arguments{
+  \item{x}{vector or a list of Java references}
+  \item{contents.class}{common class of the contained objects, see
+    details}
+  \item{obj}{Java object reference to an array that is to be evaluated}
+  \item{rawJNIRefSignature}{JNI signature that whould be used for
+    conversion. If set to \code{NULL}, the signature is detected
+    automatically.}
+  \item{silent}{if set to true, warnings are suppressed}
+  \item{dispatch}{logical. If \code{TRUE} the code attemps to dispatch
+  to either a \code{jarrayRef} object for rugged arrays and
+  \code{jrectRef} objects for rectangular arrays, creating possibly a
+  multi-dimensional object in Java (e.g., when used with a matrix).}
+  \item{simplify}{if set to \code{TRUE} more than two-dimensional arrays
+  are converted to native obejcts (e.g., matrices) if their type and
+  size matches (essentially the inverse for objects created with
+  \code{dispatch=TRUE}).}
+}
+\value{
+  \code{.jarray} returns a Java array reference (\code{jarrayRef} or \code{jrectRef}) to an
+  array created with the supplied contents.
+
+  \code{.jevalArray} returns the contents of the array object.
+}
+\details{
+  \code{.jarray}: The input can be either a vector of some sort (such as
+  numeric, integer, logical, ...) or a list of Java references. The
+  contents is pushed to the Java side and a corresponding array is
+  created. The type of the array depends on the input vector type. For
+  example numeric vector creates \code{double[]} array, integer vector
+  creates \code{int[]} array, character vector \code{String[]} array and
+  so on. If \code{x} is a list, it must contain Java references only (or
+  \code{NULL}s which will be treated as \code{NULL} references).
+
+  The \code{contents.class} parameter is used only if \code{x} is a list
+  of Java object references and it can specify the class that will be
+  used for all objects in the array. If set to \code{NULL} no assumption
+  is made and \code{java/lang/Object} will be used. Use with care and
+  only if you know what you're doing - you can always use
+  \code{\link{.jcast}} to cast the entire array to another type even if
+  you use a more general object type. One typical use is to construct
+  multi-dimensional arrays which mandates passing the array type as
+  \code{contents.class}.
+
+  The result is a reference to the newly created array.
+
+  The inverse function which fetches the elements of an array reference
+  is \code{.jevalArray}.
+
+  \code{.jevalArray} currently supports only a subset of all possible
+  array types. Recursive arrays are handled by returning a list of
+  references which can then be evaluated separately. The only exception
+  is \code{simplify=TRUE} in which case \code{.jevalArray} arrempts to
+  convert multi-dimensional arrays into native R type if there is a
+  such. This only works for rectangular arrays of the same basic type
+  (i.e. the length and type of each referenced array is the same -
+  sometimes matrices are represented that way in Java).
+}
+\examples{
+\dontshow{.jinit()}
+a <- .jarray(1:10)
+print(a)
+.jevalArray(a)
+b <- .jarray(c("hello","world"))
+print(b)
+c <- .jarray(list(a,b))
+print(c)
+# simple .jevalArray will return a list of references
+print(l <- .jevalArray(c))
+# to convert it back, use lapply
+lapply(l, .jevalArray)
+
+# two-dimensional array resulting in int[2][10]
+d <- .jarray(list(a,a),"[I")
+print(d)
+# use dispatch to convert a matrix to [[D
+e <- .jarray(matrix(1:12/2, 3), dispatch=TRUE)
+print(e)
+# simplify it back to a matrix
+.jevalArray(e, simplify=TRUE)
+}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jarrayRef-class.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jarrayRef-class.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..e39e4d5917f0ffff8687af7d2f5d1d566ea31263
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jarrayRef-class.Rd
@@ -0,0 +1,65 @@
+\name{jarrayRef-class}
+\docType{class}
+\alias{jarrayRef-class}
+\alias{[,jarrayRef-method}
+\alias{[[,jarrayRef-method}
+\alias{[[<-,jarrayRef-method}
+\alias{head,jarrayRef-method}
+\alias{tail,jarrayRef-method}
+\alias{length,jarrayRef-method}
+\alias{str,jarrayRef-method}
+\alias{unique,jarrayRef-method}
+\alias{duplicated,jarrayRef-method}
+\alias{anyDuplicated,jarrayRef-method}
+\alias{sort,jarrayRef-method}
+\alias{rev,jarrayRef-method}
+\alias{min,jarrayRef-method}
+\alias{max,jarrayRef-method}
+\alias{range,jarrayRef-method}
+
+\title{Class "jarrayRef" Reference to an array Java object }
+\description{ This class is a subclass of \link{jobjRef-class} 
+and represents a reference to an array Java object. }
+\section{Objects from the Class}{
+Objects cannot be created directly, but only as the return
+value of \code{\link{.jcall}} function.
+}
+\section{Slots}{
+  \describe{
+    \item{\code{jsig}:}{JNI signature of the array type}
+    \item{\code{jobj}:}{Internal identifier of the object}
+    \item{\code{jclass}:}{Inherited from \code{jobjRef}, but unspecified}
+  }
+}
+\section{Methods}{
+  \describe{
+  	  \item{[}{\code{signature(x = "jarrayRef")}: \emph{not yet implemented} }
+    \item{[[}{\code{signature(x = "jarrayRef")}: R indexing of java arrays }
+    \item{[[<-}{\code{signature(x = "jarrayRef")}: replacement method }
+    \item{\code{head}}{\code{signature(x = "jarrayRef")}: head of the java array }
+    \item{\code{tail}}{\code{signature(x = "jarrayRef")}: tail of the java array }
+    \item{length}{\code{signature(object = "jarrayRef")}: Number of java objects in the java array }
+    \item{str}{\code{signature(object = "jarrayRef")}: ... }
+    \item{unique}{\code{signature(x = "jarrayRef")}: \emph{not yet implemented} }
+    \item{duplicated}{\code{signature(x = "jarrayRef")}: \emph{not yet implemented} }
+    \item{anyDuplicated}{\code{signature(x = "jarrayRef")}: \emph{not yet implemented} }
+    \item{sort}{\code{signature(x = "jarrayRef")}: \emph{not yet implemented} }
+    \item{rev}{\code{signature(x = "jarrayRef")}: \emph{not yet implemented} }
+    \item{min}{\code{signature(x = "jarrayRef")}: \emph{not yet implemented} }
+    \item{max}{\code{signature(x = "jarrayRef")}: \emph{not yet implemented} }
+    \item{range}{\code{signature(x = "jarrayRef")}: \emph{not yet implemented} }
+  }
+}
+\section{Extends}{
+Class \code{"\linkS4class{jobjRef}"}, directly.
+}
+\author{ Simon Urbanek }
+\seealso{
+  \code{\link{.jcall}} or \code{\linkS4class{jobjRef}}
+  \code{\linkS4class{jrectRef}} for rectangular arrays
+}
+% need to find examples of rugged arrays
+% \examples{
+% \dontshow{.jinit()}
+% }
+\keyword{classes}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/java-tools.Rd b/com.oracle.truffle.r.pkgs/rJava/man/java-tools.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..925c883c03ede1f7c4337420209c4a7c41d62c58
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/java-tools.Rd
@@ -0,0 +1,22 @@
+\name{java-tools}
+\alias{java-tools}
+\title{java tools used internally in rJava}
+\description{java tools used internally in rJava}
+\examples{
+\dontshow{
+# running the java unit tests from the R examples
+.jinit()
+J("RJavaTools_Test")$runtests()
+J("RJavaArrayTools_Test")$runtests()
+J("ArrayWrapper_Test")$runtests()
+J("RectangularArrayBuilder_Test")$runtests()
+
+
+  p <- .jnew( "java/awt/Point" )
+  classes <- .Call( "RgetSimpleClassNames", p@jobj, TRUE, PACKAGE = "rJava" )
+  stopifnot( all( c( "Point", "Point2D", "Object", "error", "condition" ) \%in\% classes ) )
+  classes <- .Call( "RgetSimpleClassNames", p@jobj, FALSE, PACKAGE = "rJava" )
+  stopifnot( all( c( "Point", "Point2D", "Object" )  \%in\% classes ) )
+
+}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/javaImport.Rd b/com.oracle.truffle.r.pkgs/rJava/man/javaImport.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..cdee86972a7771499e17cf1749d35c3b616c2027
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/javaImport.Rd
@@ -0,0 +1,56 @@
+\name{javaImport}
+\alias{javaImport}
+\title{
+Attach mechanism for java packages
+}
+\description{
+The \code{javaImport} function creates an item on R's
+search that maps names to class names references found in 
+one or several "imported" java packages.
+}
+\usage{
+javaImport(packages = "java.lang")
+}
+\arguments{
+  \item{packages}{character vector containing java package paths}
+}
+\value{
+An external pointer to a java specific \code{UserDefinedDatabase} object
+}
+\references{
+	\emph{User-Defined Tables in the R Search Path}. Duncan Temple Lang. December 4, 2001
+	\url{http://www.omegahat.org/RObjectTables/}
+}
+\author{
+Romain Francois <francoisromain@free.fr>
+}
+\note{
+Currently the list of objects in the imported package is populated
+as new objects are found, \emph{not} at creation time.
+}
+\section{Warning}{
+This feature is experimental. Use with caution, and don't forget to
+detach.
+}
+\seealso{
+\code{\link{attach}}
+}
+\examples{
+\dontrun{
+	attach( javaImport( "java.util" ), pos = 2 , name = "java:java.util" )
+	
+	# now we can just do something like this 
+	v <- new( Vector )
+	v$add( "foobar" )
+	ls( pos = 2 )
+	
+	# or this
+	m <- new( HashMap )
+	m$put( "foo", "bar" )
+	ls( pos = 2 )
+	
+	# or even this :
+	Collections$EMPTY_MAP
+}
+}
+\keyword{ programming }
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jcall.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jcall.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..b8e801b97c8f25eceb1799f6dac1a96624ef2cfc
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jcall.Rd
@@ -0,0 +1,110 @@
+\name{jcall}
+\alias{.jcall}
+\title{
+  Call a Java method
+}
+\description{
+  \code{.jcall} calls a Java method with the supplied arguments.
+}
+\usage{
+.jcall(obj, returnSig = "V", method, ..., evalArray = TRUE, 
+    evalString = TRUE, check = TRUE, interface = "RcallMethod", 
+    simplify = FALSE, use.true.class = FALSE)
+}
+\arguments{
+  \item{obj}{Java object (\code{jobjRef} as returned by
+    \code{\link{.jcall}} or \code{\link{.jnew}}) or fully qualified
+    class name in JNI notation (e.g. \code{"java/lang/String"}).}
+  \item{returnSig}{Return signature in JNI notation (e.g. "V" for void,
+    "[I" for \code{int[]} etc.). For convenience additional type
+    \code{"S"} is supported and expanded to
+    \code{"Ljava/lang/String;"}, re-mapping \code{"T"} to represent the
+    type \code{short}.}
+  \item{method}{The name of the method to be called}
+  \item{...}{
+    Any parametes that will be passed to the Java method. The parameter
+    types are determined automatically and/or taken from the
+    \code{jobjRef} object. All named parameters are discarded.}
+  \item{evalArray}{This flag determines whether the array return value
+    is evaluated (\code{TRUE}) or passed back as Java object reference
+    (\code{FALSE}).}
+  \item{simplify}{If \code{evalArray} is \code{TRUE} then this argument
+    is passed to \code{\link{.jevalArray}()}.}
+  \item{evalString}{This flag determines whether string result is returned
+    as characters or as Java object reference.}
+  \item{check}{If set to \code{TRUE} then checks for exceptions are
+    performed before and after the call using
+    \code{\link{.jcheck}(silent=FALSE)}. This is usually the desired
+    behavior, because all calls fail until an expection is cleared.}
+  \item{interface}{This option is experimental and specifies the
+    interface used for calling the Java method; the current
+    implementation supports two interfaces:
+    \itemize{
+      \item{\code{"RcallMethod"}}{the default interface.}
+      \item{\code{"RcallSyncMethod"}}{synchronized call of a
+	method. This has simmilar effect as using \code{synchronize} in
+	Java.}
+    }
+  }
+  \item{use.true.class}{logical. If set to \code{TRUE}, the true class
+  of the returned object will be used instead of the declared signature. 
+  \code{TRUE} allows for example to grab the actual class of an object when 
+  the return type is an interface, or allows to grab an array when the 
+  declared type is Object and the returned object is an array. Use \code{FALSE} 
+  for efficiency when you are sure about the return type. }
+}
+\value{
+  Returns the result of the method.
+}
+\details{
+  \code{.jcall} requires exact match of argument and return types. For
+  higher efficiency \code{.jcall} doesn't perform any lookup in the
+  reflection tables. This means that passing subclasses of the classes
+  present in the method definition requires explicit casting using
+  \code{\link{.jcast}}. Passing \code{null} arguments also needs a
+  proper class specification with \code{\link{.jnull}}.
+
+  Java types \code{long} and \code{float} have no corresponding types in
+  R and therefore any such parameters must be flagged as such using
+  \code{\link{.jfloat}} and \code{\link{.jlong}} functions respectively.
+
+  Java also distinguishes scalar and array types whereas R doesn't have
+  the concept of a scalar. In R a scalar is basically a vector (called
+  array in Java-speak) of the length 1. Therefore passing vectors of the
+  length 1 is ambiguous. \code{.jcall} assumes that any vector of the
+  length 1 that corresponds to a native Java type is a scalar. All other
+  vectors are passed as arrays. Therefore it is important to use
+  \code{\link{.jarray}} if an arbitrary vector (including those of the
+  length 1) is to be passed as an array parameter.
+
+  \emph{Important note about encoding of character vectors:}
+  Java interface always works with strings in UTF-8 encoding, therefore
+  the safest way is to run R in a UTF-8 locale. If that is not
+  possible for some reason, rJava can be used in non-UTF-8 locales,
+  but care must be taken. Since R 2.7.0 it is possible to associate
+  encoding with strings and rJava will flag all strings it produces
+  with the appropriate UTF-8 tag. R will then perform corresponding
+  appropriate conversions where possible (at a cost of speed and
+  memory usage), but 3rd party code may not (e.g. older
+  packages). Also rJava relies on correct encoding flags for strings
+  passed to it and will attempt to perform conversions where
+  necessary. If some 3rd party code produces strings incorreclty
+  flagged, all bets are off.
+
+  Finally, for performance reasons class, method and field names as
+  well as signatures are not always converted and should not contain
+  non-ASCII characters.
+}
+\seealso{
+  \code{\link{.jnew}}, \code{\link{.jcast}}, \code{\link{.jnull}},
+  \code{\link{.jarray}}
+}
+\examples{
+\dontshow{.jinit()}
+.jcall("java/lang/System","S","getProperty","os.name")
+if (!nzchar(Sys.getenv("NOAWT"))) {
+  f <- .jnew("java/awt/Frame","Hello")
+  .jcall(f,,"setVisible",TRUE)
+}
+}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jcast.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jcast.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..513038061931fb887f0688e2fa01bc0e69a52b10
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jcast.Rd
@@ -0,0 +1,45 @@
+\name{jcast}
+\alias{.jcast}
+\title{
+  Cast a Java object to another class
+}
+\description{
+  \code{.jcast} returns a Java object reference cast to another Java class.
+}
+\usage{
+.jcast(obj, new.class = "java/lang/Object", check = FALSE, convert.array = FALSE)
+}
+\arguments{
+  \item{obj}{a Java object reference}
+  \item{new.class}{fully qualified class name in JNI notation
+    (e.g. \code{"java/lang/String"}). }
+  \item{check}{logical. If \code{TRUE}, it is checked that the object 
+effectively is an instance of the new class. See \code{\link{\%instanceof\%}}.
+Using FALSE (the default) for this argument, rJava does not perform type check and this 
+will cause an error on the first use if the cast is illegal.}
+\item{convert.array}{logical. If \code{TRUE} and the object is an array, 
+it is converted into a \code{jarrayRef} reference. }
+}
+\value{
+  Returns a Java object reference (\code{jobjRef}) to the object
+  \code{obj}, changing the object class.
+}
+\details{
+  This function is necessary if a argument of \code{\link{.jcall}} or
+  \code{\link{.jnew}} is defined as the superclass of the object to be
+  passed (see \code{\link{.jcall}}). The original object is not modified.
+  
+  The default values for the arguments \code{check} and \code{convert.array}
+  is \code{FALSE} in order to guarantee backwards compatibility, 
+  but it is recommended to set the arguments to \code{TRUE}
+}
+\seealso{
+  \code{\link{.jcall}}
+}
+\examples{
+\dontrun{
+v <- .jnew("java/util/Vector")
+.jcall("java/lang/System","I","identityHashCode",.jcast(v, "java/lang/Object"))
+}
+}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jcastToArray.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jcastToArray.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..d3543bddd7ae071b9a0ad05e3124a223cb0a70e7
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jcastToArray.Rd
@@ -0,0 +1,69 @@
+\name{jcastToArray}
+\alias{.jcastToArray}
+\title{
+  Ensures that a given object is an array reference
+}
+\description{
+  \code{.jcastToArray} takes a Java object reference of any kind and
+  returns Java array reference if the given object is a reference to an
+  array.
+}
+\usage{
+.jcastToArray(obj, signature=NULL, class="", quiet=FALSE)
+}
+\arguments{
+  \item{obj}{Java object reference to cast or a scalar vector}
+  \item{signature}{array signature in JNI notation (e.g. \code{"[I"} for
+    an array of integers). If set to \code{NULL} (the default),
+    the signature is automatically determined from the object's class.}
+  \item{class}{force the result to pose as a particular Java
+    class. This has the same effect as using \code{\link{.jcast}} on the
+    result and is provided for convenience only.}
+  \item{quiet}{if set to \code{TRUE}, no failures are reported and the
+    original object is returned unmodified.}
+}
+\value{
+  Returns a Java array reference (\code{jarrayRef}) on success. If
+  \code{quiet} is \code{TRUE} then the result can also be the original
+  object in the case of failure.
+}
+\details{
+  Sometimes a result of a method is by definition of the class
+  \code{java.lang.Object}, but the acutal referenced object may be an
+  array. In that case the method returns a Java object reference instead
+  of an array reference. In order to obtain an array reference, it is
+  necessary to cast such an object to an array reference - this is done
+  using the above \code{.jcastToArray} function.
+
+  The input is an object reference that points to an array. Ususally the
+  signature should be left at \code{NULL} such that it is determined
+  from the object's class. This is also a check, because if the object's
+  class is not an array, then the functions fails either with an error
+  (when \code{quiet=FALSE}) or by returing the original object (when
+  \code{quiet=TRUE}). If the signature is set to anything else, it is
+  not verified and the array reference is always created, even if it may
+  be invalid and unusable.
+
+  For convenience \code{.jcastToArray} also accepts non-references in
+  which case it simply calls \code{\link{.jarray}}, ignoring all other
+  parameters.
+}
+\examples{
+\dontrun{
+a <- .jarray(1:10)
+print(a)
+# let's create an array containing the array
+aa <- .jarray(list(a))
+print(aa)
+ba <- .jevalArray(aa)[[1]]
+# it is NOT the inverse, because .jarray works on a list of objects
+print(ba)
+# so we need to cast the object into an array
+b <- .jcastToArray(ba)
+# only now a and b are the same array reference
+print(b)
+# for convenience .jcastToArray behaves like .jarray for non-references
+print(.jcastToArray(1:10/2))
+}
+}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jcheck.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jcheck.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..d9f6efcaf38bf050f1c24a73925d75a0d00ae550
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jcheck.Rd
@@ -0,0 +1,96 @@
+\name{jcheck}
+\alias{.jcheck}
+\alias{.jthrow}
+\alias{.jclear}
+\alias{.jgetEx}
+\title{
+  Java exception handling
+}
+\description{
+  \code{.jcheck} checks the Java VM for any pending exceptions and
+  clears them.
+
+  \code{.jthrow} throws a Java exception.
+
+  \code{.jgetEx} polls for any pending expections and returns the exception object.
+
+  \code{.jclear} clears a pending exception.
+}
+\usage{
+.jcheck(silent = FALSE)
+
+.jthrow(exception, message = NULL)
+.jgetEx(clear = FALSE)
+.jclear()
+}
+\arguments{
+  \item{silent}{If set to \code{FALSE} then Java is instructed to print
+    the exception on \code{stderr}. Note that Windows Rgui doesn't show
+    \code{stderr} so it will not appear there (as of rJava 0.5-1 some
+    errors that the JVM prints using the vfprintf callback are passed
+    to R. However, some parts are printed using \code{System.err} in
+    which case the ususal redirection using the \code{System} class
+    can be used by the user).}
+  \item{exception}{is either a class name of an exception to create or a
+    throwable object reference that is to be thrown.}
+  \item{message}{if \code{exception} is a class name then this parameter
+    specifies the string to be used as the message of the exception. This
+    parameter is ignored if \code{exception} is a reference.}
+  \item{clear}{if set to \code{TRUE} then the returned exception is also
+  cleared, otherwise the throwable is returned without clearing the
+  cause.}
+}
+\value{
+  \code{.jcheck} returns \code{TRUE} if an exception occurred or
+  \code{FALSE} otherwise.
+
+  \code{.jgetEx} returns \code{NULL} if there are no pending exceptions
+  or an object of the class "java.lang.Throwable" representing the
+  current exception.
+}
+\details{
+  Please note that some functions (such as \code{\link{.jnew}} or
+  \code{\link{.jcall}}) call \code{.jcheck} implicitly unless
+  instructed to not do so. If you want to handle Java exceptions, you
+  should make sure that those function don't clear the exception you may
+  want to catch.
+  
+  The exception handling is still as a very low-level and experimental,
+  because it requires polling of exceptions. A more elaboate system
+  using constructs similar to \code{try} ... \code{catch} is planned for
+  next major version of \code{rJava}.
+
+  \emph{Warning:} When requesting exceptions to not be cleared
+  automatically, please note that the \code{show} method (which is
+  called by \code{print}) has a side-effect of making a Java call to get
+  the string representation of a Java object. This implies that it will
+  be impeded by any pending exceptions. Therefore exceptions obtained
+  through \code{.jgetEx} can be stored, but should not be printed
+  (or otherwise used in Java calls) until after the exception is
+  cleared. In general, all Java calls will fail (possibly silently)
+  until the exception is cleared.
+}
+\seealso{
+  \code{\link{.jcall}}, \code{\link{.jnew}}
+}
+\examples{
+\donttest{
+# we try to create a bogus object and
+# instruct .jnew to not clear the exception
+# this will raise an exception
+v <- .jnew("foo/bar", check=FALSE)
+
+# you can poll for the exception, but don't try to print it
+# (see details above)
+if (!is.null(e<-.jgetEx())) print("Java exception was raised")
+
+# expect TRUE result here because the exception was still not cleared
+print(.jcheck(silent=TRUE))
+# next invocation will be FALSE because the exception is now cleared
+print(.jcheck(silent=TRUE))
+
+# now you can print the actual expection (even after it was cleared)
+print(e)
+}
+}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jclassName.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jclassName.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..c7263d027d15e9effbd166370f22f44b855ebe22
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jclassName.Rd
@@ -0,0 +1,41 @@
+\name{jclassName-class}
+\docType{class}
+\alias{jclassName-class}
+\alias{as.character,jclassName-method}
+
+\title{Class "jclassName" - a representation of a Java class name }
+\description{ This class holds a name of a class in Java. }
+\section{Objects from the Class}{
+Objects of this class should *not* be created directly. Instead, the
+function \code{\link{J}} should be used to create new objects of this class.
+}
+\section{Slots}{
+  \describe{
+    \item{\code{name}:}{Name of the class (in source code notation)}
+    \item{\code{jobj}:}{Object representing the class in Java}
+  }
+}
+\section{Methods}{
+  The objects of class \code{jclassName} are used indirectly to be able
+  to create new Java objects via \code{new} such as
+  \code{new(J("java.lang.String"), "foo")} or to use the \code{$}
+  convenience operator on static classes, such as
+  \code{J("java.lang.Double")$parseDouble("10.2")}.
+
+  \describe{
+    \item{\code{as.character}}{\code{signature(x = "jclassName")}:
+      returns the class name as a string vector of length one.
+    }
+  }
+}
+%\references{ ~put references to the literature/web site here ~ }
+\author{ Simon Urbanek }
+%\note{ ~~further notes~~ }
+% ~Make other sections like Warning with \section{Warning }{....} ~
+\seealso{
+  \code{\link{J}}, \code{\link{new}}
+}
+%\examples{
+%##---- Should be DIRECTLY executable !! ----
+%}
+\keyword{classes}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jengine.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jengine.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..1a543df420a83e6d03cb7b49ff468cad44670f4b
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jengine.Rd
@@ -0,0 +1,44 @@
+\name{jengine}
+\alias{.jengine}
+\title{
+  Java callback engineCast a Java object to another class
+}
+\description{
+  \code{.jengine} obtains the current callback engine or starts it.
+}
+\usage{
+.jengine(start=FALSE, silent=FALSE)
+}
+\arguments{
+  \item{start}{if set to \code{TRUE} then the callback engine is started
+    if it is not yet active}
+  \item{silent}{if set to \code{TRUE} then NULL is returned if there is
+    no engine available. Otherwise an error is raised}
+}
+\value{
+  Returns a Java object reference (\code{jobjRef}) to the current Java
+  callback engine.
+}
+\details{
+  \code{.jengine} can be used to detect whether the engine was started
+  or to start the engine.
+
+  Before any callbacks from Java into R can be performed, the Java
+  callback engine must be initialized, loading Java/R Interface
+  (JRI). If JRI was not started and \code{start} is set to \code{TRUE}
+  then \code{.jengine} will load necessary classes and start
+  it.
+
+  Note that JRI is an optional part of rJava and requires R shared
+  library at the moment. By default rJava will continue with
+  installation even if JRI cannot be built.
+}
+\seealso{
+  \code{\link{.jcall}}
+}
+\examples{
+\dontrun{
+.jengine(TRUE)
+}
+}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jequals.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jequals.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..e49d8bbbd7cc90bd6bf64e4062c5f0ff1e6288f2
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jequals.Rd
@@ -0,0 +1,162 @@
+\name{jequals}
+\alias{.jequals}
+\alias{.jcompare}
+\alias{!=,ANY,jobjRef-method}
+\alias{!=,jobjRef,jobjRef-method}
+\alias{!=,jobjRef,ANY-method}
+\alias{==,ANY,jobjRef-method}
+\alias{==,jobjRef,jobjRef-method}
+\alias{==,jobjRef,ANY-method}
+\alias{<,ANY,jobjRef-method}
+\alias{<,jobjRef,jobjRef-method}
+\alias{<,jobjRef,ANY-method}
+\alias{>,ANY,jobjRef-method}
+\alias{>,jobjRef,jobjRef-method}
+\alias{>,jobjRef,ANY-method}
+\alias{<=,ANY,jobjRef-method}
+\alias{<=,jobjRef,jobjRef-method}
+\alias{<=,jobjRef,ANY-method}
+\alias{>=,ANY,jobjRef-method}
+\alias{>=,jobjRef,jobjRef-method}
+\alias{>=,jobjRef,ANY-method}
+
+\title{
+  Comparing Java References
+}
+\description{
+  \code{.jequals} function can be used to determine whether two objects
+  are equal. In addition, it allows mixed comparison of non-Java object
+  for convenience, unless strict comparison is desired.
+
+  The binary operators \code{==} and \code{!=} are mapped to
+  (non-strict) call to \code{.jequals} for convenience.
+  
+  \code{.jcompare} compares two objects in the sense of the 
+  \code{java.lang.Comparable} interface. 
+  
+  The binary operators \code{<}, \code{>}, \code{<=}, \code{>=} are mapped 
+  to calls to \code{.jcompare} for convenience
+}
+\usage{
+.jequals(a, b, strict = FALSE)
+.jcompare( a, b )
+}
+\arguments{
+  \item{a}{first object}
+  \item{b}{second object}
+  \item{strict}{when set to \code{TRUE} then non-references save for
+    \code{NULL} are always treated as different, see details.}
+}
+\value{
+ \code{.jequals} returns \code{TRUE} if both object 
+ 	are considered equal, \code{FALSE} otherwise.
+ 	
+ \code{.jcompare} returns the result of the \code{compareTo} java method
+ of the object a applied to b
+}
+\section{Methods}{
+  \describe{
+    \item{!=}{\code{signature(e1 = "ANY", e2 = "jobjRef")}: ... }
+    \item{!=}{\code{signature(e1 = "jobjRef", e2 = "jobjRef")}: ... }
+    \item{!=}{\code{signature(e1 = "jobjRef", e2 = "ANY")}: ... }
+    \item{==}{\code{signature(e1 = "ANY", e2 = "jobjRef")}: ... }
+    \item{==}{\code{signature(e1 = "jobjRef", e2 = "jobjRef")}: ... }
+    \item{==}{\code{signature(e1 = "jobjRef", e2 = "ANY")}: ... }
+    \item{<}{\code{signature(e1 = "ANY", e2 = "jobjRef")}: ... }
+    \item{<}{\code{signature(e1 = "jobjRef", e2 = "jobjRef")}: ... }
+    \item{<}{\code{signature(e1 = "jobjRef", e2 = "ANY")}: ... }
+    \item{>}{\code{signature(e1 = "ANY", e2 = "jobjRef")}: ... }
+    \item{>}{\code{signature(e1 = "jobjRef", e2 = "jobjRef")}: ... }
+    \item{>}{\code{signature(e1 = "jobjRef", e2 = "ANY")}: ... }
+    \item{>=}{\code{signature(e1 = "ANY", e2 = "jobjRef")}: ... }
+    \item{>=}{\code{signature(e1 = "jobjRef", e2 = "jobjRef")}: ... }
+    \item{>=}{\code{signature(e1 = "jobjRef", e2 = "ANY")}: ... }
+    \item{<=}{\code{signature(e1 = "ANY", e2 = "jobjRef")}: ... }
+    \item{<=}{\code{signature(e1 = "jobjRef", e2 = "jobjRef")}: ... }
+    \item{<=}{\code{signature(e1 = "jobjRef", e2 = "ANY")}: ... }
+
+	 }
+}
+\details{
+	\code{.jequals} compares two Java objects by calling \code{equals}
+  method of one of the objects and passing the other object as its
+  argument. This allows Java objects to define the `equality' in
+  object-dependent way.
+
+  In addition, \code{.jequals} allows the comparison of Java object to
+  other scalar R objects. This is done by creating a temporary Java
+  object that corresponds to the R object and using it for a call to the
+  \code{equals} method. If such conversion is not possible a warning is
+  produced and the result it \code{FALSE}. The automatic conversion
+  will be avoided if \code{strict} parameter is set to \code{TRUE}.
+
+  \code{NULL} values in \code{a} or \code{b} are replaced by Java
+  \code{null}-references and thus \code{.jequals(NULL,NULL)} is \code{TRUE}.
+
+  If neither \code{a} and \code{b} are Java objects (with the exception
+  of both being \code{NULL}) then the result is identical to that of
+  \code{all.equal(a,b)}.
+  
+  Neither comparison operators nor \code{.jequals} supports vectors and
+  returns \code{FALSE} in that case. A warning is also issued unless
+  strict comparison was requested.
+}
+\note{
+  Don't use \code{x == NULL} to check for
+  \code{null}-references, because \code{x} could be \code{NULL} and thus
+  the result would be an empty vector. Use \code{\link{is.jnull}}
+  instead.
+  (In theory \code{is.jnull} and \code{x == .jnull()} are the the same,
+  but \code{is.jnull} is more efficient.)
+}
+\seealso{
+  \code{\link{is.jnull}}
+}
+\examples{
+\dontshow{.jinit()}
+s <- .jnew("java/lang/String", "foo")
+.jequals(s, "foo") # TRUE
+.jequals(s, "foo", strict=TRUE) # FALSE - "foo" is not a Java object
+t <- s
+.jequals(s, t, strict=TRUE) # TRUE
+
+s=="foo" # TRUE
+
+\dontshow{ 
+	stopifnot( 
+		.jequals(s, "foo"), 
+		!.jequals(s, "foo", strict=TRUE), 
+		.jequals(s, t, strict=TRUE), 
+		s == "foo"
+	)
+}
+
+Double <- J("java.lang.Double")
+d1 <- new( Double, 0.0 ) 
+d2 <- new( Double, 1.0 )
+d3 <- new( Double, 0.0 )
+
+d1 < d2
+d1 <= d3
+d1 >= d3
+d1 > d2
+
+# cannot compare a Double and a String
+try( d1 < "foo" )
+
+# but can compare a Double and an Integer
+d1 < 10L
+
+\dontshow{
+	stopifnot( 
+		d1 < d2       ,
+		d1 <= d3      ,
+		d1 >= d3      ,
+		! (d1 > d2 )  , 
+		inherits( try( d1 < "foo", silent = TRUE ), "try-error" ), 
+		d1 < 10L )
+}
+
+
+}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jfield.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jfield.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..46438c89f771a973561afcf9912d41ddbfefed55
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jfield.Rd
@@ -0,0 +1,57 @@
+\name{jfield}
+\alias{.jfield}
+\alias{.jfield<-}
+\title{
+  Obtains the value of a field 
+}
+\description{
+  \code{.jfield} returns the value of the specified field on an object.
+}
+\usage{
+.jfield(o, sig = NULL, name, true.class = is.null(sig), convert = TRUE)
+`.jfield<-`(o, name, value)
+}
+\arguments{
+  \item{o}{Class name or object (Java reference) whose field is to be
+    accessed. Static fields are supported both by specifying the class
+    name or using an instance.}
+  \item{sig}{signature (JNI type) of the field. If set to \code{NULL}
+    rJava attempts to determine the signature using reflection. For
+    efficiency it is recommended to specify the signature, because
+    the reflection lookup is quite expensive.}
+  \item{name}{name of the field to access}
+  \item{true.class}{by default the class of the resulting object matches
+    the siganture of the field. Setting this flag to \code{TRUE} causes
+    \code{.jfield} to use true class name of the resulting object
+    instead. (this flag has no effect on scalar fields)}
+  \item{convert}{when set to \code{TRUE} all references are converted to
+    native types (where possible). Otherwise Java references are
+    returned directly.}
+  \item{value}{value to assign into the field. The field signature is
+    determined from the value in the same way that parameter signatures
+    are determined in \code{\link{.jcall}} - be sure to cast the value
+    as necessary, no automatic conversion is done.}
+}
+\value{
+  \code{.jfield}: contents of the field, \code{.jfield<-}: modified object.
+}
+\details{
+  The detection of a field signature in \code{.jfield} using reflection
+  is considerably expensive (more than 3 additional method calls have to
+  be performed), therefore it is recommended for time-critical code to
+  specify the field signature beforehand.
+
+  NOTE: The sequence of arguments in \code{.jfield} has been changed
+  since rJava 0.5 to be more consistent and match the sequence in
+  \code{.jcall}. Also \code{.jsimplify} is no longer needed as primitive
+  types are obtained directly.
+}
+\seealso{
+  \code{\link{.jcall}}
+}
+\examples{
+\dontrun{
+.jfield("java/lang/Boolean",, "TYPE")
+}
+}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jfloat-class.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jfloat-class.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..f7eb877cc4e5e5fefc57ff01a417ffa9c4b06bb9
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jfloat-class.Rd
@@ -0,0 +1,54 @@
+\name{jfloat-class}
+\docType{class}
+\alias{jfloat-class}
+\alias{jlong-class}
+\alias{jbyte-class}
+\alias{jchar-class}
+\title{Classes "jfloat", "jlong", "jbyte" and "jchar" specify Java
+  native types that are not native in R}
+\description{ These classes wrap a numeric vector to be treated as
+  \code{float} or \code{long} argument when passed to Java and an
+  integer vector to be treated as \code{byte} or \code{char}. R doesn't
+  distinguish between \code{double} and \code{float}, but Java
+  does. In order to satisfy object types, numeric vectors that should be
+  converted to floats or long on the Java side must be wrapped in this
+  class. In addition \code{jbyte} must be used when passing scalar byte
+  (but not byte arrays, those are mapped into RAW vectors). Finally
+  \code{jchar} it used when mapping integer vectors into unicode Java
+  character vectors.}
+\section{Objects from the Class}{
+  Objects can be created by calling \code{\link{.jfloat}},
+  \code{\link{.jlong}}, \code{\link{.jbyte}} or \code{\link{.jchar}}
+  respectively.
+}
+\section{Slots}{
+  \describe{
+    \item{\code{.Data}:}{Payload}
+  }
+}
+\section{Extends}{
+  "jfloat" and "jlong":
+  Class \code{"numeric"}, from data part.
+  Class \code{"vector"}, by class \code{"numeric"}.
+
+  "jbyte" and "jchar":
+  Class \code{"integer"}, from data part.
+  Class \code{"vector"}, by class \code{"integer"}.
+}
+\section{Methods}{
+  "jfloat" and "jlong" have no methods other than those inherited from "numeric".
+  "jbyte" and "jchar" have no methods other than those inherited from "integer".
+}
+%\references{ ~put references to the literature/web site here ~ }
+\author{ Simon Urbanek }
+%\note{ ~~further notes~~ }
+
+% ~Make other sections like Warning with \section{Warning }{....} ~
+
+\seealso{
+  \code{\link{.jfloat}}, \code{\link{.jlong}}, \code{\link{.jbyte}}, \code{\link{.jchar}} and \code{\link{.jcall}}
+}
+%\examples{
+%##---- Should be DIRECTLY executable !! ----
+%}
+\keyword{classes}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jfloat.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jfloat.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..378918d92055460c2cd5a7910b4ad8d140571e13
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jfloat.Rd
@@ -0,0 +1,66 @@
+\name{jfloat}
+\alias{.jfloat}
+\alias{.jlong}
+\alias{.jbyte}
+\alias{.jchar}
+\alias{.jshort}
+\alias{jfloat}
+\alias{jlong}
+\alias{jbyte}
+\alias{jchar}
+\alias{jshort}
+\title{
+  Wrap numeric vector as flat Java parameter
+}
+\description{
+  \code{.jfloat} marks a numeric vector as an object that can be used
+  as parameter to Java calls that require \code{float} parameters.
+  Similarly, \code{.jlong} marks a numeric vector as \code{long} parameter.
+}
+\usage{
+.jfloat(x)
+.jlong(x)
+.jbyte(x)
+.jchar(x)
+.jshort(x)
+}
+\arguments{
+  \item{x}{numeric vector}
+}
+\value{
+  Returns a numeric vector of the class \code{jfloat}, \code{jlong},
+  \code{jbyte}, \code{jshort} or \code{jchar}
+  that can be used as parameter to Java calls that require
+  \code{float}, \code{long}, \code{byte}, \code{short} or \code{char}
+  parameters respectively.
+}
+\details{
+  R has no native \code{float} or \code{long} type. Numeric vectors are
+  stored as \code{double}s, hence there is no native way to pass float
+  numbers to Java methods. The \code{.jfloat} call marks a numeric
+  vector as having the Java type \code{float} by wrapping it in the
+  \code{jfloat} class. The class is still a subclass of \code{numeric},
+  therefore all regular R operations are unaffected by this.
+
+  Similarly, \code{.jlong} is used to mark a numeric vector as a
+  parameter of the \code{long} Java type. Please note that in general R
+  has no native type that will hold a \code{long} value, so conversion
+  between Java's \code{long} type and R's numeric is potentially lossy.
+
+  \code{.jbyte} is used when a scalar byte is to be passed ot Java. Note
+  that byte arrays are natively passed as RAW vectors, not as
+  \code{.jbyte} arrays.
+  
+  \code{jchar} is strictly experimental and may be based on
+  \code{character} vectors in the future.
+}
+\seealso{
+  \code{\link{.jcall}}, \code{\link{jfloat-class}}
+}
+%\examples{
+%\dontrun{
+%v <- .jnew("java/util/Vector")
+%.jcall("java/lang/System","I","identityHashCode",.jcast(v, "java/lang/Object"))
+%}
+%}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jinit.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jinit.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..075f5210832aa7c3ff6f04db9fbd1dde168128d8
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jinit.Rd
@@ -0,0 +1,74 @@
+\name{jinit}
+\alias{.jinit}
+\title{
+  Initialize Java VM
+}
+\description{
+  \code{.jinit} initializes the Java Virtual Machine (JVM). This
+  function must be called before any rJava functions can be used.
+}
+\usage{
+.jinit(classpath = NULL, parameters = getOption("java.parameters"), ...,
+silent = FALSE, force.init = FALSE)
+}
+\arguments{
+  \item{classpath}{Any additional classes to include in the Java class
+    paths (i.e. locations of Java classes to use). This path will be
+    prepended to paths specified in the \code{CLASSPATH} environment
+    variable. Do NOT set this system class path initializing a package,
+    use \code{\link{.jpackage}} instead, see details.}
+  \item{parameters}{character vector of parameters to be passed to
+    the virtual machine. They are implementation dependent and apply
+    to JDK version 1.2 or higher only. Please note that each parameter
+    must be in a separate element of the array, you cannot use a
+    space-separated string with multiple parameters.}
+  \item{...}{Other optional Java initialization parameters (implementation-dependent).}
+  \item{silent}{If set to \code{TRUE} no warnings are issued.}
+  \item{force.init}{If set to \code{TRUE} JVM is re-initialized even if
+    it is already running.}
+}
+\value{
+  The return value is an integer specifying whether and how the VM was
+  initialized. Negative values indicate failure, zero denotes successful
+  initialization and positive values signify partially successful
+  initilization (i.e. the VM is up, but parameters or class path could
+  not be set due to an existing or incompatible VM).
+}
+\details{
+  Starting with version 0.5 rJava provides a custom class loader that can
+  automatically track classes and native libraries that are provided in
+  R packages. Therefore R packages should NOT use \code{.jinit}, but
+  call \code{\link{.jpackage}} instead. In addition this allows the use
+  of class path modifying function \code{\link{.jaddClassPath}}.
+
+  Important note: if a class is found on the system class path (i.e. on
+  the \code{classpath} specified to \code{.jinit}) then the system class
+  loader is used instead of the rJava loader, which can lead to problems
+  with reflection and native library support is not enabled. Therefore
+  it is highly recommended to use \code{.jpackage} or
+  \code{.jaddClassPath} instead of \code{classpath} (save for system
+  classes).
+  
+  Stating with version 0.3-8 rJava is now capable of modifying the class
+  path on the fly for certain Sun-based Java virtual machines, even when
+  attaching to an existing VM. However, this is done by exploiting the
+  way ClassLoader is implemented and may fail in the future. In general
+  it is officially not possible to change the class path of a running
+  VM.
+  
+  At any rate, it is impossible to change any other VM parameters of a
+  running VM, so when using \code{.jinit} in a package, be generous with
+  limits and don't use VM parameters to unnecessarily restrict
+  resources (or preferably use \code{\link{.jpackage}} instead).
+}
+\seealso{
+  \code{\link{.jpackage}}
+}
+\examples{
+\dontrun{
+## set heap size limit to 512MB (see java -X) and
+## use "myClasses.jar" as the class path
+.jinit(classpath="myClasses.jar", parameters="-Xmx512m")
+}
+}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jmemprof.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jmemprof.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..9f0857bef89de7d9138a0a26b4f40d7a432dbc31
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jmemprof.Rd
@@ -0,0 +1,47 @@
+\name{jmemprof}
+\alias{.jmemprof}
+\title{
+  rJava memory profiler
+}
+\description{
+  \code{.jmemprof} enables or disables rJava memory profiling. If rJava
+  was compiled without memory profiling support, then a call to this
+  function always causes an error.
+}
+\usage{
+.jmemprof(file = "-")
+}
+\arguments{
+  \item{file}{file to write profiling information to or \code{NULL} to
+    disable profiling}
+}
+\value{
+  Returns \code{NULL}.
+}
+\details{
+  The \code{file} parameter must be either a filename (which will be
+  opened in append-mode) or "-" to use standard output or \code{NULL} to
+  disable profiling. An empty string "" is equivalent to \code{NULL} in
+  this context.
+
+  Note that lots of finalizers are run only when R exists, so usually
+  you want to enable profiling early and let R exit to get a sensible
+  profile. Runninng gc may be helpful to get rid of references that can
+  be collected in R.
+
+  A simple perl script is provided to analyze the result of the
+  profiler. Due to its simple text format, it is possible to capture
+  entire stdout including the profiler information to have both the
+  console context for the allocations and the profile. Memory profiling
+  is also helful if rJava debug is enabled.
+
+  Note that memory profiling support must be compiled in rJava and it is
+  by default compiled only if debug mode is enabled (which is not the
+  case by default).
+}
+\examples{
+\donttest{
+.jmemprof("rJava.mem.profile.txt")
+}
+}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jnew.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jnew.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..d599012346b9c68b248b07d50eca708ca537a36b
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jnew.Rd
@@ -0,0 +1,51 @@
+\name{jnew}
+\alias{.jnew}
+\title{
+  Create a Java object
+}
+\description{
+	\code{.jnew} create a new Java object.
+}
+\usage{
+.jnew(class, ..., check=TRUE, silent=!check, class.loader=NULL)
+}
+\arguments{
+  \item{class}{fully qualified class name in JNI notation (e.g. \code{"java/lang/String"}).}
+  \item{...}{
+    Any parameters that will be passed to the corresponding
+    constructor. The parameter types are determined automatically and/or
+    taken from the \code{jobjRef} object. For details see
+    \code{\link{.jcall}}. Note that all named parameters are discarded.}
+  \item{check}{
+    If set to \code{TRUE} then \code{\link{.jcheck}} is invoked before
+    and after the call to the constructor to clear any pending Java
+    exceptions.}
+  \item{silent}{
+    If set to \code{FALSE} then \code{.jnew} will fail with an error if
+    the object cannot be created, otherwise a null-reference is returned
+    instead. In addition, this flag is also passed to final
+    \code{.jcheck} if \code{check} above is set to \code{TRUE}. Note
+    that the error handling also clears exceptions, so
+    \code{check=FALSE, silent=FALSE} is usually not a meaningful
+    combination.
+  }
+  \item{class.loader}{optional class loader to force for loading the
+    class. If not set, the rJava class loader is used first. The default
+    Java class loader is always used as a last resort. This is for
+    expert use only! If you set the class loader, the class loading
+    behavior changes - use only in very special circumstances.}
+}
+\value{
+  Returns the reference (\code{jobjRef}) to the newly created object or
+  \code{null}-reference (see \code{\link{.jnull}}) if something went wrong.
+}
+\seealso{
+  \code{\link{.jcall}}, \code{\link{.jnull}}
+}
+\examples{
+\dontrun{
+f <- .jnew("java/awt/Frame","Hello")
+.jcall(f,,"setVisible",TRUE)
+}
+}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jnull.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jnull.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..2f316f7faff4ced0bca90d90c797575ef7761a1a
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jnull.Rd
@@ -0,0 +1,57 @@
+\name{jnull}
+\alias{.jnull}
+\alias{is.jnull}
+\title{
+  Java null object reference
+}
+\description{
+  \code{.jnull} returns a \code{null} reference of a specified class
+  type. The resulting object is of the class \code{jobjRef}.
+
+  \code{is.jnull} is an extension of \code{is.null} that also returns
+  \code{TRUE} if the supplied object is a \code{null} Java reference.
+}
+\usage{
+.jnull(class = "java/lang/Object")
+is.jnull(x)
+}
+\arguments{
+  \item{class}{fully qualified target class name in JNI notation
+    (e.g. \code{"java/lang/String"}).}
+  \item{x}{object to check}
+}
+\value{
+  \code{.jnull} returns a Java object reference (\code{jobjRef}) of a
+  \code{null} object having the specified object class.
+
+  \code{is.jnull} returns \code{TRUE} if \code{is.null(x)} is
+  \code{TRUE} or if \code{x} is a Java \code{null} reference.
+}
+\details{
+  \code{.jnull} is necesary if \code{null} is to be passed as an
+  argument of \code{\link{.jcall}} or \code{\link{.jnew}}, in order to be
+  able to find the correct method/constructor.
+
+  Example: given the following method definitions of the class \code{A}:
+  \itemize{
+    \item{o}{public static void run(String a);}
+    \item{o}{public static void run(Double n);}
+  }
+  Calling \code{.jcall("A",,"run",NULL)} is ambiguous, because it is
+  unclear which method is to be used. Therefore rJava requires class
+  information with each argument to \code{\link{.jcall}}. If we wanted
+  to run the String-version, we could use
+  \code{.jcall("A",,"run",.jnull("java/lang/String"))}.
+
+  \code{is.jnull} is a test that should be used to determine whether a
+  given Java reference is a \code{null} reference.
+}
+\seealso{
+  \code{\link{.jcall}}, \code{\link{.jcast}}
+}
+\examples{
+\dontrun{
+.jcall("java/lang/System","I","identityHashCode",.jnull())
+}
+}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jobjRef-class.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jobjRef-class.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..af2bfa852abaa9a6f7048a41485afcfe3d0ee1f3
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jobjRef-class.Rd
@@ -0,0 +1,24 @@
+\name{jobjRef-class}
+\docType{class}
+\alias{jobjRef-class}
+
+\title{Class "jobjRef" - Reference to a Java object }
+\description{ This class describes a reference to an object held in a JavaVM. }
+\section{Objects from the Class}{
+Objects of this class should *not* be created directly. Instead, the function \code{\link{.jnew}} should be use to create new Java objects. They can also be created as results of the \code{\link{.jcall}} function.
+}
+\section{Slots}{
+  \describe{
+    \item{\code{jobj}:}{Internal identifier of the object (external pointer to be precise)}
+    \item{\code{jclass}:}{Java class name of the object (in JNI notation)}
+  }
+  Java-side attributes are not accessed via slots, but the \code{$} operator instead.
+}
+\section{Methods}{
+This object's Java methods are not accessed directly. Instead, \code{\link{.jcall}} JNI-API should be used for invoking Java methods. For convenience the \code{$} operator can be used to call methods via reflection API.
+}
+\author{ Simon Urbanek }
+\seealso{
+  \code{\link{.jnew}}, \code{\link{.jcall}}  or \code{\link{jarrayRef-class}}
+}
+\keyword{classes}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jpackage.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jpackage.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..29daddf40f423213ae23a5ef3b4b0dd06b82ba8d
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jpackage.Rd
@@ -0,0 +1,66 @@
+\name{jpackage}
+\alias{.jpackage}
+\title{
+  Initialize an R package containing Java code
+}
+\description{
+  \code{.jpackage} initializes the Java Virtual Machine (JVM) for an R
+  package. In addition to starting the JVM it also registers Java
+  classes and native code contained in the package with the JVM.
+  function must be called before any rJava functions can be used.
+}
+\usage{
+.jpackage(name, jars='*', morePaths='', nativeLibrary=FALSE, lib.loc=NULL)
+}
+\arguments{
+  \item{name}{name of the package. It should correspond to the
+    \code{pkgname} parameter of \code{.onLoad} or \code{.First.lib}
+    function.}
+  \item{jars}{Java archives in the \code{java} directory of the package
+    that should be added to the class path. The paths must be relative
+    to package's \code{java} directory. A special value of
+    \code{'*'} adds all \code{.jar} files from the \code{java} the
+    directory.}
+  \item{morePaths}{vector listing any additional entries that should
+    be added to the class path.}
+  \item{nativeLibrary}{a logical determining whether rJava should look
+    for native code in the R package's shared object or not.}
+  \item{lib.loc}{a character vector with path names of R libraries, or
+    \code{NULL} (see \code{\link{system.file}} and examples below).}
+
+}
+\value{
+  The return value is an invisible TRUE if the initialization was successful.  
+}
+\details{
+  \code{.jpackage} initializes a Java R package as follows: first the
+  JVM is initialized via \code{\link{.jinit}} (if it is not running
+  already). Then the \code{java} directory of the package is added to
+  the class path. Then \code{.jpackage} prepends \code{jars} with the
+  path to the \code{java} directory of the package and adds them to the
+  class path (or all \code{.jar} files if \code{'*'} was specified).
+  Finally the \code{morePaths} parameter (if set) is passed to a call
+  to \code{\link{.jaddClassPath}}.
+
+  Therefore the easiest way to create a Java package is to add
+  \code{.jpackage(pkgname, lib.loc=libname)} in \code{.onLoad} or
+  \code{.First.lib}, and copy all necessary classes to a JAR file(s)
+  which is placed in the \code{inst/java/} directory of the source
+  package.
+
+  If a package needs special Java parameters, \code{"java.parameters"}
+  option can be used to set them on initialization. Note, however, that
+  Java parameters can only be used during JVM initialization and other
+  package may have intialized JVM already.
+}
+\seealso{
+  \code{\link{.jinit}}
+}
+\examples{
+\dontrun{
+.onLoad <- function(libname, pkgname) {
+  .jpackage(pkgname, lib.loc=libname)
+}
+}
+}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jrectRef-class.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jrectRef-class.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..88787d014f0e107b84c319344e7da964e3ba10e8
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jrectRef-class.Rd
@@ -0,0 +1,278 @@
+\name{jrectRef-class}
+\Rdversion{1.1}
+\docType{class}
+\alias{jrectRef-class}
+\alias{[,jrectRef-method}
+\alias{length,jrectRef-method}
+\alias{str,jrectRef-method}
+\alias{dim,jrectRef-method}
+\alias{dim<-,jrectRef-method}
+\alias{unique,jrectRef-method}
+\alias{duplicated,jrectRef-method}
+\alias{anyDuplicated,jrectRef-method}
+\alias{sort,jrectRef-method}
+\alias{rev,jrectRef-method}
+\alias{min,jrectRef-method}
+\alias{max,jrectRef-method}
+\alias{range,jrectRef-method}
+
+\title{Rectangular java arrays}
+\description{References to java arrays that are guaranteed to be rectangular, i.e similar 
+to R arrays}
+\section{Objects from the Class}{
+Objects of this class should *not* be created directly. 
+Instead, they usually come as a result of a java method call. 
+}
+\section{Slots}{
+  \describe{
+    \item{\code{jsig}:}{JNI signature of the array type}
+    \item{\code{jobj}:}{Internal identifier of the object}
+    \item{\code{jclass}:}{Inherited from \code{jobjRef}, but unspecified}
+    \item{\code{dimension}:}{dimension vector of the array}
+  }
+}
+\section{Extends}{
+Class \code{"\linkS4class{jarrayRef}"}, directly.
+Class \code{"\linkS4class{jobjRef}"}, by class "jarrayRef", distance 2.
+}
+\section{Methods}{
+  \describe{
+    \item{length}{\code{signature(x = "jrectRef")}: The number of elements in the array. 
+    	Note that if the array has more than one dimension, 
+    	it gives the number of arrays in the first dimension, and not the total 
+    	number of atomic objects in tha array (like R does). This gives what would be 
+		returned by \code{array.length} in java.}
+    \item{str}{\code{signature(object = "jrectRef")}: ... }
+    \item{[}{\code{signature(x = "jrectRef")}: R indexing of rectangular java arrays }
+    \item{dim}{\code{signature(x = "jrectRef")}: extracts the dimensions of the array }
+    \item{dim<-}{\code{signature(x = "jrectRef")}: sets the dimensions of the array }
+    \item{unique}{\code{signature(x = "jrectRef")}: unique objects in the array}
+    \item{duplicated}{\code{signature(x = "jrectRef")}: see \code{\link{duplicated}} }
+    \item{anyDuplicated}{\code{signature(x = "jrectRef")}: see \code{\link{anyDuplicated}} }
+    \item{sort}{\code{signature(x = "jrectRef")}: returns a \emph{new} array with elements from x in order }
+    \item{rev}{\code{signature(x = "jrectRef")}: returns a \emph{new} array with elements from x reversed }
+    \item{min}{\code{signature(x = "jrectRef")}: the smallest object in the array (in the sense of the Comparable interface) }
+    \item{max}{\code{signature(x = "jrectRef")}: the biggest object in the array (in the sense of the Comparable interface) }
+    \item{range}{\code{signature(x = "jrectRef")}: the range of the array (in the sense of the Comparable interface) }
+  }
+}
+\examples{
+\dontshow{
+# these examples are only unit tests so far
+.jinit()
+}
+v <- new( J("java.util.Vector") )
+v$add( "hello" )
+v$add( "world" )
+v$add( new( J("java.lang.Double"), "10.2" ) )
+array <- v$toArray()
+
+array[ c(TRUE,FALSE,TRUE) ]
+array[ 1:2 ]
+array[ -3 ]
+
+# length 
+length( array )
+\dontshow{stopifnot(length(array) == 3L)}
+
+# also works as a pseudo field as in java
+array$length
+\dontshow{stopifnot(array$length == 3L)}
+
+
+\dontshow{
+# # 2d
+dim2d <- c(5L, 2L)
+
+x <- .jcall( "RectangularArrayExamples", "[[Z",
+"getBooleanDoubleRectangularArrayExample",  evalArray = TRUE, simplify = TRUE)
+stopifnot( identical( typeof( x ), "logical" ) )
+stopifnot( identical( dim(x) , dim2d ) )
+stopifnot( identical( as.vector(x), rep( c(FALSE,TRUE), 5 ) ) )
+
+x <- .jcall( "RectangularArrayExamples", "[[I",
+"getIntDoubleRectangularArrayExample",  evalArray = TRUE, simplify = TRUE )
+stopifnot( identical( typeof( x ), "integer" ) )
+stopifnot( identical( dim(x) , dim2d ) )
+stopifnot( identical( as.vector(x), 0:9 ) )
+ 
+x <- .jcall( "RectangularArrayExamples", "[[B",
+"getByteDoubleRectangularArrayExample",  evalArray = TRUE, simplify = TRUE )
+stopifnot( identical( typeof( x ), "raw" ) )
+stopifnot( identical( dim(x) , dim2d ) )
+stopifnot( identical( as.vector(x), as.raw(0:9) ) )
+
+x <- .jcall( "RectangularArrayExamples", "[[J",
+"getLongDoubleRectangularArrayExample",  evalArray = TRUE, simplify = TRUE )
+stopifnot( identical( typeof( x ), "double" ) )
+stopifnot( identical( dim(x) , dim2d ) )
+stopifnot( identical( as.vector(x), as.numeric(0:9) ) )
+
+x <- .jcall( "RectangularArrayExamples", "[[S",
+"getShortDoubleRectangularArrayExample",  evalArray = TRUE, simplify = TRUE )
+stopifnot( identical( typeof( x ), "integer" ) )
+stopifnot( identical( dim(x) , dim2d ) )
+stopifnot( identical( as.vector(x), 0:9 ) )
+
+x <- .jcall( "RectangularArrayExamples", "[[D",
+"getDoubleDoubleRectangularArrayExample",  evalArray = TRUE, simplify = TRUE )
+stopifnot( identical( typeof( x ), "double" ) )
+stopifnot( identical( dim(x) , dim2d ) )
+stopifnot( identical( as.vector(x), as.numeric(0:9) ) )
+
+x <- .jcall( "RectangularArrayExamples", "[[C",
+"getCharDoubleRectangularArrayExample",  evalArray = TRUE, simplify = TRUE )
+stopifnot( identical( typeof( x ), "integer" ) )
+stopifnot( identical( dim(x) , dim2d ) )
+stopifnot( identical( as.vector(x), 0:9 ) )
+
+x <- .jcall( "RectangularArrayExamples", "[[F",
+"getFloatDoubleRectangularArrayExample",  evalArray = TRUE, simplify = TRUE )
+stopifnot( identical( typeof( x ), "double" ) )
+stopifnot( identical( dim(x) , dim2d ) )
+stopifnot( identical( as.vector(x), as.numeric(0:9) ) )
+
+x <- .jcall( "RectangularArrayExamples", "[[Ljava/lang/String;",
+"getStringDoubleRectangularArrayExample",  evalArray = TRUE, simplify = TRUE )
+stopifnot( identical( typeof( x ), "character" ) )
+stopifnot( identical( dim(x) , dim2d ) )
+stopifnot( identical( as.vector(x), as.character(0:9) ) )
+
+
+# 3d
+
+dim3d <- c(5L, 3L, 2L) 
+
+x <- .jcall( "RectangularArrayExamples", "[[[Z",
+"getBooleanTripleRectangularArrayExample",  evalArray = TRUE, simplify = TRUE)
+stopifnot( identical( typeof( x ), "logical" ) )
+stopifnot( identical( dim(x) , dim3d ) )
+stopifnot( identical( as.vector(x), rep( c(FALSE,TRUE), 15L ) ) )
+
+x <- .jcall( "RectangularArrayExamples", "[[[I",
+"getIntTripleRectangularArrayExample",  evalArray = TRUE, simplify = TRUE )
+stopifnot( identical( typeof( x ), "integer" ) )
+stopifnot( identical( dim(x) , dim3d ) )
+stopifnot( identical( as.vector(x), 0:29 ) )
+ 
+x <- .jcall( "RectangularArrayExamples", "[[[B",
+"getByteTripleRectangularArrayExample",  evalArray = TRUE, simplify = TRUE )
+stopifnot( identical( typeof( x ), "raw" ) )
+stopifnot( identical( dim(x) , dim3d ) )
+stopifnot( identical( as.vector(x), as.raw(0:29) ) )
+
+x <- .jcall( "RectangularArrayExamples", "[[[J",
+"getLongTripleRectangularArrayExample",  evalArray = TRUE, simplify = TRUE )
+stopifnot( identical( typeof( x ), "double" ) )
+stopifnot( identical( dim(x) , dim3d ) )
+stopifnot( identical( as.vector(x), as.numeric(0:29) ) )
+
+x <- .jcall( "RectangularArrayExamples", "[[[S",
+"getShortTripleRectangularArrayExample",  evalArray = TRUE, simplify = TRUE )
+stopifnot( identical( typeof( x ), "integer" ) )
+stopifnot( identical( dim(x) , dim3d ) )
+stopifnot( identical( as.vector(x), 0:29 ) )
+
+x <- .jcall( "RectangularArrayExamples", "[[[D",
+"getDoubleTripleRectangularArrayExample",  evalArray = TRUE, simplify = TRUE )
+stopifnot( identical( typeof( x ), "double" ) )
+stopifnot( identical( dim(x) , dim3d ) )
+stopifnot( identical( as.vector(x), as.numeric(0:29) ) )
+
+x <- .jcall( "RectangularArrayExamples", "[[[C",
+"getCharTripleRectangularArrayExample",  evalArray = TRUE, simplify = TRUE )
+stopifnot( identical( typeof( x ), "integer" ) )
+stopifnot( identical( dim(x) , dim3d ) )
+stopifnot( identical( as.vector(x), 0:29 ) )
+
+x <- .jcall( "RectangularArrayExamples", "[[[F",
+"getFloatTripleRectangularArrayExample",  evalArray = TRUE, simplify = TRUE )
+stopifnot( identical( typeof( x ), "double" ) )
+stopifnot( identical( dim(x) , dim3d ) )
+stopifnot( identical( as.vector(x), as.numeric(0:29) ) )
+
+x <- .jcall( "RectangularArrayExamples", "[[[Ljava/lang/String;",
+"getStringTripleRectangularArrayExample",  evalArray = TRUE, simplify = TRUE )
+stopifnot( identical( typeof( x ), "character" ) )
+stopifnot( identical( dim(x) , dim3d ) )
+stopifnot( identical( as.vector(x), as.character(0:29) ) )
+          
+
+# testing the indexing
+
+xj <- .jarray( x, dispatch = TRUE )
+stopifnot( dim( xj[ ,, ] ) == c( 5L, 3L, 2L ) )
+stopifnot( dim( xj[ ] ) == c( 5L, 3L, 2L ) )
+stopifnot( dim( xj[ ,,1,drop= TRUE] ) == c( 5L, 3L ) )
+stopifnot( dim( xj[ ,,1,drop= FALSE] ) == c( 5L, 3L, 1L ) )
+stopifnot( dim( xj[ ,1,,drop= TRUE] ) == c( 5L, 2L ) )
+stopifnot( dim( xj[ ,1,,drop= FALSE] ) == c( 5L, 1L, 2L ) )
+stopifnot( dim( xj[ 1,,,drop= TRUE] ) == c( 3L, 2L ) )
+stopifnot( dim( xj[ 1,,,drop= FALSE] ) == c( 1L, 3L, 2L ) )
+stopifnot( dim( xj[ ,1,1,drop= TRUE] ) == c( 5L ) )
+stopifnot( dim( xj[ ,1,1,drop= FALSE] ) == c( 5L, 1L, 1L ) )
+stopifnot( dim( xj[ 1,1,1,drop= TRUE] ) == c( 1L ) )
+stopifnot( dim( xj[ 1,1,1,drop= FALSE] ) == c( 1L, 1L, 1L ) )
+
+# testing simplify
+stopifnot( identical( xj[simplify=TRUE], x) )
+stopifnot( identical( xj[,1,,simplify=TRUE], x[,1,]) )
+stopifnot( identical( xj[,1,-1,simplify=TRUE], x[,1,-1]) )
+stopifnot( identical( xj[4,1,c(TRUE,FALSE),simplify=TRUE], x[4,1,c(TRUE,FALSE)]) )
+stopifnot( identical( xj[1:10,simplify=TRUE], x[1:10]) )
+
+# test dim<-
+dim( xj ) <- c( 15L, 2L )
+stopifnot( xj@jsig == "[[Ljava/lang/String;" )
+stopifnot( dim( xj ) == c(15L, 2L ) )
+
+dim( xj ) <- NULL
+stopifnot( xj@jsig == "[Ljava/lang/String;" )
+stopifnot( dim( xj ) == 30L )
+
+# test unique
+# **** FIXME: this should really work even with dispatch=FALSE since
+#             it's a vector but it does not! It applies to everything
+#             below
+x <- .jarray( rep( 1:2, each = 5 ), dispatch = TRUE )
+xu <- unique( x )
+stopifnot( dim(xu) == 2L )
+
+  p1 <- .jnew( "java/awt/Point" )
+  p2 <- .jnew( "java/awt/Point" )
+  x <- .jarray( list( p1, p2 ), dispatch = TRUE )
+  xu <- unique( x )
+  stopifnot( dim( xu ) == 1L )
+
+# test duplicated
+x <- .jarray( rep( 1:2, each = 5 ), dispatch = TRUE )
+xd <- duplicated( x )
+stopifnot( xd == rep( c( FALSE, TRUE, TRUE, TRUE, TRUE), 2L ) ) 
+if (rJava:::.base.has.anyDuplicated) stopifnot( anyDuplicated( x ) == 2L )
+
+  p1 <- .jnew( "java/awt/Point" )
+  p2 <- .jnew( "java/awt/Point" )
+  x <- .jarray( list( p1, p2 ), dispatch = TRUE )
+  xd <- duplicated( x )
+  stopifnot( xd == c( FALSE, TRUE) )
+  if (rJava:::.base.has.anyDuplicated) stopifnot( anyDuplicated( x ) == 2L )
+
+# test sort, rev
+d1 <- .jnew("java/lang/Double", 0)
+d2 <- .jnew("java/lang/Double", -1)
+a <- .jarray( list( d1, d2), dispatch = TRUE )
+stopifnot( sort( a )[[1]]$doubleValue() == -1.0 )
+stopifnot( rev( a )[[1]]$doubleValue() == -1.0 )
+
+# test min, max, range
+Double <- J("java.lang.Double")
+a <- .jarray( list( new( Double, 10 ), new( Double, 4), new( Double, 5)
+), "java/lang/Double", dispatch = TRUE )
+stopifnot( min( a )$doubleValue() == 4  )
+stopifnot( max( a )$doubleValue() == 10 )
+stopifnot( range(a)[[1]]$doubleValue() == 4 )
+stopifnot( range(a)[[2]]$doubleValue() == 10)
+
+}
+}
+\keyword{classes}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jreflection.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jreflection.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..7d3b0600e1c8b15645dc8314798af1f6a545d6e9
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jreflection.Rd
@@ -0,0 +1,51 @@
+\name{jreflection}
+\alias{.jmethods}
+\alias{.jfields}
+\alias{.jconstructors}
+\title{
+  Simple helper functions for Java reflection
+}
+\description{
+  \code{.jconstructors} returns a character vector with all constructors for
+  a given class or object.
+  \code{.jmethods} returns a character vector with all methods for
+  a given class or object.
+  \code{.jfields} returns a character vector with all fileds (aka attributes) for a given class or object.
+}
+\usage{
+.jconstructors(o, as.obj = FALSE)
+.jmethods(o, name = NULL, as.obj = FALSE)
+.jfields(o, name = NULL, as.obj = FALSE)
+}
+\arguments{
+  \item{o}{Name of a class (either notation is fine) or an object whose
+    class will be queried}
+  \item{name}{Name of the method/field to look for. May contain regular
+    expressions except for \code{^$}.}
+  \item{as.obj}{if \code{TRUE} then a list of Java objects is
+    returned, otherwise a character vector (obtained by calling
+    \code{toString()} on each entry).}
+}
+\value{
+  Returns a character vector (if \code{as.obj} is \code{FALSE}) or a
+  list of Java objects. Each entry corresponds to the
+  \code{Constructor} resp. \code{Method} resp. \code{Field} object.
+}
+\details{
+  There first two functions are intended to help with finding correct
+  signatures for methods and constructors. Since the low-level API in
+  rJava doesn't use reflection automatically, it is necessary to
+  provide a proper  signature. That is somewhat easier using the above
+  methods.
+}
+\seealso{
+  \code{\link{.jcall}}, \code{\link{.jnew}}, \code{\link{.jcast}} or \code{\link{$,jobjRef-method}}
+}
+\examples{
+\dontrun{
+.jconstructors("java/util/Vector")
+v <- .jnew("java/util/Vector")
+.jmethods(v, "add")
+}
+}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jserialize.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jserialize.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..29383d5784bf287dbdd6adb3de0ee81790d8f32d
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jserialize.Rd
@@ -0,0 +1,107 @@
+\name{jserialize}
+\alias{.jserialize}
+\alias{.junserialize}
+\alias{.jcache}
+\title{
+  Java object serialization
+}
+\description{
+  \code{.jserialize} serializes a Java object into raw vector using
+  Java serialization.
+
+  \code{.junserialize} re-constructs a Java object from its serialized
+  (raw-vector) form.
+
+  \code{.jcache} updates, retrieves or removes R-side object cache
+  which can be used for persistent storage of Java objects across
+  sessions.
+}
+\usage{
+.jserialize(o)
+.junserialize(data)
+.jcache(o, update=TRUE)
+}
+\arguments{
+  \item{o}{Java object}
+  \item{data}{serialized Java object as a raw vector}
+  \item{update}{must be \code{TRUE} (cache is updated), \code{FALSE}
+  (cache is retrieved) or \code{NULL} (cache is deleted).}
+}
+\value{
+  \code{.jserialize} returns a raw vector
+
+  \code{.junserialize} returns a Java object or \code{NULL} if an error
+  occurred (currently you may use \code{.jcheck()} to further
+  investigate the error)
+
+  \code{.jcache} returns the current cache (usually a raw vector) or
+  \code{NULL} if there is no cache.
+}
+\details{
+  Not all Java objects support serialization, see Java documentation
+  for details. Note that Java serialization and serialization of R
+  objects are two entirely different mechanisms that cannot be
+  interchanged. \code{.jserialize} and \code{.junserialize} can
+  be used to access Java serialization facilities.
+
+  \code{.jcache} manipulates the R-side Java object cache associated
+  with a given Java reference:
+
+  Java objects do not persist across sessions, because the Java
+  Virtual Machine (JVM) is destroyed when R is closed. All saved Java
+  object references will be restored as \code{null} references, since
+  the corresponding objects no longer exist (see R documentation on
+  serialization). However, it is possible to serialize a Java object
+  (if supported by the object) and store its serialized form in
+  R. This allows for the object to be deserialized when loaded into
+  another active session (but see notes below!)
+
+  R-side cache consists of a serialized form of the object as raw
+  vector. This cache is attached to the Java object and thus will be
+  saved when the Java object is saved. rJava provides an automated way
+  of deserializing Java references if they are \code{null} references
+  and have a cache attached. This is done on-demand basis whenever a
+  reference to a Java object is required.
+
+  Therefore packages can use \code{.jcache} to provide a way of
+  creating Java references that persist across sessions. However, they
+  must be very cautious in doing so. First, make sure the serialized
+  form is not too big. Storing whole datasets in Java serialized form
+  will hog immense amounts of memory on the R side and should be
+  avoided. In addition, be aware that the cache is just a snapshot, it
+  doesn't change when the referenced Java object is modified. Hence it
+  is most useful only for references that are not modified outside
+  R. Finally, internal references to other Java objects accessible
+  from R are not retained (see below). Most common use of
+  \code{.jcache} is with Java references that point to definitions of
+  methods (e.g., models) and other descriptive objects which are then
+  used by other, active Java classes to act upon. Caching of such
+  active objects is not a good idea, they should be instantiated by
+  functions that operate on the descriptive references instead.
+
+  \emph{Important note:} the serialization of Java references does NOT
+  take into account any dependencies on the R side. Therefore if you
+  hold a reference to a Java object in R that is also referenced by
+  the serialized Java object on the Java side, then this relationship
+  cannot be retained upon restore. Instead, two copies of disjoint
+  objects will be created which can cause confusion and errorneous
+  behavior.
+
+  The cache is attached to the reference external pointer and thus it
+  is shared with all copies of the same reference (even when changed
+  via \code{\link{.jcast}} etc.), but it is independent of other
+  references to the object obtained separately
+  (e.g., via \code{\link{.jcall}} or \code{\link{.jfield}}).
+
+  Also note that deserialization (even automated one) requires a
+  running virtual machine. Therefore you must make sure that either
+  \code{\link{.jinit}} or \code{\link{.jpackage}} is used before any
+  Java references are accessed.
+}
+%\seealso{
+%}
+%\examples{
+%\dontrun{
+%}
+%}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/jsimplify.Rd b/com.oracle.truffle.r.pkgs/rJava/man/jsimplify.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..59a8ed04624939d78d83db84ffd0566dde291749
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/jsimplify.Rd
@@ -0,0 +1,49 @@
+\name{jsimplify}
+\alias{.jsimplify}
+\title{
+  Converts Java object to a simple scalar if possible
+}
+\description{
+  \code{.jsimplify} attempts to convert Java objects that represent
+  simple scalars into corresponding scalar representation in R.
+}
+\usage{
+.jsimplify(o, promote=FALSE)
+}
+\arguments{
+  \item{o}{arbitrary object}
+  \item{promote}{logical, if \code{TRUE} then an ambiguous conversion
+  where the native type value would map to \code{NA} (e.g., Java
+  \code{int} type with value -2147483648) will be taken
+  to represent an actual value and will be promoted to a larger type
+  that can represent the value (in case of \code{int} promoted to
+  \code{double}). If \code{FALSE} then such values are assumed to
+  represent \code{NA}s.}
+}
+\value{
+  Simple scalar or \code{o} unchanged.
+}
+\details{
+  If \code{o} is not a Java object reference, \code{o} is returned
+  as-is. If \code{o} is a reference to a scalar object (such as single
+  integer, number, string or boolean) then the value of that object is
+  returned as R vector of the corresponding type and length one.
+
+  This function is used by \code{\link{.jfield}} to simplify the results
+  of field access if required.
+
+  Currently there is no function inverse to this, the usual way to wrap
+  scalar values in Java references is to use \code{\link{.jnew}} as the
+  corresponding constructor.
+}
+\seealso{
+  \code{\link{.jfield}}
+}
+\examples{
+\dontrun{
+i <- .jnew("java/lang/Integer", as.integer(10))
+print(i)
+print(.jsimplify(i))
+}
+}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/loader.Rd b/com.oracle.truffle.r.pkgs/rJava/man/loader.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..f7a8e4afebf1c8ac0bb74894bb5fd292e67ed43e
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/loader.Rd
@@ -0,0 +1,37 @@
+\name{loader}
+\alias{.jaddClassPath}
+\alias{.jclassPath}
+\title{
+  Java class loader
+}
+\description{
+  \code{.jaddClassPath} adds directories or JAR files to the class
+  path.
+
+  \code{.jclassPath} returns a vector containg the current entries in
+  the class path
+}
+\usage{
+.jaddClassPath(path)
+.jclassPath()
+}
+\arguments{
+  \item{path}{character string vector listing the paths to add to the
+    class path}
+}
+\value{
+  \code{.jclassPath} returns a character vector listing the class path sequence.
+}
+%\details{
+% 
+%}
+%\seealso{
+%  \code{\link{.jpackage}}
+%}
+\examples{
+\dontrun{
+.jaddClassPath("/my/jars/foo.jar","/my/classes/")
+print(.jclassPath())
+}
+}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/new.Rd b/com.oracle.truffle.r.pkgs/rJava/man/new.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..8d76bfbb87c99cfca54a4425ba1a0c926c1928d2
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/new.Rd
@@ -0,0 +1,33 @@
+\name{new}
+\alias{new,jclassName-method}
+\title{
+  Create a new Java object
+}
+\description{
+  Creates a new Java object and invokes the constructor with given arguments.
+}
+\section{Methods}{
+  \describe{
+    \item{\code{new}}{\code{signature(Class = "jclassName")}: ... }
+  }
+}
+\details{
+  The \code{new} method is used as the high-level API to create new
+  Java objects (for low-level access see \code{\link{.jnew}}). It
+  returns the newly created Java object.
+
+  \code{...} arguments are passed to the constructor of the class
+  specified as \code{J("class.name")}.
+}
+\seealso{
+  \code{\link{.jnew}}, \code{\link{jclassName-class}}
+}
+\examples{
+\dontrun{
+v <- new(J("java.lang.String"), "Hello World!")
+v$length()
+v$indexOf("World")
+names(v)
+}
+}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/rep.Rd b/com.oracle.truffle.r.pkgs/rJava/man/rep.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..afd95df3f6f6331770018af57e31c3938860d1a6
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/rep.Rd
@@ -0,0 +1,32 @@
+\name{rep}
+\alias{rep,jarrayRef-method}
+\alias{rep,jobjRef-method}
+\alias{rep,jrectRef-method}
+
+\title{Creates java arrays by cloning}
+\description{ 
+	Creates a java array by cloning a reference several times
+}
+\section{Methods}{
+  \describe{
+    \item{rep}{\code{signature(object = "jobjRef")}: ... }
+    \item{rep}{\code{signature(object = "jarrayRef")}: ... }
+    \item{rep}{\code{signature(object = "jrectRef")}: ... }
+  }
+}
+
+\seealso{
+  \code{\link[base]{rep}} or \code{\link{.jarray}}
+}
+
+\examples{
+\dontshow{.jinit()}
+if (!nzchar(Sys.getenv("NOAWT"))) {
+  p <- .jnew( "java.awt.Point" )
+  a <- rep( p, 10 )
+
+  stopifnot( dim(a) == c(10L ) )
+  a[[1]]$move( 10L, 50L )
+  stopifnot( a[[2]]$getX() == 0.0 )
+}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/show.Rd b/com.oracle.truffle.r.pkgs/rJava/man/show.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..4e0c5ab3607c4c31a568dc8e4c9bcdd28bdaf3ba
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/show.Rd
@@ -0,0 +1,21 @@
+\name{show}
+\alias{show,jobjRef-method}
+\alias{str,jobjRef-method}
+\alias{show,jarrayRef-method}
+\alias{show,jclassName-method}
+\title{Show a Java Object Reference}
+\description{
+  Display a Java object reference in a descriptive, textual form. The
+  default implementation calls \code{toString} Java method to obtain
+  object's printable value and uses calls \code{show} on the resulting
+  string garnished with additional details.
+}
+\section{Methods}{
+  \describe{
+    \item{show}{\code{signature(object = "jobjRef")}: ... }
+    \item{show}{\code{signature(object = "jarrayRef")}: ... }
+    \item{show}{\code{signature(object = "jclassName")}: ... }
+    \item{str}{\code{signature(object = "jobjRef")}: currently identical to show }
+  }
+}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/toJava.Rd b/com.oracle.truffle.r.pkgs/rJava/man/toJava.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..f05004b307dcc7646666405189d59f51e23c7179
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/toJava.Rd
@@ -0,0 +1,44 @@
+\name{toJava}
+\alias{toJava}
+\title{
+Convert R objects to REXP references in Java
+}
+\description{
+\code{toJava} takes an R object and creates a reference to that object
+in Java. This reference can then be passed to Java methods such taht
+they can refer to it back in R. This is commonly used to pass functions
+to Java such that Java code can call those functions later.
+}
+\usage{
+toJava(x, engine = NULL)
+}
+\arguments{
+  \item{x}{R object to reference. It can be any R object and it will be
+    retained at least for the duration of the reference on the Java side.}
+  \item{engine}{REngine in which the reference is to be created. If
+    <code>null</code> then the last created engine is used. This must be
+    a Java object and a subclass of org.rosuda.REngine (and NOT the old
+    org.rosuda.JRI.Rengine!).
+    }
+}
+%\details{
+%}
+\value{
+  There result is a Java reference (\code{jobjRef}) of the Java class
+  \code{REXPReference}.
+}
+\examples{
+\dontrun{
+  .jinit()
+  # requires JRI and REngine classes
+  .jengine(TRUE)
+  f <- function() { cat("Hello!\n"); 1 }
+  fref <- toJava(f)
+  # to use this in Java you would use something like:
+  # public static REXP call(REXPReference fn) throws REngineException, REXPMismatchException {
+  #	 return fn.getEngine().eval(new REXPLanguage(new RList(new REXP[] { fn })), null, false);
+  # }
+  # .jcall("Call","Lorg/rosuda/REngine/REXP;","call", fref)
+  }
+}
+\keyword{interface}
diff --git a/com.oracle.truffle.r.pkgs/rJava/man/with.Rd b/com.oracle.truffle.r.pkgs/rJava/man/with.Rd
new file mode 100644
index 0000000000000000000000000000000000000000..86c5e301d585d8a99dc80f28961de14c38563366
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/man/with.Rd
@@ -0,0 +1,106 @@
+\name{with.jobjRef}
+\alias{with.jobjRef}
+\alias{within.jobjRef}
+\alias{with.jarrayRef}
+\alias{within.jarrayRef}
+\alias{with.jclassName}
+\alias{within.jclassName}
+\title{
+with and within methods for Java objects and class names
+}
+\description{
+Convenience wrapper that allow calling methods of 
+Java object and classes from within the object (or class).
+}
+\usage{
+\S3method{with}{jobjRef}(data, expr, ...)
+\S3method{within}{jobjRef}(data, expr, ...)
+
+\S3method{with}{jarrayRef}(data, expr, ...)
+\S3method{within}{jarrayRef}(data, expr, ...)
+
+\S3method{with}{jclassName}(data, expr, ...)
+\S3method{within}{jclassName}(data, expr, ...)
+}
+\arguments{
+ \item{data}{
+ A Java object reference or a java class name. See \code{\link{J}}
+}
+ \item{expr}{
+R expression to evaluate
+}
+ \item{\dots}{
+ignored
+}
+}
+\details{
+The expression is evaluated in an environment 
+that contains a mapping between the public fields 
+and methods of the object. 
+
+The methods of the object are mapped to standard R functions
+in the environment. In case of classes, only static methods
+are used.
+
+The fields of the object are mapped to active bindings
+(see \link{makeActiveBinding}) so that they can be accessed
+and modified from within the environment. For classes, only 
+static fields are used.
+}
+\value{
+	\code{with} returns the value of the expression and 
+	\code{within} returns the \code{data} argument
+}
+\author{
+Romain Francois <francoisromain@free.fr>
+}
+\references{
+	the \code{java.lang.reflect} package: 
+	\url{http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/package-summary.html}
+}
+\examples{
+\dontshow{.jinit()}
+
+if (!nzchar(Sys.getenv("NOAWT"))) {
+  p <- .jnew( "java/awt/Point", 0L, 0L )
+  with( p, {
+	# x and y and now 0
+	move( 10L, 10L )
+	# x and y are now 10
+	x <- x + y
+  } )
+
+  f <- within( .jnew( "javax/swing/JFrame" ) , {
+	layout <- .jnew( "java/awt/BorderLayout" )
+	setLayout( layout )
+	add( .jnew( "javax/swing/JLabel", "north" ), layout$NORTH )
+	add( .jnew( "javax/swing/JLabel", "south" ), layout$SOUTH )
+	add( .jnew( "javax/swing/JLabel", "west" ), layout$WEST )
+	add( .jnew( "javax/swing/JLabel", "east" ), layout$EAST )
+	setSize( .jnew( "java/awt/Dimension", 400L, 400L ) )
+	setVisible( TRUE )
+  } )
+}
+
+Double <- J("java.lang.Double")
+with( Double, MIN_VALUE )
+with( Double, parseDouble( "10.2" ) )
+
+\dontrun{
+# inner class example
+% TODO: find a better example
+HashMap <- J("java.util.HashMap")
+with( HashMap, new( SimpleEntry, "key", "value" ) )
+with( HashMap, SimpleEntry )
+}
+
+with( J("java.lang.System"), getProperty("java.home") )
+
+\dontshow{
+stopifnot( with( Double, parseDouble("10.0") ) == 10.0 )
+d <- new( Double, "10.0") 
+stopifnot( with( d, doubleValue() ) == 10.0 )
+}
+
+}
+\keyword{ classes }
diff --git a/com.oracle.truffle.r.pkgs/rJava/mkdist b/com.oracle.truffle.r.pkgs/rJava/mkdist
new file mode 100644
index 0000000000000000000000000000000000000000..9466475aa63ac80f34f61d122ebabbd963a51aa0
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/mkdist
@@ -0,0 +1,201 @@
+#!/bin/sh
+
+# to locate JRI the following sequence is used:
+#  - ${JRI}
+#  - ${ORGPATH}/rosuda/JRI (if ORGPATH is set)
+#  - ../../../org/rosuda/JRI
+
+if [ "$1" = "-h" ]; then
+    echo ''
+    echo " Usage: $0 [-c|-h]"
+    echo ''
+    echo ' Options: -c  clean dist (remove all generated files first)'
+    echo '          -h  this help screen'
+    echo ''
+    exit 0
+fi
+
+SWD=`pwd`
+echo "Removing previous dist ..."
+rm -rf /tmp/rJava
+mkdir /tmp/rJava
+echo "Copying package base ..."
+cp -r . /tmp/rJava
+
+if [ -e "${SWD}/jri/mkdist" ]; then
+    JRI="${SWD}/jri"
+    rm -rf /tmp/rJava/jri
+    echo "Embedded JRI: ${JRI}"
+fi
+
+rm /tmp/rJava/mkdist
+rm -f /tmp/rJava/*~ /tmp/rJava/R/*~ /tmp/rJava/src/*~ /tmp/rJava/man/*~
+rm -rf /tmp/rJava/aclo* /tmp/rJava/autom*
+
+## remove GH README
+rm -f /tmp/rJava/README.md
+
+cd /tmp/rJava
+
+if [ "$1" = "-c" ]; then
+    rm -f configure install-sh jri/configure
+fi
+
+if [ -e /tmp/rJava/configure ]; then
+    echo "Note: autoreconf is *not* ran automatically if configure exists."
+    echo "      Run it manually if necessary."
+else 
+    echo "Running autoreconf ..."
+    autoreconf
+    rm -rf autom4te* acloc*
+fi
+
+if [ ! -e install-sh ]; then
+    echo "Fetching install-sh ..."
+    ams=/usr/share/automake/install-sh
+    if [ ! -e $ams ]; then
+	ams=`ls /usr/share/automake*/install*sh|tail -n 1`
+    fi
+    if [ -z "$ams" -o ! -e "$ams" ]; then
+	echo "*** ERROR: install-sh is not present and I can't find it in /usr/share"
+	exit 2
+    fi
+    cp $ams install-sh
+fi
+
+if [ ! -e getsp.class ]; then
+    echo "Compiling getsp.class"
+    javac -target 1.2 -source 1.2 getsp.java
+fi
+
+echo "Removing CVS/SVN and backup files ..."
+rm -rf `find . -name CVS -or -name .svn -or -name \*~`
+
+## since we merged JRI and rJava trees we no longer support ORG builds
+if [ ! -e jri/configure ]; then
+    if [ -e "${SWD}/jri/mkdist" ]; then
+	DEFAULTJRI="${SWD}/jri"
+    fi
+    : ${JRI=$DEFAULTJRI}
+    if [ ! -e "$JRI" ]; then
+	echo "*** ERROR: JRI dist is not in the jri subdirectory and JRI env var is not set!"
+	echo " Please set JRI to point to JRI sources or unpack JRI dist into the jri directory"
+	echo ""
+	echo " When using GIT, don't forget to use git clone --recursive"
+	exit 1
+    fi
+    if [ -e $JRI/mkdist ]; then
+	echo "Building JRI dist to include ..."
+	rm -rf /tmp/JRI_*
+	mywd=`pwd`
+	cd $JRI
+	sh mkdist
+	cd /tmp/rJava
+	jf=`ls /tmp/JRI_*|sed -n -e 1p`;
+	if [ -z "$jf" -o ! -e "$jf" ]; then
+	    echo "*** ERROR: Cannot get JRI distro!"
+	    exit 1
+	fi
+	rm -rf jri JRI ${SWD}/JRI_*
+	#mkdir jri 2> /dev/null > /dev/null
+	cd /tmp/rJava
+	tar fvxz $jf
+    else
+	tar fxz $JRI
+    fi
+    if [ -e jri/JRI ]; then
+	rm -rf 1
+	mv jri 1
+	mv 1/JRI jri
+	rm -rf 1
+    fi
+    if [ ! -e jri/Makefile.in ]; then
+	if [ -e JRI/Makefile.in ]; then
+	    mv JRI jri
+	else
+	    echo "*** ERROR: jri is not correctly set up."
+	    exit 1
+	fi
+    fi
+    if [ -e jri/Makefile.in -a -e JRI/Makefile.in ]; then
+	# case-insensitive fs - but we need lower case *sigh*
+	mv JRI 1
+	mv 1 jri
+    fi
+fi
+
+DEFAULTRENG="${SWD}/jri/REngine"
+if [ ! -e "$DEFAULTRENG/Makefile" ]; then
+    echo "*** WARNING *** cannot find REngine sources, the distribution will NOT include REngine!"
+else
+    (cd "$DEFAULTRENG"; make clean; make)
+    if [ ! -e "$DEFAULTRENG/REngine.jar" ]; then
+	echo "*** ERROR *** cannot compile REngine API"
+	exit 1
+    fi
+    (cd "$DEFAULTRENG/JRI" && make)
+    if [ ! -e "$DEFAULTRENG/JRI/JRIEngine.jar" ]; then
+	echo "*** ERROR *** cannot compile JRI part of the REngine API"
+	exit 1
+    fi
+    ## create JRIEngine that contains really just the JRIEngine and not JRI since that will be installed separately
+    (cd "$DEFAULTRENG/JRI" && jar fc JRIEngine.jar org/rosuda/REngine/JRI)
+    mkdir -p /tmp/rJava/inst/jri 2>/dev/null
+    cp "$DEFAULTRENG/REngine.jar" "$DEFAULTRENG/JRI/JRIEngine.jar" /tmp/rJava/inst/jri
+    (cd "$DEFAULTRENG/JRI" && make clean)
+fi
+
+
+#cd ..
+#echo "Updating INDEX ..."
+# R CMD Rdindex rJava > rJava/INDEX
+#echo "library(tools)\nsink(\"rJava/INDEX\")\nRdindex(\"rJava/man\")\nsink()" | R --vanilla > /dev/null
+
+echo "Compile Java classes ..."
+cd /tmp/rJava
+mkdir -p inst/java/boot
+# compile all java classes
+cd src/java
+make clean
+make compile
+echo "Generate javadoc documentation"
+make javadoc
+cd ../..
+echo "Copy compiled Java classes ..."
+# copy all complied Java classes and sources
+cp src/java/*.class inst/java
+cp src/java/*.java inst/java
+# move RJavaClassLoader into boot area since it will be loaded by the system class loader
+mv inst/java/RJavaClassLoader* inst/java/boot
+# move javadoc directory
+mv src/java/javadoc inst/javadoc
+
+echo "Updating version ..."
+cd /tmp/rJava
+VER=`sed -n -e 's/.*rJava v\([0-9.-]\{1,\}\).*/\1/p' src/rJava.h`
+echo "rJava version ${VER}"
+cat DESCRIPTION| sed "s/Version:.*/Version: ${VER}/" > d
+mv d DESCRIPTION
+rm -rf tests
+if test -n "${OPTIMIZED}"; then
+    echo "Creating optimized sources ..."
+    echo '#define ONEFILE 1' > src/all
+    for f in `ls src/*.c`; do
+	echo "#line 1 \"$f\"" >> src/all
+	cat $f >> src/all
+	echo '' >> src/all
+    done
+    rm src/*.c
+    mv src/all src/rJava.c
+fi
+
+echo "Creating package ..."
+cd ..
+rm -f `find rJava -name ._\*`
+rm -rf rJava/.git rJava/jri/REngine/.git
+R CMD build rJava
+cd ${SWD}
+cp /tmp/rJava_${VER}.tar.gz ..
+rm -rf /tmp/rJava
+echo "Done."
+ls -l ../rJava_${VER}.tar.gz
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/Makevars b/com.oracle.truffle.r.pkgs/rJava/src/Makevars
new file mode 100644
index 0000000000000000000000000000000000000000..9df7b0d2380b7245c25b6078aa5b03550f1ec8c6
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/Makevars
@@ -0,0 +1,17 @@
+# we need to add JNI specific stuff here
+PKG_CPPFLAGS=-I. -I/Library/Java/JavaVirtualMachines/labsjdk1.8.0_121-jvmci-0.29//include -I/Library/Java/JavaVirtualMachines/labsjdk1.8.0_121-jvmci-0.29//include/darwin
+PKG_LIBS=-L/Library/Java/JavaVirtualMachines/labsjdk1.8.0_121-jvmci-0.29/jre/lib/server -ljvm
+JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_122.jdk/Contents/Home/
+# make SHLIB believe that we know better what the objects are
+#OBJECTS=Rglue.o callJNI.o initJNI.o rJava.o jri.o jri_glue.o
+
+all: $(SHLIB) # jri
+
+.PHONY: all
+
+# this is a hack to force SHLIB to run our sub-make
+jri:
+	(cd ../jri && $(MAKE))
+	-@mkdir -p ../inst/jri
+	@(cp -r ../jri/src/JRI.jar ../jri/*jri.* ../jri/run ../jri/examples ../inst/jri/)
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/Makevars.in b/com.oracle.truffle.r.pkgs/rJava/src/Makevars.in
new file mode 100644
index 0000000000000000000000000000000000000000..e87396c52b537122946dc5bb0a731b96f859d028
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/Makevars.in
@@ -0,0 +1,17 @@
+# we need to add JNI specific stuff here
+PKG_CPPFLAGS=-I. @JAVA_CPPFLAGS@
+PKG_LIBS=@JAVA_LIBS@
+JAVA_HOME=@JAVA_HOME@
+# make SHLIB believe that we know better what the objects are
+#OBJECTS=Rglue.o callJNI.o initJNI.o rJava.o jri.o jri_glue.o
+
+all: $(SHLIB) @WANT_JRI_TRUE@ jri
+
+.PHONY: all
+
+# this is a hack to force SHLIB to run our sub-make
+jri:
+	(cd ../jri && $(MAKE))
+	-@mkdir -p ../inst/jri
+	@(cp -r ../jri/src/JRI.jar ../jri/*jri.* ../jri/run ../jri/examples ../inst/jri/)
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/Makevars.win b/com.oracle.truffle.r.pkgs/rJava/src/Makevars.win
new file mode 100644
index 0000000000000000000000000000000000000000..0b28d1bf04fce3bdc89c047bdbeff16aff67cab0
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/Makevars.win
@@ -0,0 +1,29 @@
+# To compile the Windows version, you need to:
+# - set JAVA_HOME to the JDK root (used for includes only)
+# in addition if the pre-compiled stuff is not present, then also:
+# - generate libjvm.dll.a from JDK's jvm.dll
+#   (run `make' in `jvm-w32')
+# - copy WinRegistry.dll into inst/libs
+
+# You can modify the following line as the unlima ratio fallback.
+# Shouldn't be necessary, because JAVA_HOME and autodetection
+# have higher precedence.
+DEFAULT_JAVA_HOME=C:\\jdk1.4.2_04
+
+# this file is generated by configure.win and honors JAVA_HOME env.var
+-include Makevars.java
+
+ifeq ($(JAVA_HOME),)
+JAVA_HOME:=$(DEFAULT_JAVA_HOME)
+endif
+
+$(warning JAVA_HOME is $(JAVA_HOME))
+
+# normally you don't have to touch this unless you want to add
+# debugging flags like -DRJ_DEBUG or -DRJ_PROFILE to PKG_CFLAGS
+JAVA_INCLUDES=$(JAVA_HOME)/include $(JAVA_HOME)/include/win32
+PKG_CPPFLAGS = -D_R_ -DWin32 -Ijvm-w32 -I$(RHOME)/src/include $(JAVA_INCLUDES:%=-I%)
+PKG_LIBS = -Ljvm-w32 -ljvm.dll
+
+$(warning PKG_CPPFLAGS are $(PKG_CPPFLAGS))
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/Rglue.c b/com.oracle.truffle.r.pkgs/rJava/src/Rglue.c
new file mode 100644
index 0000000000000000000000000000000000000000..22466806024b0e39284453e8944cd1124cd9b1b4
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/Rglue.c
@@ -0,0 +1,1079 @@
+#define USE_RINTERNALS 1
+#include "rJava.h"
+#include <R.h>
+#include <Rdefines.h>
+#include <R_ext/Parse.h>
+#include <R_ext/Print.h>
+
+#include <stdarg.h>
+
+/* max supported # of parameters to Java methdos */
+#ifndef maxJavaPars
+#define maxJavaPars 32
+#endif
+
+/* pre-2.4 have no S4SXP but used VECSXP instead */
+#ifndef S4SXP
+#define S4SXP VECSXP
+#endif
+
+/** returns TRUE if JRI has callback support compiled in or FALSE otherwise */
+REPC SEXP RJava_has_jri_cb() {
+  SEXP r = allocVector(LGLSXP, 1);
+#ifdef ENABLE_JRICB
+  LOGICAL(r)[0] = 1;
+#else
+  LOGICAL(r)[0] = 0;
+#endif
+  return r;
+} 
+
+/* debugging output (enable with -DRJ_DEBUG) */
+#ifdef RJ_DEBUG
+HIDE void rjprintf(char *fmt, ...) {
+  va_list v;
+  va_start(v,fmt);
+  Rvprintf(fmt,v);
+  va_end(v);
+}
+/* we can't assume ISO C99 (variadic macros), so we have to use one more level of wrappers */
+#define _dbg(X) X
+#else
+#define _dbg(X)
+#endif
+
+/* profiling code (enable with -DRJ_PROFILE) */
+#ifdef RJ_PROFILE
+#include <sys/time.h>
+
+HIDE long time_ms() {
+#ifdef Win32
+  return 0; /* in Win32 we have no gettimeofday :( */
+#else
+  struct timeval tv;
+  gettimeofday(&tv,0);
+  return (tv.tv_usec/1000)+(tv.tv_sec*1000);
+#endif
+}
+
+static long profilerTime;
+
+#define profStart() profilerTime=time_ms()
+HIDE void profReport(char *fmt, ...) {
+  long npt=time_ms();
+  va_list v;
+  va_start(v,fmt);
+  Rvprintf(fmt,v);
+  va_end(v);
+  Rprintf(" %ld ms\n",npt-profilerTime);
+  profilerTime=npt;
+}
+#define _prof(X) X
+#else
+#define profStart()
+#define _prof(X)
+#endif
+
+static void JRefObjectFinalizer(SEXP ref) {
+    if (java_is_dead) return;
+
+  if (TYPEOF(ref)==EXTPTRSXP) {
+    JNIEnv *env=getJNIEnv();
+    jobject o = R_ExternalPtrAddr(ref);
+
+#ifdef RJ_DEBUG
+    {
+      jstring s=callToString(env, o);
+      const char *c="???";
+      if (s) c=(*env)->GetStringUTFChars(env, s, 0);
+      _dbg(rjprintf("Finalizer releases Java object [%s] reference %lx (SEXP@%lx)\n", c, (long)o, (long)ref));
+      if (s) {
+	(*env)->ReleaseStringUTFChars(env, s, c);
+	releaseObject(env, s);
+      }
+    }
+#endif
+
+    if (env && o) {
+      /* _dbg(rjprintf("  finalizer releases global reference %lx\n", (long)o);) */
+      _mp(MEM_PROF_OUT("R %08x FIN\n", (int)o))
+      releaseGlobal(env, o);
+    }
+  }
+}
+
+/* jobject to SEXP encoding - 0.2 and earlier use INTSXP */
+SEXP j2SEXP(JNIEnv *env, jobject o, int releaseLocal) {
+  if (!env) error("Invalid Java environment in j2SEXP");
+  if (o) {
+    jobject go = makeGlobal(env, o);
+    _mp(MEM_PROF_OUT("R %08x RNEW %08x\n", (int) go, (int) o))
+    if (!go)
+      error("Failed to create a global reference in Java.");
+    _dbg(rjprintf(" j2SEXP: %lx -> %lx (release=%d)\n", (long)o, (long)go, releaseLocal));
+    if (releaseLocal)
+      releaseObject(env, o);
+    o=go;
+  }
+  
+  {
+    SEXP xp = R_MakeExternalPtr(o, R_NilValue, R_NilValue);
+
+#ifdef RJ_DEBUG
+    {
+      JNIEnv *env=getJNIEnv();
+      jstring s=callToString(env, o);
+      const char *c="???";
+      if (s) c=(*env)->GetStringUTFChars(env, s, 0);
+      _dbg(rjprintf("New Java object [%s] reference %lx (SEXP@%lx)\n", c, (long)o, (long)xp));
+      if (s) {
+	(*env)->ReleaseStringUTFChars(env, s, c);
+	releaseObject(env, s);
+      }
+    }
+#endif
+
+    R_RegisterCFinalizerEx(xp, JRefObjectFinalizer, TRUE);
+    return xp;
+  }
+}
+
+#if R_VERSION >= R_Version(2,7,0)
+/* returns string from a CHARSXP making sure that the result is in UTF-8 */
+const char *rj_char_utf8(SEXP s) {
+	if (Rf_getCharCE(s) == CE_UTF8) return CHAR(s);
+	return Rf_reEnc(CHAR(s), getCharCE(s), CE_UTF8, 0); /* subst. invalid chars: 1=hex, 2=., 3=?, other=skip */
+}
+#endif
+
+HIDE void deserializeSEXP(SEXP o) {
+  _dbg(rjprintf("attempt to deserialize %p (clCL=%p, oCL=%p)\n", o, clClassLoader, oClassLoader));
+  SEXP s = EXTPTR_PROT(o);
+  if (TYPEOF(s) == RAWSXP && EXTPTR_PTR(o) == NULL) {
+    JNIEnv *env = getJNIEnv();
+    if (env && clClassLoader && oClassLoader) {
+      jbyteArray ser = newByteArray(env, RAW(s), LENGTH(s));
+      if (ser) {
+	jmethodID mid = (*env)->GetMethodID(env, clClassLoader, "toObject", "([B)Ljava/lang/Object;");
+	if (mid) {
+	  jobject res = (*env)->CallObjectMethod(env, oClassLoader, mid, ser);
+	  if (res) {
+	    jobject go = makeGlobal(env, res);
+	    _mp(MEM_PROF_OUT("R %08x RNEW %08x\n", (int) go, (int) res))
+	    if (go) {
+	      _dbg(rjprintf(" - succeeded: %p\n", go));
+	      /* set the deserialized object */
+	      EXTPTR_PTR(o) = (SEXP) go;
+	      /* Note: currently we don't remove the serialized content, because it was created explicitly using .jcache to allow repeated saving. Once this is handled by a hook, we shall remove it. However, to assure compatibility TAG is always NULL for now, so we do clear the cache if TAG is non-null for future use. */
+	      if (EXTPTR_TAG(o) != R_NilValue) {
+		/* remove the serialized raw vector */
+		SETCDR(o, R_NilValue); /* Note: this is abuse of the API since it uses the fact that PROT is stored in CDR */
+	      }
+	    }
+	  }
+	}
+	releaseObject(env, ser);
+      }
+    }    
+  }
+}
+
+#define addtmpo(T, X) { jobject _o = X; if (_o) { _dbg(rjprintf(" parameter to release later: %lx\n", (unsigned long) _o)); *T=_o; T++;} }
+#define fintmpo(T) { *T = 0; }
+
+/* concatenate a string to a signature buffer increasing it as necessary */
+static void strcats(sig_buffer_t *sig, const char *add) {
+  int l = strlen(add);
+  int al = sig->len;
+  if (al + l >= sig->maxsig - 1) {
+    sig->maxsig += 8192;
+    if (sig->sig == sig->sigbuf) { /* first-time allocation */
+      char *ns = (char*) malloc(sig->maxsig);
+      memcpy(ns, sig->sig, al + 1);
+      sig->sig = ns;
+    } else /* re-allocation */
+      sig->sig = (char*) realloc(sig->sig, sig->maxsig);
+  }
+  strcpy(sig->sig + al, add);
+  sig->len += l;
+}
+
+/* initialize a signature buffer */
+HIDE void init_sigbuf(sig_buffer_t *sb) {
+  sb->len = 0;
+  sb->maxsig = sizeof(sb->sigbuf);
+  sb->sig = sb->sigbuf;
+}
+
+/* free the content of a signature buffer (if necessary) */
+HIDE void done_sigbuf(sig_buffer_t *sb) { 
+  if (sb->sig != sb->sigbuf) free(sb->sig);
+}
+
+/** converts parameters in SEXP list to jpar and sig.
+    since 0.4-4 we ignore named arguments in par
+*/
+static int Rpar2jvalue(JNIEnv *env, SEXP par, jvalue *jpar, sig_buffer_t *sig, int maxpars, jobject *tmpo) {
+  SEXP p=par;
+  SEXP e;
+  int jvpos=0;
+  int i=0;
+
+  while (p && TYPEOF(p)==LISTSXP && (e=CAR(p))) {
+    /* skip all named arguments */
+    if (TAG(p) && TAG(p)!=R_NilValue) { p=CDR(p); continue; };
+
+    if (jvpos >= maxpars) {
+	if (maxpars == maxJavaPars)
+	    Rf_error("Too many arguments in Java call. maxJavaPars is %d, recompile rJava with higher number if needed.", maxJavaPars);
+	break;
+    }
+    
+    _dbg(rjprintf("Rpar2jvalue: par %d type %d\n",i,TYPEOF(e)));
+    if (TYPEOF(e)==STRSXP) {
+      _dbg(rjprintf(" string vector of length %d\n",LENGTH(e)));
+      if (LENGTH(e)==1) {
+	  SEXP sv = STRING_ELT(e, 0);
+	  strcats(sig,"Ljava/lang/String;");
+	  if (sv == R_NaString) {
+	      addtmpo(tmpo, jpar[jvpos++].l = 0);
+	  } else {
+	      addtmpo(tmpo, jpar[jvpos++].l = newString(env, CHAR_UTF8(sv)));
+	  }
+      } else {
+	  int j = 0;
+	  jobjectArray sa = (*env)->NewObjectArray(env, LENGTH(e), javaStringClass, 0);
+	  _mp(MEM_PROF_OUT("  %08x LNEW string[%d]\n", (int) sa, LENGTH(e)))
+	  if (!sa) {
+	      fintmpo(tmpo);
+	      error("unable to create string array.");
+	      return -1;
+	  }
+	  addtmpo(tmpo, sa);
+	  while (j < LENGTH(e)) {
+	      SEXP sv = STRING_ELT(e,j);
+	      if (sv == R_NaString) {
+	      } else {
+		  jobject s = newString(env, CHAR_UTF8(sv));
+		  _dbg(rjprintf (" [%d] \"%s\"\n",j,CHAR_UTF8(sv)));
+		  (*env)->SetObjectArrayElement(env, sa, j, s);
+		  if (s) releaseObject(env, s);
+	      }
+	      j++;
+	  }
+	  jpar[jvpos++].l = sa;
+	  strcats(sig,"[Ljava/lang/String;");
+      }
+    } else if (TYPEOF(e)==RAWSXP) {
+      _dbg(rjprintf(" raw vector of length %d\n", LENGTH(e)));
+      strcats(sig,"[B");
+      addtmpo(tmpo, jpar[jvpos++].l=newByteArray(env, RAW(e), LENGTH(e)));
+    } else if (TYPEOF(e)==INTSXP) {
+      _dbg(rjprintf(" integer vector of length %d\n",LENGTH(e)));
+      if (LENGTH(e)==1) {
+	if (inherits(e, "jbyte")) {
+	  _dbg(rjprintf("  (actually a single byte 0x%x)\n", INTEGER(e)[0]));
+	  jpar[jvpos++].b=(jbyte)(INTEGER(e)[0]);
+	  strcats(sig,"B");
+	} else if (inherits(e, "jchar")) {
+	  _dbg(rjprintf("  (actually a single character 0x%x)\n", INTEGER(e)[0]));
+	  jpar[jvpos++].c=(jchar)(INTEGER(e)[0]);
+	  strcats(sig,"C");
+	} else if (inherits(e, "jshort")) {
+	  _dbg(rjprintf("  (actually a single short 0x%x)\n", INTEGER(e)[0]));
+	  jpar[jvpos++].s=(jshort)(INTEGER(e)[0]);
+	  strcats(sig,"S");
+	} else {
+	  strcats(sig,"I");
+	  jpar[jvpos++].i=(jint)(INTEGER(e)[0]);
+	  _dbg(rjprintf("  single int orig=%d, jarg=%d [jvpos=%d]\n",
+		   (INTEGER(e)[0]),
+		   jpar[jvpos-1],
+		   jvpos));
+	}
+      } else {
+	if (inherits(e, "jbyte")) {
+	  strcats(sig,"[B");
+	  addtmpo(tmpo, jpar[jvpos++].l=newByteArrayI(env, INTEGER(e), LENGTH(e)));
+	} else if (inherits(e, "jchar")) {
+	  strcats(sig,"[C");
+	  addtmpo(tmpo, jpar[jvpos++].l=newCharArrayI(env, INTEGER(e), LENGTH(e)));
+	} else if (inherits(e, "jshort")) {
+	  strcats(sig,"[S");
+	  addtmpo(tmpo, jpar[jvpos++].l=newShortArrayI(env, INTEGER(e), LENGTH(e)));
+	} else {
+	  strcats(sig,"[I");
+	  addtmpo(tmpo, jpar[jvpos++].l=newIntArray(env, INTEGER(e), LENGTH(e)));
+	}
+      }
+    } else if (TYPEOF(e)==REALSXP) {
+      if (inherits(e, "jfloat")) {
+	_dbg(rjprintf(" jfloat vector of length %d\n", LENGTH(e)));
+	if (LENGTH(e)==1) {
+	  strcats(sig,"F");
+	  jpar[jvpos++].f=(jfloat)(REAL(e)[0]);
+	} else {
+	  strcats(sig,"[F");
+	  addtmpo(tmpo, jpar[jvpos++].l=newFloatArrayD(env, REAL(e),LENGTH(e)));
+	}
+      } else if (inherits(e, "jlong")) {
+	_dbg(rjprintf(" jlong vector of length %d\n", LENGTH(e)));
+	if (LENGTH(e)==1) {
+	  strcats(sig,"J");
+	  jpar[jvpos++].j=(jlong)(REAL(e)[0]);
+	} else {
+	  strcats(sig,"[J");
+	  addtmpo(tmpo, jpar[jvpos++].l=newLongArrayD(env, REAL(e),LENGTH(e)));
+	}
+      } else {
+	_dbg(rjprintf(" real vector of length %d\n",LENGTH(e)));
+	if (LENGTH(e)==1) {
+	  strcats(sig,"D");
+	  jpar[jvpos++].d=(jdouble)(REAL(e)[0]);
+	} else {
+	  strcats(sig,"[D");
+	  addtmpo(tmpo, jpar[jvpos++].l=newDoubleArray(env, REAL(e),LENGTH(e)));
+	}
+      }
+    } else if (TYPEOF(e)==LGLSXP) {
+      _dbg(rjprintf(" logical vector of length %d\n",LENGTH(e)));
+      if (LENGTH(e)==1) {
+	strcats(sig,"Z");
+	jpar[jvpos++].z=(jboolean)(LOGICAL(e)[0]);
+      } else {
+	strcats(sig,"[Z");
+	addtmpo(tmpo, jpar[jvpos++].l=newBooleanArrayI(env, LOGICAL(e),LENGTH(e)));
+      }
+    } else if (TYPEOF(e)==VECSXP || TYPEOF(e)==S4SXP) {
+      _dbg(rjprintf(" generic vector of length %d\n", LENGTH(e)));
+      if (IS_JOBJREF(e)) {
+	jobject o=(jobject)0;
+	const char *jc=0;
+	SEXP n=getAttrib(e, R_NamesSymbol);
+	if (TYPEOF(n)!=STRSXP) n=0;
+	_dbg(rjprintf(" which is in fact a Java object reference\n"));
+	if (TYPEOF(e)==VECSXP && LENGTH(e)>1) { /* old objects were lists */
+	  fintmpo(tmpo);
+	  error("Old, unsupported S3 Java object encountered.");
+	} else { /* new objects are S4 objects */
+	  SEXP sref, sclass;
+	  sref=GET_SLOT(e, install("jobj"));
+	  if (sref && TYPEOF(sref)==EXTPTRSXP) {
+	    jverify(sref);
+	    o = (jobject)EXTPTR_PTR(sref);
+	  } else /* if jobj is anything else, assume NULL ptr */
+	    o=(jobject)0;
+	  sclass=GET_SLOT(e, install("jclass"));
+	  if (sclass && TYPEOF(sclass)==STRSXP && LENGTH(sclass)==1)
+	    jc=CHAR_UTF8(STRING_ELT(sclass,0));
+	  if (IS_JARRAYREF(e) && jc && !*jc) {
+	    /* if it's jarrayRef with jclass "" then it's an uncast array - use sig instead */
+	    sclass=GET_SLOT(e, install("jsig"));
+	    if (sclass && TYPEOF(sclass)==STRSXP && LENGTH(sclass)==1)
+	      jc=CHAR_UTF8(STRING_ELT(sclass,0));
+	  }
+	}
+	if (jc) {
+	  if (*jc!='[') { /* not an array, we assume it's an object of that class */
+	    strcats(sig,"L"); strcats(sig,jc); strcats(sig,";");
+	  } else /* array signature is passed as-is */
+	    strcats(sig,jc);
+	} else
+	  strcats(sig,"Ljava/lang/Object;");
+	jpar[jvpos++].l=o;
+      } else {
+	_dbg(rjprintf(" (ignoring)\n"));
+      }
+    }
+    i++;
+    p=CDR(p);
+  }
+  fintmpo(tmpo);
+  return jvpos;
+}
+
+/** free parameters that were temporarily allocated */
+static void Rfreejpars(JNIEnv *env, jobject *tmpo) {
+  if (!tmpo) return;
+  while (*tmpo) {
+    _dbg(rjprintf("Rfreepars: releasing %lx\n", (unsigned long) *tmpo));
+    releaseObject(env, *tmpo);
+    tmpo++;
+  }
+}
+
+/** map one parameter into jvalue and determine its signature (unused in fields.c) */
+HIDE jvalue R1par2jvalue(JNIEnv *env, SEXP par, sig_buffer_t *sig, jobject *otr) {
+  jobject tmpo[4] = {0, 0};
+  jvalue v[4];
+  int p = Rpar2jvalue(env, CONS(par, R_NilValue), v, sig, 2, tmpo);
+  /* this should never happen, but just in case - we can only assume responsibility for one value ... */
+  if (p != 1 || (tmpo[0] && tmpo[1])) {
+    Rfreejpars(env, tmpo);
+    error("invalid parameter");
+  }
+  *otr = *tmpo;
+  return *v;
+}
+
+/** call specified non-static method on an object
+   object (int), return signature (string), method name (string) [, ..parameters ...]
+   arrays and objects are returned as IDs (hence not evaluated)
+*/
+REPE SEXP RcallMethod(SEXP par) {
+  SEXP p = par, e;
+  sig_buffer_t sig;
+  jvalue jpar[maxJavaPars];
+  jobject tmpo[maxJavaPars+1];
+  jobject o = 0;
+  const char *retsig, *mnam, *clnam = 0;
+  jmethodID mid = 0;
+  jclass cls;
+  JNIEnv *env = getJNIEnv();
+  
+  profStart();
+  p=CDR(p); e=CAR(p); p=CDR(p);
+  if (e==R_NilValue) 
+    error_return("RcallMethod: call on a NULL object");
+  if (TYPEOF(e)==EXTPTRSXP) {
+    jverify(e);
+    o = (jobject)EXTPTR_PTR(e);
+  } else if (TYPEOF(e)==STRSXP && LENGTH(e)==1)
+    clnam = CHAR_UTF8(STRING_ELT(e, 0));
+  else
+    error_return("RcallMethod: invalid object parameter");
+  if (!o && !clnam)
+    error_return("RcallMethod: attempt to call a method of a NULL object.");
+#ifdef RJ_DEBUG
+  {
+    SEXP de=CAR(CDR(p));
+    rjprintf("RcallMethod (env=%x):\n",env);
+    if (TYPEOF(de)==STRSXP && LENGTH(de)>0)
+      rjprintf(" method to call: %s on object 0x%x or class %s\n",CHAR_UTF8(STRING_ELT(de,0)),o,clnam);
+  }
+#endif
+  if (clnam)
+    cls = findClass(env, clnam, oClassLoader);
+  else
+    cls = objectClass(env,o);
+  if (!cls)
+    error_return("RcallMethod: cannot determine object class");
+#ifdef RJ_DEBUG
+  rjprintf(" class: "); printObject(env, cls);
+#endif
+  e=CAR(p); p=CDR(p);
+  if (TYPEOF(e)==STRSXP && LENGTH(e)==1) { /* signature */
+    retsig=CHAR_UTF8(STRING_ELT(e,0));
+    /*
+      } else if (inherits(e, "jobjRef")) { method object 
+    SEXP mexp = GET_SLOT(e, install("jobj"));
+    jobject mobj = (jobject)(INTEGER(mexp)[0]);
+    _dbg(rjprintf(" signature is Java object %x - using reflection\n", mobj);
+    mid = (*env)->FromReflectedMethod(*env, jobject mobj);
+    retsig = getReturnSigFromMethodObject(mobj);
+    */
+  } else error_return("RcallMethod: invalid return signature parameter");
+    
+  e=CAR(p); p=CDR(p);
+  if (TYPEOF(e)!=STRSXP || LENGTH(e)!=1)
+    error_return("RcallMethod: invalid method name");
+  mnam = CHAR_UTF8(STRING_ELT(e,0));
+  init_sigbuf(&sig);
+  strcats(&sig, "(");
+  Rpar2jvalue(env, p, jpar, &sig, maxJavaPars, tmpo);
+  strcats(&sig, ")");
+  strcats(&sig, retsig);
+  _dbg(rjprintf(" method \"%s\" signature is %s\n", mnam, sig.sig));
+  mid=o?
+    (*env)->GetMethodID(env, cls, mnam, sig.sig):
+    (*env)->GetStaticMethodID(env, cls, mnam, sig.sig);
+  if (!mid && o) { /* try static method as a fall-back */
+    checkExceptionsX(env, 1);
+    o = 0;
+    mid = (*env)->GetStaticMethodID(env, cls, mnam, sig.sig);
+  }
+  if (!mid) {
+    checkExceptionsX(env, 1);
+    Rfreejpars(env, tmpo);
+    releaseObject(env, cls);
+    done_sigbuf(&sig);
+    error("method %s with signature %s not found", mnam, sig.sigbuf);
+  }
+#if (RJ_PROFILE>1)
+  profReport("Found CID/MID for %s %s:",mnam,sig.sig);
+#endif
+  switch (*retsig) {
+  case 'V': {
+BEGIN_RJAVA_CALL
+    o?
+      (*env)->CallVoidMethodA(env, o, mid, jpar):
+      (*env)->CallStaticVoidMethodA(env, cls, mid, jpar);
+END_RJAVA_CALL
+    Rfreejpars(env, tmpo);
+    releaseObject(env, cls);
+    _prof(profReport("Method \"%s\" returned:",mnam));
+    return R_NilValue;
+  }
+  case 'I': {
+BEGIN_RJAVA_CALL
+    int r=o?
+      (*env)->CallIntMethodA(env, o, mid, jpar):
+      (*env)->CallStaticIntMethodA(env, cls, mid, jpar);  
+    e = allocVector(INTSXP, 1);
+    INTEGER(e)[0] = r;
+END_RJAVA_CALL
+    Rfreejpars(env, tmpo);
+    releaseObject(env, cls);
+    _prof(profReport("Method \"%s\" returned:",mnam));
+    return e;
+  }
+  case 'B': {
+BEGIN_RJAVA_CALL
+    int r=(int) (o?
+		 (*env)->CallByteMethodA(env, o, mid, jpar):
+		 (*env)->CallStaticByteMethodA(env, cls, mid, jpar));
+    e = allocVector(INTSXP, 1);
+    INTEGER(e)[0] = r;
+END_RJAVA_CALL
+    Rfreejpars(env, tmpo);
+    releaseObject(env, cls);
+    _prof(profReport("Method \"%s\" returned:",mnam));
+    return e;
+  }
+  case 'C': {
+BEGIN_RJAVA_CALL
+    int r=(int) (o?
+		 (*env)->CallCharMethodA(env, o, mid, jpar):
+		 (*env)->CallStaticCharMethodA(env, cls, mid, jpar));
+    e = allocVector(INTSXP, 1);
+    INTEGER(e)[0] = r;
+END_RJAVA_CALL
+    Rfreejpars(env, tmpo);
+    releaseObject(env, cls);
+    _prof(profReport("Method \"%s\" returned:",mnam));
+    return e;
+   }
+ case 'J': { 
+BEGIN_RJAVA_CALL
+    jlong r=o?
+      (*env)->CallLongMethodA(env, o, mid, jpar):
+      (*env)->CallStaticLongMethodA(env, cls, mid, jpar);
+    e = allocVector(REALSXP, 1);
+    REAL(e)[0]=(double)r;
+END_RJAVA_CALL
+    Rfreejpars(env, tmpo);
+    releaseObject(env, cls);
+    _prof(profReport("Method \"%s\" returned:",mnam));
+    return e;
+ }
+ case 'S': { 
+BEGIN_RJAVA_CALL
+    jshort r=o?
+      (*env)->CallShortMethodA(env, o, mid, jpar):
+      (*env)->CallStaticShortMethodA(env, cls, mid, jpar);
+    e = allocVector(INTSXP, 1);
+    INTEGER(e)[0]=(int)r;
+END_RJAVA_CALL
+    Rfreejpars(env, tmpo);
+    releaseObject(env, cls);
+    _prof(profReport("Method \"%s\" returned:",mnam));
+    return e;
+ }
+ case 'Z': {
+BEGIN_RJAVA_CALL
+    jboolean r=o?
+      (*env)->CallBooleanMethodA(env, o, mid, jpar):
+      (*env)->CallStaticBooleanMethodA(env, cls, mid, jpar);
+    e = allocVector(LGLSXP, 1);
+    LOGICAL(e)[0]=(r)?1:0;
+END_RJAVA_CALL
+    Rfreejpars(env, tmpo);
+    releaseObject(env, cls);
+    _prof(profReport("Method \"%s\" returned:",mnam));
+    return e;
+ }
+ case 'D': {
+BEGIN_RJAVA_CALL
+    double r=o?
+      (*env)->CallDoubleMethodA(env, o, mid, jpar):
+      (*env)->CallStaticDoubleMethodA(env, cls, mid, jpar);
+    e = allocVector(REALSXP, 1);
+    REAL(e)[0]=r;
+END_RJAVA_CALL
+    Rfreejpars(env, tmpo);
+    releaseObject(env, cls);
+    _prof(profReport("Method \"%s\" returned:",mnam));
+    return e;
+  }
+ case 'F': {
+BEGIN_RJAVA_CALL
+  double r = (double) (o?
+		      (*env)->CallFloatMethodA(env, o, mid, jpar):
+		      (*env)->CallStaticFloatMethodA(env, cls, mid, jpar));
+  e = allocVector(REALSXP, 1);
+  REAL(e)[0] = r;
+END_RJAVA_CALL
+  Rfreejpars(env, tmpo);
+  releaseObject(env, cls);
+  _prof(profReport("Method \"%s\" returned:",mnam));
+  return e;
+ }
+ case 'L':
+ case '[': {
+   jobject r;
+BEGIN_RJAVA_CALL
+   r = o?
+     (*env)->CallObjectMethodA(env, o, mid, jpar):
+     (*env)->CallStaticObjectMethodA(env, cls, mid, jpar);
+END_RJAVA_CALL
+    Rfreejpars(env, tmpo);
+    releaseObject(env, cls);
+    _mp(MEM_PROF_OUT("  %08x LNEW object method \"%s\" result\n", (int) r, mnam))
+    if (!r) {
+      _prof(profReport("Method \"%s\" returned NULL:",mnam));
+      return R_NilValue;
+    }
+    e = j2SEXP(env, r, 1);
+    _prof(profReport("Method \"%s\" returned",mnam));
+    return e;
+   }
+  } /* switch */
+  _prof(profReport("Method \"%s\" has an unknown signature, not called:",mnam));
+  releaseObject(env, cls);
+  error("unsupported/invalid mathod signature %s", retsig);
+  return R_NilValue;
+}
+
+/** like RcallMethod but the call will be synchronized */
+REPE SEXP RcallSyncMethod(SEXP par) {
+  SEXP p=par, e;
+  jobject o = 0;
+  JNIEnv *env=getJNIEnv();
+
+  p=CDR(p); e=CAR(p); p=CDR(p);
+  if (e==R_NilValue) 
+    error("RcallSyncMethod: call on a NULL object");
+  if (TYPEOF(e)==EXTPTRSXP) {
+    jverify(e);
+    o = (jobject)EXTPTR_PTR(e);
+  } else
+    error("RcallSyncMethod: invalid object parameter");
+  if (!o)
+    error("RcallSyncMethod: attempt to call a method of a NULL object.");
+#ifdef RJ_DEBUG
+  rjprintf("RcallSyncMethod: object: "); printObject(env, o);
+#endif
+  if ((*env)->MonitorEnter(env, o) != JNI_OK) {
+    REprintf("Rglue.warning: couldn't get monitor on the object, running unsynchronized.\n");
+    return RcallMethod(par);
+  }
+
+  e = RcallMethod(par);
+
+  if ((*env)->MonitorExit(env, o) != JNI_OK)
+    REprintf("Rglue.SERIOUS PROBLEM: MonitorExit failed, subsequent calls may cause a deadlock!\n");
+
+  return e;
+}
+
+/** create new object.
+    fully-qualified class in JNI notation (string) [, constructor parameters] */
+REPE SEXP RcreateObject(SEXP par) {
+  SEXP p=par;
+  SEXP e;
+  int silent=0;
+  const char *class;
+  sig_buffer_t sig;
+  jvalue jpar[maxJavaPars];
+  jobject tmpo[maxJavaPars+1];
+  jobject o, loader = 0;
+  JNIEnv *env=getJNIEnv();
+
+  if (TYPEOF(p)!=LISTSXP) {
+    _dbg(rjprintf("Parameter list expected but got type %d.\n",TYPEOF(p)));
+    error_return("RcreateObject: invalid parameter");
+  }
+
+  p=CDR(p); /* skip first parameter which is the function name */
+  e=CAR(p); /* second is the class name */
+  if (TYPEOF(e)!=STRSXP || LENGTH(e)!=1)
+    error("RcreateObject: invalid class name");
+  class = CHAR_UTF8(STRING_ELT(e,0));
+  _dbg(rjprintf("RcreateObject: new object of class %s\n",class));
+  init_sigbuf(&sig);
+  strcats(&sig, "(");
+  p=CDR(p);
+  Rpar2jvalue(env, p, jpar, &sig, maxJavaPars, tmpo);
+  strcats(&sig, ")V");
+  _dbg(rjprintf(" constructor signature is %s\n",sig.sig));
+
+  /* look for named arguments */
+  while (TYPEOF(p)==LISTSXP) {
+    if (TAG(p) && isSymbol(TAG(p))) {
+      if (TAG(p)==install("silent") && isLogical(CAR(p)) && LENGTH(CAR(p))==1)
+	silent=LOGICAL(CAR(p))[0];
+
+      /* class.loader */
+      if (TAG(p)==install("class.loader")) {
+	SEXP e = CAR(p);
+	if (TYPEOF(e) == S4SXP && IS_JOBJREF(e)) {
+	  SEXP sref = GET_SLOT(e, install("jobj"));
+	  if (sref && TYPEOF(sref) == EXTPTRSXP) {
+	    jverify(sref);
+	    loader = (jobject)EXTPTR_PTR(sref);
+	  }
+	} else if (e != R_NilValue)
+	  Rf_error("invalid class.loader");
+      }
+    }
+    p = CDR(p);
+  }
+  if (!loader) loader = oClassLoader;
+BEGIN_RJAVA_CALL
+  o = createObject(env, class, sig.sig, jpar, silent, loader);
+END_RJAVA_CALL
+  done_sigbuf(&sig);
+  Rfreejpars(env, tmpo);
+  if (!o) return R_NilValue;
+
+#ifdef RJ_DEBUG
+  {
+    jstring s=callToString(env, o);
+    const char *c="???";
+    if (s) c=(*env)->GetStringUTFChars(env, s, 0);
+    rjprintf(" new Java object [%s] reference %lx (local)\n", c, (long)o);
+    if (s) {
+      (*env)->ReleaseStringUTFChars(env, s, c);
+      releaseObject(env, s);
+    }
+  }
+#endif
+  
+  return j2SEXP(env, o, 1);
+}
+
+/** returns the name of an object's class (in the form of R string) */
+static SEXP getObjectClassName(JNIEnv *env, jobject o) {
+  jclass cls;
+  jobject r;
+  char cn[128];
+  if (!o) return mkString("java/jang/Object");
+  cls = objectClass(env, o);
+  if (!cls) return mkString("java/jang/Object");
+  r = (*env)->CallObjectMethod(env, cls, mid_getName);
+  _mp(MEM_PROF_OUT("  %08x LNEW object getName result\n", (int) r))
+  if (!r) {
+    releaseObject(env, cls);
+    releaseObject(env, r);
+    error("unable to get class name");
+  }
+  cn[127]=0; *cn=0;
+  {
+    int sl = (*env)->GetStringLength(env, r);
+    if (sl>127) {
+      releaseObject(env, cls);
+      releaseObject(env, r);
+      error("class name is too long");
+    }
+    if (sl) (*env)->GetStringUTFRegion(env, r, 0, sl, cn);
+  }
+  { char *c=cn; while(*c) { if (*c=='.') *c='/'; c++; } }
+  releaseObject(env, cls);
+  releaseObject(env, r);
+  return mkString(cn);
+}
+
+/** creates a new jobjRef object. If klass is NULL then the class is determined from the object (if also o=NULL then the class is set to java/lang/Object) */
+HIDE SEXP new_jobjRef(JNIEnv *env, jobject o, const char *klass) {
+  SEXP oo = NEW_OBJECT(MAKE_CLASS("jobjRef"));
+  if (!inherits(oo, "jobjRef"))
+    error("unable to create jobjRef object");
+  PROTECT(oo);
+  SET_SLOT(oo, install("jclass"),
+	   klass?mkString(klass):getObjectClassName(env, o));
+  SET_SLOT(oo, install("jobj"), j2SEXP(env, o, 1));
+  UNPROTECT(1);
+  return oo;
+}
+
+/** 
+ * creates a new jclassName object. similar to what the jclassName
+ * function does in the R side
+ *
+ * @param env pointer to the jni env
+ * @param cl Class instance
+ */
+HIDE SEXP new_jclassName(JNIEnv *env, jobject/*Class*/ cl ) {
+  SEXP oo = NEW_OBJECT(MAKE_CLASS("jclassName"));
+  if (!inherits(oo, "jclassName"))
+    error("unable to create jclassName object");
+  PROTECT(oo);
+  SET_SLOT(oo, install("name"), getName(env, cl) );
+  SET_SLOT(oo, install("jobj"), new_jobjRef( env, cl, "java/lang/Class" ) );
+  UNPROTECT(1);
+  return oo;
+}
+
+/** Calls the Class.getName method and return the result as an R STRSXP */
+HIDE SEXP getName( JNIEnv *env, jobject/*Class*/ cl){
+	char cn[128];
+	
+	jstring r = (*env)->CallObjectMethod(env, cl, mid_getName);
+  
+	cn[127]=0; *cn=0;
+  	int sl = (*env)->GetStringLength(env, r);
+  	if (sl>127) {
+  	  error("class name is too long");
+  	}
+  	if (sl) (*env)->GetStringUTFRegion(env, r, 0, sl, cn);
+  	char *c=cn; while(*c) { if (*c=='.') *c='/'; c++; }
+
+	SEXP res = PROTECT( mkString(cn ) ); 
+	releaseObject(env, r);
+	UNPROTECT(1); /* res */
+	return res;
+}
+
+static SEXP new_jarrayRef(JNIEnv *env, jobject a, const char *sig) {
+  /* it is too tedious to try to do this in C, so we use 'new' R function instead */
+  /* SEXP oo = eval(LCONS(install("new"),LCONS(mkString("jarrayRef"),R_NilValue)), R_GlobalEnv); */
+  SEXP oo = NEW_OBJECT(MAKE_CLASS("jarrayRef"));
+  /* .. and set the slots in C .. */
+  if (! IS_JARRAYREF(oo) )
+    error("unable to create an array");
+  PROTECT(oo);
+  SET_SLOT(oo, install("jobj"), j2SEXP(env, a, 1));
+  SET_SLOT(oo, install("jclass"), mkString(sig));
+  SET_SLOT(oo, install("jsig"), mkString(sig));
+  UNPROTECT(1);
+  return oo;
+}
+
+/**
+ * Creates a reference to a rectangular java array.
+ *
+ * @param env 
+ * @param a the java object
+ * @param sig signature (class of the array object)
+ * @param dim dimension vector
+ */
+static SEXP new_jrectRef(JNIEnv *env, jobject a, const char *sig, SEXP dim ) {
+  /* it is too tedious to try to do this in C, so we use 'new' R function instead */
+  /* SEXP oo = eval(LCONS(install("new"),LCONS(mkString("jrectRef"),R_NilValue)), R_GlobalEnv); */
+  SEXP oo = NEW_OBJECT(MAKE_CLASS("jrectRef"));
+  /* .. and set the slots in C .. */
+  if (! IS_JRECTREF(oo) )
+    error("unable to create an array");
+  PROTECT(oo);
+  SET_SLOT(oo, install("jobj"), j2SEXP(env, a, 1));
+  SET_SLOT(oo, install("jclass"), mkString(sig));
+  SET_SLOT(oo, install("jsig"), mkString(sig));
+  SET_SLOT(oo, install("dimension"), dim);
+  
+  UNPROTECT(1); /* oo */
+  return oo;
+}
+
+/* this does not take care of multi dimensional arrays properly */
+
+/**
+ * Creates a one dimensionnal java array
+ *
+ * @param an R list or vector
+ * @param cl the class name
+ */
+REPC SEXP RcreateArray(SEXP ar, SEXP cl) {
+  JNIEnv *env=getJNIEnv();
+  
+  if (ar==R_NilValue) return R_NilValue;
+  switch(TYPEOF(ar)) {
+  case INTSXP:                                
+    {
+      if (inherits(ar, "jbyte")) {
+	jbyteArray a = newByteArrayI(env, INTEGER(ar), LENGTH(ar));
+	if (!a) error("unable to create a byte array");
+	return new_jarrayRef(env, a, "[B" ) ;
+      } else if (inherits(ar, "jchar")) {
+	jcharArray a = newCharArrayI(env, INTEGER(ar), LENGTH(ar));
+	if (!a) error("unable to create a char array");
+	return new_jarrayRef(env, a, "[C" ); 
+      } else if (inherits(ar, "jshort")) {
+	jshortArray a = newShortArrayI(env, INTEGER(ar), LENGTH(ar));
+	if (!a) error("unable to create a short integer array");
+	return new_jarrayRef(env, a, "[S");
+      } else {
+	jintArray a = newIntArray(env, INTEGER(ar), LENGTH(ar));
+	if (!a) error("unable to create an integer array");
+	return new_jarrayRef(env, a, "[I");
+      }
+    }
+  case REALSXP:
+    {
+      if (inherits(ar, "jfloat")) {
+	jfloatArray a = newFloatArrayD(env, REAL(ar), LENGTH(ar));
+	if (!a) error("unable to create a float array");
+	return new_jarrayRef(env, a, "[F");
+      } else if (inherits(ar, "jlong")){
+	jlongArray a = newLongArrayD(env, REAL(ar), LENGTH(ar));
+	if (!a) error("unable to create a long array");
+	return new_jarrayRef(env, a, "[J");
+      } else {
+	jdoubleArray a = newDoubleArray(env, REAL(ar), LENGTH(ar));
+	if (!a) error("unable to create double array");
+	return new_jarrayRef(env, a, "[D");
+      }
+    }
+  case STRSXP:
+    {
+      jobjectArray a = (*env)->NewObjectArray(env, LENGTH(ar), javaStringClass, 0);
+      int i = 0;
+      if (!a) error("unable to create a string array");
+      while (i < LENGTH(ar)) {
+	  SEXP sa = STRING_ELT(ar, i);
+	  if (sa != R_NaString) {
+	      jobject so = newString(env, CHAR_UTF8(sa));
+	      (*env)->SetObjectArrayElement(env, a, i, so);
+	      releaseObject(env, so);
+	  }
+	  i++;
+      }
+      return new_jarrayRef(env, a, "[Ljava/lang/String;");
+    }
+  case LGLSXP:
+    {
+      /* ASSUMPTION: LOGICAL()=int* */
+      jbooleanArray a = newBooleanArrayI(env, LOGICAL(ar), LENGTH(ar));
+      if (!a) error("unable to create a boolean array");
+      return new_jarrayRef(env, a, "[Z");
+    }
+  case VECSXP:
+    {
+      int i=0;
+      jclass ac = javaObjectClass;
+      const char *sigName = 0;
+      char buf[256];
+      
+      while (i<LENGTH(ar)) {
+	SEXP e = VECTOR_ELT(ar, i);
+	if (e != R_NilValue &&
+	    !inherits(e, "jobjRef") &&
+	    !inherits(e, "jarrayRef") && 
+	    !inherits(e, "jrectRef") )
+	  error("Cannot create a Java array from a list that contains anything other than Java object references.");
+	i++;
+      }
+      /* optional class name for the objects contained in the array */
+      if (TYPEOF(cl)==STRSXP && LENGTH(cl)>0) {
+	const char *cname = CHAR_UTF8(STRING_ELT(cl, 0));
+	if (cname) {
+	  ac = findClass(env, cname, oClassLoader);
+	  if (!ac)
+	    error("Cannot find class %s.", cname);
+	  if (strlen(cname)<253) {
+	    /* it's valid to have [* for class name (for mmulti-dim
+	       arrays), but then we cannot add [L..; */
+	    if (*cname == '[') {
+	      /* we have to add [ prefix to the signature */
+	      buf[0] = '[';
+	      strcpy(buf+1, cname);
+	    } else {
+	      buf[0] = '['; buf[1] = 'L'; 
+	      strcpy(buf+2, cname);
+	      strcat(buf,";");
+	    }
+	    sigName = buf;
+	  }
+	}
+      } /* if contents class specified */
+      {
+	jobjectArray a = (*env)->NewObjectArray(env, LENGTH(ar), ac, 0);
+	_mp(MEM_PROF_OUT("  %08x LNEW object[%d]\n", (int)a, LENGTH(ar)))
+	if (ac != javaObjectClass) releaseObject(env, ac);
+	i=0;
+	if (!a) error("Cannot create array of objects.");
+	while (i < LENGTH(ar)) {
+	  SEXP e = VECTOR_ELT(ar, i);
+	  jobject o = 0;
+	  if (e != R_NilValue) {
+	    SEXP sref = GET_SLOT(e, install("jobj"));
+	    if (sref && TYPEOF(sref) == EXTPTRSXP) {
+	      jverify(sref);
+	      o = (jobject)EXTPTR_PTR(sref);
+	    }
+	  }	  
+	  (*env)->SetObjectArrayElement(env, a, i, o);
+	  i++;
+	}
+	return new_jarrayRef(env, a, sigName?sigName:"[Ljava/lang/Object;");
+      }
+    }
+  case RAWSXP:
+    {
+      jbyteArray a = newByteArray(env, RAW(ar), LENGTH(ar));
+      if (!a) error("unable to create a byte array");
+      return new_jarrayRef(env, a, "[B");
+    }
+  }
+  error("Unsupported type to create Java array from.");
+  return R_NilValue;
+}
+
+/** check whether there is an exception pending and
+    return the exception if any (NULL otherwise) */
+REPC SEXP RpollException() {
+  JNIEnv *env=getJNIEnv();
+  jthrowable t;
+BEGIN_RJAVA_CALL
+  t=(*env)->ExceptionOccurred(env);
+END_RJAVA_CALL
+  _mp(MEM_PROF_OUT("  %08x LNEW RpollException throwable\n", (int)t))
+  return t?j2SEXP(env, t, 1):R_NilValue;
+}
+
+/** clear any pending exceptions */
+REP void RclearException() {
+  JNIEnv *env=getJNIEnv();
+BEGIN_RJAVA_CALL
+  (*env)->ExceptionClear(env);  
+END_RJAVA_CALL
+}
+
+REPC SEXP javaObjectCache(SEXP o, SEXP what) {
+  if (TYPEOF(o) != EXTPTRSXP)
+    error("invalid object");
+  if (TYPEOF(what) == RAWSXP || what == R_NilValue) {
+    /* set PROT to the serialization of NULL */
+    SETCDR(o, what);
+    return what;
+  }
+  if (TYPEOF(what) == LGLSXP)
+    return EXTPTR_PROT(o);
+  error("invalid argument");
+  return R_NilValue;
+}
+
+REPC SEXP RthrowException(SEXP ex) {
+  JNIEnv *env=getJNIEnv();
+  jthrowable t=0;
+  SEXP exr;
+  int tr=0;
+  SEXP res;
+
+  if (!inherits(ex, "jobjRef"))
+    error("Invalid throwable object.");
+  
+  exr=GET_SLOT(ex, install("jobj"));
+  if (exr && TYPEOF(exr)==EXTPTRSXP) {
+    jverify(exr);
+    t=(jthrowable)EXTPTR_PTR(exr);
+  }
+  if (!t)
+    error("Throwable must be non-null.");
+  
+BEGIN_RJAVA_CALL
+  tr = (*env)->Throw(env, t);
+END_RJAVA_CALL
+  res = allocVector(INTSXP, 1);
+  INTEGER(res)[0]=tr;
+  return res;
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/arrayc.c b/com.oracle.truffle.r.pkgs/rJava/src/arrayc.c
new file mode 100644
index 0000000000000000000000000000000000000000..b1d1cdffefb38c8c86d9c196ccff6e7f41756856
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/arrayc.c
@@ -0,0 +1,444 @@
+/* R-callable functions to convert arrays into R objects
+ *
+ * rJava R/Java interface  (C)Copyright 2003-2007 Simon Urbanek
+ * (see rJava project root for licensing details)
+ */
+
+#include "rJava.h"
+
+/** get contents of the object array in the form of list of ext. pointers */
+REPC SEXP RgetObjectArrayCont(SEXP e) {
+  SEXP ar;
+  jarray o;
+  int l,i;
+  JNIEnv *env=getJNIEnv();
+
+  profStart();
+  if (e==R_NilValue) return R_NilValue;
+  if (TYPEOF(e)==EXTPTRSXP) {
+    jverify(e);
+    o=(jobject)EXTPTR_PTR(e);
+  } else
+    error("invalid object parameter");
+  _dbg(rjprintf("RgetObjectArrayCont: jarray %x\n",o));
+  if (!o) return R_NilValue;
+  l=(int)(*env)->GetArrayLength(env, o);
+  _dbg(rjprintf(" convert object array of length %d\n",l));
+  if (l<1) return R_NilValue;
+  PROTECT(ar=allocVector(VECSXP,l));
+  i=0;
+  while (i<l) {
+    jobject ae = (*env)->GetObjectArrayElement(env, o, i);
+    _mp(MEM_PROF_OUT("  %08x LNEW object array element [%d]\n", (int) ae, i))
+    SET_VECTOR_ELT(ar, i, j2SEXP(env, ae, 1));
+    i++;
+  }
+  UNPROTECT(1);
+  _prof(profReport("RgetObjectArrayCont[%d]:",o));
+  return ar;
+}
+
+/** get contents of the object array in the form of STRSXP vector */
+REPC SEXP RgetStringArrayCont(SEXP e) {
+  SEXP ar = R_NilValue ;
+  if (e==R_NilValue) return R_NilValue;
+  if (TYPEOF(e)==EXTPTRSXP) {
+    jverify(e);
+    ar = getStringArrayCont( (jarray)EXTPTR_PTR(e) ) ;
+  } else
+    error("invalid object parameter");
+  return ar;
+}
+
+/** get contents of the integer array object */
+REPC SEXP RgetIntArrayCont(SEXP e) {
+  SEXP ar;
+  jarray o;
+  int l;
+  jint *ap;
+  JNIEnv *env=getJNIEnv();
+
+  profStart();
+  if (e==R_NilValue) return e;
+  if (TYPEOF(e)==EXTPTRSXP) {
+    jverify(e);
+    o=(jobject)EXTPTR_PTR(e);
+  } else
+    error("invalid object parameter");
+  _dbg(rjprintf("RgetIntArrayCont: jarray %x\n",o));
+  if (!o) return R_NilValue;
+  l=(int)(*env)->GetArrayLength(env, o);
+  _dbg(rjprintf(" convert int array of length %d\n",l));
+  if (l<0) return R_NilValue;
+  ap=(jint*)(*env)->GetIntArrayElements(env, o, 0);
+  if (!ap)
+    error("cannot obtain integer array contents");
+  PROTECT(ar=allocVector(INTSXP,l));
+  if (l>0) memcpy(INTEGER(ar),ap,sizeof(jint)*l);
+  UNPROTECT(1);
+  (*env)->ReleaseIntArrayElements(env, o, ap, 0);
+  _prof(profReport("RgetIntArrayCont[%d]:",o));
+  return ar;
+}
+
+/** get contents of the boolean array object */
+REPC SEXP RgetBoolArrayCont(SEXP e) {
+  SEXP ar;
+  jarray o;
+  int l;
+  jboolean *ap;
+  JNIEnv *env=getJNIEnv();
+
+  profStart();
+  if (e==R_NilValue) return e;
+  if (TYPEOF(e)==EXTPTRSXP) {
+    jverify(e);
+    o=(jobject)EXTPTR_PTR(e);
+  } else
+    error("invalid object parameter");
+  _dbg(rjprintf("RgetBoolArrayCont: jarray %x\n",o));
+  if (!o) return R_NilValue;
+  l=(int)(*env)->GetArrayLength(env, o);
+  _dbg(rjprintf(" convert bool array of length %d\n",l));
+  if (l<0) return R_NilValue;
+  ap=(jboolean*)(*env)->GetBooleanArrayElements(env, o, 0);
+  if (!ap)
+    error("cannot obtain boolean array contents");
+  PROTECT(ar=allocVector(LGLSXP,l));
+  { /* jboolean = byte, logical = int, need to convert */
+    int i = 0;
+    while (i < l) {
+      LOGICAL(ar)[i] = ap[i];
+      i++;
+    }
+  }
+  UNPROTECT(1);
+  (*env)->ReleaseBooleanArrayElements(env, o, ap, 0);
+  _prof(profReport("RgetBoolArrayCont[%d]:",o));
+  return ar;
+}
+
+/** get contents of a character array object */
+REPC SEXP RgetCharArrayCont(SEXP e) {
+  SEXP ar;
+  jarray o;
+  int l;
+  jchar *ap;
+  JNIEnv *env=getJNIEnv();
+
+  profStart();
+  if (e==R_NilValue) return e;
+  if (TYPEOF(e)==EXTPTRSXP) {
+    jverify(e);
+    o=(jobject)EXTPTR_PTR(e);
+  } else
+    error("invalid object parameter");
+  _dbg(rjprintf("RgetCharArrayCont: jarray %x\n",o));
+  if (!o) return R_NilValue;
+  l=(int)(*env)->GetArrayLength(env, o);
+  _dbg(rjprintf(" convert char array of length %d\n",l));
+  if (l<0) return R_NilValue;
+  ap = (*env)->GetCharArrayElements(env, o, 0);
+  if (!ap)
+    error("cannot obtain char array contents");
+  PROTECT(ar=allocVector(INTSXP,l));
+  { /* jchar = 16-bit, need to convert */
+    int i = 0;
+    while (i < l) {
+      INTEGER(ar)[i] = ap[i];
+      i++;
+    }
+  }
+  UNPROTECT(1);
+  (*env)->ReleaseCharArrayElements(env, o, ap, 0);
+  _prof(profReport("RgetCharArrayCont[%d]:",o));
+  return ar;
+}
+
+/** get contents of a short array object */
+REPC SEXP RgetShortArrayCont(SEXP e) {
+  SEXP ar;
+  jarray o;
+  int l;
+  jshort *ap;
+  JNIEnv *env=getJNIEnv();
+
+  profStart();
+  if (e==R_NilValue) return e;
+  if (TYPEOF(e)==EXTPTRSXP) {
+    jverify(e);
+    o=(jobject)EXTPTR_PTR(e);
+  } else
+    error("invalid object parameter");
+  _dbg(rjprintf("RgetBoolArrayCont: jarray %x\n",o));
+  if (!o) return R_NilValue;
+  l=(int)(*env)->GetArrayLength(env, o);
+  _dbg(rjprintf(" convert short array of length %d\n",l));
+  if (l<0) return R_NilValue;
+  ap = (*env)->GetShortArrayElements(env, o, 0);
+  if (!ap)
+    error("cannot obtain short array contents");
+  PROTECT(ar=allocVector(INTSXP,l));
+  { /* jshort = 16-bit, need to convert */
+    int i = 0;
+    while (i < l) {
+      INTEGER(ar)[i] = ap[i];
+      i++;
+    }
+  }
+  UNPROTECT(1);
+  (*env)->ReleaseShortArrayElements(env, o, ap, 0);
+  _prof(profReport("RgetShortArrayCont[%d]:",o));
+  return ar;
+}
+
+/** get contents of the byte array object */
+REPC SEXP RgetByteArrayCont(SEXP e) {
+  SEXP ar;
+  jarray o;
+  int l;
+  jbyte *ap;
+  JNIEnv *env=getJNIEnv();
+  
+  profStart();
+  if (e==R_NilValue) return e;
+  if (TYPEOF(e)==EXTPTRSXP) {
+    jverify(e);
+    o = (jobject)EXTPTR_PTR(e);
+  } else
+    error("invalid object parameter");
+  _dbg(rjprintf("RgetByteArrayCont: jarray %x\n",o));
+  if (!o) return R_NilValue;
+  l=(int)(*env)->GetArrayLength(env, o);
+  _dbg(rjprintf(" convert byte array of length %d\n",l));
+  if (l<0) return R_NilValue;
+  ap=(jbyte*)(*env)->GetByteArrayElements(env, o, 0);
+  if (!ap)
+    error("cannot obtain byte array contents");
+  PROTECT(ar=allocVector(RAWSXP,l));
+  if (l>0) memcpy(RAW(ar),ap,l);
+  UNPROTECT(1);
+  (*env)->ReleaseByteArrayElements(env, o, ap, 0);
+  _prof(profReport("RgetByteArrayCont[%d]:",o));
+  return ar;
+}
+
+/** get contents of the double array object  */
+REPC SEXP RgetDoubleArrayCont(SEXP e) {
+  SEXP ar;
+  jarray o;
+  int l;
+  jdouble *ap;
+  JNIEnv *env=getJNIEnv();
+
+  profStart();
+  if (e==R_NilValue) return e;
+  if (TYPEOF(e)==EXTPTRSXP) {
+    jverify(e);
+    o = (jobject)EXTPTR_PTR(e);
+  } else
+    error("invalid object parameter");
+  _dbg(rjprintf("RgetDoubleArrayCont: jarray %x\n",o));
+  if (!o) return R_NilValue;
+  l=(int)(*env)->GetArrayLength(env, o);
+  _dbg(rjprintf(" convert double array of length %d\n",l));
+  if (l<0) return R_NilValue;
+  ap=(jdouble*)(*env)->GetDoubleArrayElements(env, o, 0);
+  if (!ap)
+    error("cannot obtain double array contents");
+  PROTECT(ar=allocVector(REALSXP,l));
+  if (l>0) memcpy(REAL(ar),ap,sizeof(jdouble)*l);
+  UNPROTECT(1);
+  (*env)->ReleaseDoubleArrayElements(env, o, ap, 0);
+  _prof(profReport("RgetDoubleArrayCont[%d]:",o));
+  return ar;
+}
+
+/** get contents of the float array object (double) */
+REPC SEXP RgetFloatArrayCont(SEXP e) {
+  SEXP ar;
+  jarray o;
+  int l;
+  jfloat *ap;
+  JNIEnv *env=getJNIEnv();
+
+  profStart();
+  if (e==R_NilValue) return e;
+  if (TYPEOF(e)==EXTPTRSXP) {
+    jverify(e);
+    o = (jobject)EXTPTR_PTR(e);
+  } else
+    error("invalid object parameter");
+  _dbg(rjprintf("RgetFloatArrayCont: jarray %d\n",o));
+  if (!o) return R_NilValue;
+  l=(int)(*env)->GetArrayLength(env, o);
+  _dbg(rjprintf(" convert float array of length %d\n",l));
+  if (l<0) return R_NilValue;
+  ap=(jfloat*)(*env)->GetFloatArrayElements(env, o, 0);
+  if (!ap)
+    error("cannot obtain float array contents");
+  PROTECT(ar=allocVector(REALSXP,l));
+  { /* jfloat must be coerced into double .. we use just a cast for each element */
+    int i=0;
+    while (i<l) { REAL(ar)[i]=(double)ap[i]; i++; }
+  }
+  UNPROTECT(1);
+  (*env)->ReleaseFloatArrayElements(env, o, ap, 0);
+  _prof(profReport("RgetFloatArrayCont[%d]:",o));
+  return ar;
+}
+
+/** get contents of the long array object (int) */
+REPC SEXP RgetLongArrayCont(SEXP e) {
+  SEXP ar;
+  jarray o;
+  int l;
+  jlong *ap;
+  JNIEnv *env=getJNIEnv();
+	
+  profStart();
+  if (e==R_NilValue) return e;
+  if (TYPEOF(e)==EXTPTRSXP) {
+    jverify(e);
+    o=(jobject)EXTPTR_PTR(e);
+  } else
+    error("invalid object parameter");
+  _dbg(rjprintf("RgetLongArrayCont: jarray %d\n",o));
+  if (!o) return R_NilValue;
+  l=(int)(*env)->GetArrayLength(env, o);
+  _dbg(rjprintf(" convert long array of length %d\n",l));
+  if (l<0) return R_NilValue;
+  ap=(jlong*)(*env)->GetLongArrayElements(env, o, 0);
+  if (!ap)
+    error("cannot obtain long contents");
+  PROTECT(ar=allocVector(REALSXP,l));
+  { /* long must be coerced into double .. we use just a cast for each element, bad idea? */
+    int i=0;
+    while (i<l) { REAL(ar)[i]=(double)ap[i]; i++; }
+  }
+  UNPROTECT(1);
+  (*env)->ReleaseLongArrayElements(env, o, ap, 0);
+  _prof(profReport("RgetLongArrayCont[%d]:",o));
+  return ar;
+}
+
+
+/* these below have been factored out of the ones above so that they 
+   can also be used internally in jni code */
+   
+/** 
+ * get contents of the String array in the form of STRSXP vector
+ * 
+ * @param e a pointer to a String[] object
+ * 
+ * @return a STRSXP vector mirroring the java array
+ */
+HIDE SEXP getStringArrayCont(jarray o) {
+	SEXP ar;
+  int l,i;
+  const char *c;
+  JNIEnv *env=getJNIEnv();
+
+  profStart();
+  
+  _dbg(rjprintf("RgetStringArrayCont: jarray %x\n",o));
+  if (!o) return R_NilValue;
+  l=(int)(*env)->GetArrayLength(env, o);
+  _dbg(rjprintf(" convert string array of length %d\n",l));
+  if (l<0) return R_NilValue;
+  PROTECT(ar=allocVector(STRSXP,l));
+  i=0;
+  while (i<l) {
+    jobject sobj=(*env)->GetObjectArrayElement(env, o, i);
+    _mp(MEM_PROF_OUT("  %08x LNEW object array element [%d]\n", (int) sobj, i))
+    c=0;
+    if (sobj) {
+      /* we could (should?) check the type here ...
+      if (!(*env)->IsInstanceOf(env, sobj, javaStringClass)) {
+	printf(" not a String\n");
+      } else
+      */
+      c=(*env)->GetStringUTFChars(env, sobj, 0);
+    }
+    if (!c)
+      SET_STRING_ELT(ar, i, R_NaString);
+    else {
+      SET_STRING_ELT(ar, i, mkCharUTF8(c));
+      (*env)->ReleaseStringUTFChars(env, sobj, c);
+    }
+    if (sobj) releaseObject(env, sobj);
+    i++;
+  }
+  UNPROTECT(1);
+  _prof(profReport("RgetStringArrayCont[%d]:",o))
+  return ar;
+}
+
+
+/**
+ *  Get the list of class names of a java object
+ * This is a jni wrapper around the RJavaTools.getSimpleClassNames method
+ */
+HIDE jarray getSimpleClassNames( jobject o, jboolean addConditionClasses ){
+
+	JNIEnv *env=getJNIEnv();
+	jarray a ;
+	
+	profStart();
+	a = (jarray) (*env)->CallStaticObjectMethod(env, 
+		rj_RJavaTools_Class, mid_rj_getSimpleClassNames, 
+		o, addConditionClasses ) ;
+    _prof(profReport("getSimpleClassNames[%d]:",o)) ;
+	return a ;
+}
+
+/** 
+ * Get the list of class names of a java object, and
+ * structure it as a STRSXP vector
+ */ 
+HIDE SEXP getSimpleClassNames_asSEXP( jobject o, jboolean addConditionClasses ){
+	if( !o ){
+		SEXP res = PROTECT( allocVector( STRSXP, 4) ) ;
+		SET_STRING_ELT( res, 0, mkChar( "Exception" ) ) ; 
+		SET_STRING_ELT( res, 1, mkChar( "Throwable" ) ) ; 
+		SET_STRING_ELT( res, 2, mkChar( "error" ) ) ; 
+		SET_STRING_ELT( res, 3, mkChar( "condition" ) ) ; 
+		UNPROTECT(1);
+		return res ;
+	} else{
+		return getStringArrayCont( getSimpleClassNames( o, addConditionClasses ) );
+	}
+}
+
+/**
+ * Returns the STRSXP vector of simple class names of the object o
+ */
+REPC SEXP RgetSimpleClassNames( SEXP e, SEXP addConditionClasses ){
+	
+	SEXP ar = R_NilValue ;
+  	if (e==R_NilValue) return R_NilValue;
+  	jobject jobj ;
+  	if (TYPEOF(e)==EXTPTRSXP) {
+  		jverify(e);
+  		jobj = (jobject)EXTPTR_PTR(e) ;
+  	} else {
+  		error("invalid object parameter");
+  	}
+	
+ 	Rboolean add ;
+	switch(TYPEOF(addConditionClasses)) {
+		case LGLSXP:
+		    add = LOGICAL(addConditionClasses)[0];
+		    break;
+		case INTSXP:
+		    add = INTEGER(addConditionClasses)[0]; 
+		    break;
+		default:
+		    add = asLogical(addConditionClasses);
+	}
+	
+  ar = getSimpleClassNames_asSEXP( jobj , (jboolean)add ) ;
+
+  return ar;
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/callJNI.c b/com.oracle.truffle.r.pkgs/rJava/src/callJNI.c
new file mode 100644
index 0000000000000000000000000000000000000000..24b6d8f72dbfbf11525ffcb885befce07b91f8ec
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/callJNI.c
@@ -0,0 +1,360 @@
+#include <stdarg.h>
+#include <string.h>
+#include "rJava.h"
+#include <R_ext/Print.h>
+#include <R_ext/Error.h>
+
+#ifdef MEMPROF
+FILE *memprof_f = 0;
+#endif
+
+/* local to JRI */
+static void releaseLocal(JNIEnv *env, jobject o);
+
+REPC SEXP RJavaCheckExceptions(SEXP silent) {
+    int result = 0;
+    JNIEnv *env = getJNIEnv();
+    if (env)
+	result = checkExceptionsX(env, asInteger(silent));
+    return ScalarInteger(result);
+}
+
+HIDE void* errJNI(const char *err, ...) {
+	char msg[512];
+	va_list ap;
+#ifndef RJ_DEBUG
+	/* non-debug version goes straight to ckx - it should never return */
+	ckx(NULL);
+#endif
+	va_start(ap, err);
+	msg[511]=0;
+	vsnprintf(msg, 511, err, ap);
+#ifdef RJ_DEBUG
+	Rf_warning(msg);
+#else
+	Rf_error(msg);
+	/* this never returns and is just a fallback in case ckx doesn't return */
+#endif
+	va_end(ap);
+	checkExceptionsX(getJNIEnv(), 0);
+	return 0;
+}
+
+/* loader: if NULL does NOT use any custom loader but uses system FindClass,
+   otherwise Class.forName(..., true, loader) if user first and system only as fall-back */
+HIDE jclass findClass(JNIEnv *env, const char *cName, jobject loader) {
+  if (loader) {
+    char cn[128], *c=cn;
+    jobject cns;
+    jclass cl;
+
+    strcpy(cn, cName);
+    while (*c) { if (*c=='/') *c='.'; c++; };
+    cns = newString(env, cn);
+    if (!cns) error("unable to create Java string from '%s'", cn);
+#ifdef DEBUG_CL
+    printf("findClass(\"%s\") [with %s loader]\n", cn, (loader && loader == oClassLoader) ? "rJava" : "custom");
+#endif
+    cl = (jclass) (*env)->CallStaticObjectMethod(env, javaClassClass, mid_forName, cns, (jboolean) 1, loader);
+#if RJAVA_LEGACY
+    clx(env);
+#endif
+    _mp(MEM_PROF_OUT("  %08x LNEW class\n", (int) cl))
+    releaseObject(env, cns);
+#ifdef DEBUG_CL
+    printf(" - got %x\n", (unsigned int) cl);
+#endif
+#if RJAVA_LEGACY
+    if (cl)
+#endif
+	return cl;
+  }
+#ifdef DEBUG_CL
+  printf("findClass(\"%s\") (no loader)\n", cName);
+#endif
+  { 
+    jclass cl = (*env)->FindClass(env, cName);
+    _mp(MEM_PROF_OUT("  %08x LNEW class\n", (int) cl))
+#ifdef DEBUG_CL
+    printf(" - got %x\n", (unsigned int) cl); 
+#endif
+    return cl;
+  }
+}
+
+/* loader: if NULL, uses oClassLoader (rJava class loader) */
+HIDE jobject createObject(JNIEnv *env, const char *class, const char *sig, jvalue *par, int silent, jobject loader) {
+  /* va_list ap; */
+  jmethodID mid;
+  jclass cls;
+  jobject o;
+
+  cls=findClass(env, class, loader ? loader : oClassLoader);
+  if (!cls) return silent?0:errJNI("createObject.FindClass %s failed",class);
+  mid=(*env)->GetMethodID(env, cls, "<init>", sig);
+  if (!mid) {
+    releaseLocal(env, cls);  
+    return silent?0:errJNI("createObject.GetMethodID(\"%s\",\"%s\") failed",class,sig);
+  }
+  
+  /*  va_start(ap, sig); */
+  o=(*env)->NewObjectA(env, cls, mid, par);
+  _mp(MEM_PROF_OUT("  %08x LNEW object\n", (int) o))
+  /* va_end(ap); */
+  releaseLocal(env, cls);  
+  
+  return (o||silent)?o:errJNI("NewObject(\"%s\",\"%s\",...) failed",class,sig);
+}
+
+HIDE void printObject(JNIEnv *env, jobject o) {
+  jmethodID mid;
+  jclass cls;
+  jobject s;
+  const char *c;
+
+  cls=(*env)->GetObjectClass(env,o);
+  _mp(MEM_PROF_OUT("  %08x LNEW class from object %08x (JRI-local)\n", (int)cls, (int)o))
+  if (!cls) { releaseLocal(env, cls); errJNI("printObject.GetObjectClass failed"); return ; }
+  mid=(*env)->GetMethodID(env, cls, "toString", "()Ljava/lang/String;");
+  if (!mid) { releaseLocal(env, cls); errJNI("printObject.GetMethodID for toString() failed"); return; }
+  s=(*env)->CallObjectMethod(env, o, mid);
+  _mp(MEM_PROF_OUT("  %08x LNEW object method toString result (JRI-local)\n", (int)s))
+  if (!s) { releaseLocal(env, cls); errJNI("printObject o.toString() call failed"); return; }
+  c=(*env)->GetStringUTFChars(env, (jstring)s, 0);
+  (*env)->ReleaseStringUTFChars(env, (jstring)s, c);
+  releaseLocal(env, cls);  
+  releaseLocal(env, s);
+}
+
+HIDE jdoubleArray newDoubleArray(JNIEnv *env, double *cont, int len) {
+  jdoubleArray da=(*env)->NewDoubleArray(env,len);
+  jdouble *dae;
+
+  _mp(MEM_PROF_OUT("  %08x LNEW double[%d]\n", (int) da, len))
+  if (!da) return errJNI("newDoubleArray.new(%d) failed",len);
+  dae=(*env)->GetDoubleArrayElements(env, da, 0);
+  if (!dae) {
+    releaseLocal(env, da);
+    return errJNI("newDoubleArray.GetDoubleArrayElements failed");
+  }
+  memcpy(dae,cont,sizeof(jdouble)*len);
+  (*env)->ReleaseDoubleArrayElements(env, da, dae, 0);
+  return da;
+}
+
+HIDE jintArray newIntArray(JNIEnv *env, int *cont, int len) {
+  jintArray da=(*env)->NewIntArray(env,len);
+  jint *dae;
+
+  _mp(MEM_PROF_OUT("  %08x LNEW int[%d]\n", (int) da, len))
+  if (!da) return errJNI("newIntArray.new(%d) failed",len);
+  dae=(*env)->GetIntArrayElements(env, da, 0);
+  if (!dae) {
+    releaseLocal(env,da);
+    return errJNI("newIntArray.GetIntArrayElements failed");
+  }
+  memcpy(dae,cont,sizeof(jint)*len);
+  (*env)->ReleaseIntArrayElements(env, da, dae, 0);
+  return da;
+}
+
+HIDE jbyteArray newByteArray(JNIEnv *env, void *cont, int len) {
+  jbyteArray da=(*env)->NewByteArray(env,len);
+  jbyte *dae;
+
+  _mp(MEM_PROF_OUT("  %08x LNEW byte[%d]\n", (int) da, len))
+  if (!da) return errJNI("newByteArray.new(%d) failed",len);
+  dae=(*env)->GetByteArrayElements(env, da, 0);
+  if (!dae) {
+    releaseLocal(env,da);
+    return errJNI("newByteArray.GetByteArrayElements failed");
+  }
+  memcpy(dae,cont,len);
+  (*env)->ReleaseByteArrayElements(env, da, dae, 0);
+  return da;
+}
+
+HIDE jbyteArray newByteArrayI(JNIEnv *env, int *cont, int len) {
+  jbyteArray da=(*env)->NewByteArray(env,len);
+  jbyte* dae;
+  int i=0;
+
+  _mp(MEM_PROF_OUT("  %08x LNEW byte[%d]\n", (int) da, len))
+  if (!da) return errJNI("newByteArray.new(%d) failed",len);
+  dae=(*env)->GetByteArrayElements(env, da, 0);
+  if (!dae) {
+    releaseLocal(env,da);
+    return errJNI("newByteArray.GetByteArrayElements failed");
+  }
+  while (i<len) {
+    dae[i]=(jbyte)cont[i];
+    i++;
+  }
+  (*env)->ReleaseByteArrayElements(env, da, dae, 0);
+  return da;
+}
+
+HIDE jbooleanArray newBooleanArrayI(JNIEnv *env, int *cont, int len) {
+  jbooleanArray da=(*env)->NewBooleanArray(env,len);
+  jboolean *dae;
+  int i=0;
+
+  _mp(MEM_PROF_OUT("  %08x LNEW bool[%d]\n", (int) da, len))
+  if (!da) return errJNI("newBooleanArrayI.new(%d) failed",len);
+  dae=(*env)->GetBooleanArrayElements(env, da, 0);
+  if (!dae) {
+    releaseLocal(env,da);
+    return errJNI("newBooleanArrayI.GetBooleanArrayElements failed");
+  }
+  /* we cannot just memcpy since JNI uses unsigned char and R uses int */
+  while (i<len) {
+    dae[i]=(jboolean)cont[i];
+    i++;
+  }
+  (*env)->ReleaseBooleanArrayElements(env, da, dae, 0);
+  return da;
+}
+
+HIDE jcharArray newCharArrayI(JNIEnv *env, int *cont, int len) {
+  jcharArray da=(*env)->NewCharArray(env,len);
+  jchar *dae;
+  int i=0;
+
+  _mp(MEM_PROF_OUT("  %08x LNEW char[%d]\n", (int) da, len))
+  if (!da) return errJNI("newCharArrayI.new(%d) failed",len);
+  dae=(*env)->GetCharArrayElements(env, da, 0);
+  if (!dae) {
+    releaseLocal(env,da);
+    return errJNI("newCharArrayI.GetCharArrayElements failed");
+  }
+  while (i<len) {
+    dae[i]=(jchar)cont[i];
+    i++;
+  }
+  (*env)->ReleaseCharArrayElements(env, da, dae, 0);
+  return da;
+}
+
+HIDE jshortArray newShortArrayI(JNIEnv *env, int *cont, int len) {
+  jshortArray da=(*env)->NewShortArray(env,len);
+  jshort *dae;
+  int i=0;
+
+  _mp(MEM_PROF_OUT("  %08x LNEW short[%d]\n", (int) da, len))
+  if (!da) return errJNI("newShortArrayI.new(%d) failed",len);
+  dae=(*env)->GetShortArrayElements(env, da, 0);
+  if (!dae) {
+    releaseLocal(env,da);
+    return errJNI("newShortArrayI.GetShortArrayElements failed");
+  }
+  while (i<len) {
+    dae[i]=(jshort)cont[i];
+    i++;
+  }
+  (*env)->ReleaseShortArrayElements(env, da, dae, 0);
+  return da;
+}
+
+HIDE jfloatArray newFloatArrayD(JNIEnv *env, double *cont, int len) {
+  jfloatArray da=(*env)->NewFloatArray(env,len);
+  jfloat *dae;
+  int i=0;
+
+  _mp(MEM_PROF_OUT("  %08x LNEW float[%d]\n", (int) da, len))
+  if (!da) return errJNI("newFloatArrayD.new(%d) failed",len);
+  dae=(*env)->GetFloatArrayElements(env, da, 0);
+  if (!dae) {
+    releaseLocal(env,da);
+    return errJNI("newFloatArrayD.GetFloatArrayElements failed");
+  }
+  /* we cannot just memcpy since JNI uses float and R uses double */
+  while (i<len) {
+    dae[i]=(jfloat)cont[i];
+    i++;
+  }
+  (*env)->ReleaseFloatArrayElements(env, da, dae, 0);
+  return da;
+}
+
+HIDE jlongArray newLongArrayD(JNIEnv *env, double *cont, int len) {
+	jlongArray da=(*env)->NewLongArray(env,len);
+	jlong *dae;
+	int i=0;
+	
+	_mp(MEM_PROF_OUT("  %08x LNEW long[%d]\n", (int) da, len))
+	if (!da) return errJNI("newLongArrayD.new(%d) failed",len);
+	dae=(*env)->GetLongArrayElements(env, da, 0);
+	if (!dae) {
+	  releaseLocal(env, da);
+	  return errJNI("newLongArrayD.GetFloatArrayElements failed");
+	}
+	/* we cannot just memcpy since JNI uses long and R uses double */
+	while (i<len) {
+		/* we're effectively rounding to prevent representation issues
+		   however, we still may introduce some errors this way */
+		dae[i]=(jlong)(cont[i]+0.5);
+		i++;
+	}
+	(*env)->ReleaseLongArrayElements(env, da, dae, 0);
+	return da;
+}
+
+HIDE jstring newString(JNIEnv *env, const char *cont) {
+  jstring s=(*env)->NewStringUTF(env, cont);
+  _mp(MEM_PROF_OUT("  %08x LNEW string \"%s\"\n", (int) s, cont))
+  return s?s:errJNI("newString(\"%s\") failed",cont);
+}
+
+HIDE void releaseObject(JNIEnv *env, jobject o) {
+  /* Rprintf("releaseObject: %lx\n", (long)o);
+     printObject(env, o); */
+  _mp(MEM_PROF_OUT("  %08x LREL\n", (int)o))
+  (*env)->DeleteLocalRef(env, o);
+}
+
+HIDE jclass objectClass(JNIEnv *env, jobject o) {
+  jclass cls=(*env)->GetObjectClass(env,o);
+  _mp(MEM_PROF_OUT("  %08x LNEW class from object %08x\n", (int) cls, (int) o))
+    return cls;
+}  
+
+static void releaseLocal(JNIEnv *env, jobject o) {
+  _mp(MEM_PROF_OUT("  %08x LREL (JRI-local)\n", (int)o))
+  (*env)->DeleteLocalRef(env, o);
+}
+
+HIDE jobject makeGlobal(JNIEnv *env, jobject o) {
+  jobject g=(*env)->NewGlobalRef(env,o);
+  _mp(MEM_PROF_OUT("G %08x GNEW %08x\n", (int) g, (int) o))
+  return g?g:errJNI("makeGlobal: failed to make global reference");
+}
+
+HIDE void releaseGlobal(JNIEnv *env, jobject o) {
+  /* Rprintf("releaseGlobal: %lx\n", (long)o);
+     printObject(env, o); */
+  _mp(MEM_PROF_OUT("G %08x GREL\n", (int) o))
+  (*env)->DeleteGlobalRef(env,o);
+}
+
+static jobject nullEx = 0;
+
+HIDE int checkExceptionsX(JNIEnv *env, int silent) {
+  jthrowable t=(*env)->ExceptionOccurred(env);
+  
+  if (t == nullEx) t = 0; else {
+    if ((*env)->IsSameObject(env, t, 0)) {
+      nullEx = t; t = 0;
+    } else {
+      _mp(MEM_PROF_OUT("  %08x LNEW exception\n", (int) t))
+    }
+  }
+
+  if (t) {
+	  if (!silent) 
+		  ckx(env);
+    (*env)->ExceptionClear(env);
+    releaseLocal(env, t);
+    return 1;
+  }
+  return 0;
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/callback.c b/com.oracle.truffle.r.pkgs/rJava/src/callback.c
new file mode 100644
index 0000000000000000000000000000000000000000..32af2ef53d82ad8867db2b445e86beed6ed915db
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/callback.c
@@ -0,0 +1,74 @@
+#include "rJava.h"
+
+#ifdef ENABLE_JRICB
+
+#include <R_ext/eventloop.h>
+#include <unistd.h>
+#include "callback.h"
+
+int RJava_has_control = 0;
+
+/* ipcin   ->  receives requests on R thread
+   ipcout  <-  write to place requests to main R thread
+   resout  <-  written by main thread to respond
+   resin   ->  read to get info from main thread */
+
+static int ipcin, ipcout, resin, resout;
+
+static struct rJavaInfoBlock_s {
+  int ipcin, ipcout, resin, resout;
+  int *has_control;
+} rJavaInfoBlock;
+
+struct rJavaInfoBlock_s *RJava_get_info_block() {
+  return &rJavaInfoBlock;
+}
+
+typedef void(callbackfn)(void*);
+
+static void RJava_ProcessEvents(void *data) {
+  long buf[4];
+  int n = read(ipcin, buf, sizeof(long));
+  if (buf[0] == IPCC_LOCK_REQUEST) {
+    RJava_has_control = 1;
+    buf[0] = IPCC_LOCK_GRANTED;
+    write(resout, buf, sizeof(long));
+    n = read(ipcin, buf, sizeof(long));
+  }
+  if (buf[0] == IPCC_CLEAR_LOCK) {
+    RJava_has_control = 0;
+  }
+  if (buf[0] == IPCC_CONTROL_ADDR) {
+    buf[1] = (long) (void*) &RJava_has_control;
+    write(resout, buf, sizeof(long)*2);
+  }
+  if (buf[0] == IPCC_CALL_REQUEST) {
+    callbackfn *fn;
+    read(ipcin, buf+1, sizeof(long)*2);
+    fn = (callbackfn*) buf[1];
+    RJava_has_control = 1;
+    fn((void*) buf[2]);
+    RJava_has_control = 0;
+  }
+}
+
+int RJava_init_loop() {
+  int pfd[2];
+  pipe(pfd);
+  ipcin = pfd[0];
+  ipcout = pfd[1];
+  pipe(pfd);
+  resin = pfd[0];
+  resout = pfd[1];
+
+  rJavaInfoBlock.ipcin = ipcin;
+  rJavaInfoBlock.ipcout = ipcout;
+  rJavaInfoBlock.resin = resin;
+  rJavaInfoBlock.resout = resout;
+  rJavaInfoBlock.has_control = &RJava_has_control;
+
+  addInputHandler(R_InputHandlers, ipcin, RJava_ProcessEvents, RJavaActivity);
+  return 0;
+}
+
+#endif
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/callback.h b/com.oracle.truffle.r.pkgs/rJava/src/callback.h
new file mode 100644
index 0000000000000000000000000000000000000000..c3132ffbe2330661f94dfc5fb089f4994b32fa3a
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/callback.h
@@ -0,0 +1,18 @@
+#ifndef __CALLBACK_H__
+#define __CALLBACK_H__
+
+#ifdef ENABLE_JRICB
+extern int RJava_has_control;
+#endif
+
+#define RJavaActivity 16
+
+/* all IPC messages are long-alligned */
+#define IPCC_LOCK_REQUEST 1
+#define IPCC_LOCK_GRANTED 2 /* reponse on IPCC_LOCK_REQUEST */
+#define IPCC_CLEAR_LOCK   3
+#define IPCC_CALL_REQUEST 4 /* pars: <fn-ptr> <data-ptr> */
+#define IPCC_CONTROL_ADDR 5 /* ipc: request, res: <ctrl-ptr> */
+
+#endif
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/config.h b/com.oracle.truffle.r.pkgs/rJava/src/config.h
new file mode 100644
index 0000000000000000000000000000000000000000..a54fd1eec1c22279866350030fef09329450fe75
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/config.h
@@ -0,0 +1,94 @@
+/* src/config.h.  Generated from config.h.in by configure.  */
+/* src/config.h.in.  Generated from configure.ac by autoheader.  */
+
+/* define if callbacks support is enabled. */
+/* #undef ENABLE_JRICB */
+
+/* Define to 1 if you have the declaration of `siglongjmp', and to 0 if you
+   don't. */
+#define HAVE_DECL_SIGLONGJMP 1
+
+/* Define to 1 if you have the declaration of `sigsetjmp', and to 0 if you
+   don't. */
+#define HAVE_DECL_SIGSETJMP 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define if you have POSIX.1 compatible sigsetjmp/siglongjmp. */
+#define HAVE_POSIX_SETJMP 1
+
+/* Define to 1 when static inline works */
+#define HAVE_STATIC_INLINE 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+#define HAVE_SYS_TIME_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have <sys/wait.h> that is POSIX.1 compatible. */
+#define HAVE_SYS_WAIT_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Set if the Java parameter -Xrs is supported */
+/* #undef HAVE_XRS */
+
+/* Set if caching JNI environment is enabled. */
+/* #undef JNI_CACHE */
+
+/* memory profiling is enabled when defined */
+/* #undef MEMPROF */
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "Simon.Urbanek@r-project.org"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "rJava"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "rJava 0.8"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "rjava"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "0.8"
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Set if threading support should be enabled. */
+/* #undef THREADS */
+
+/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
+#define TIME_WITH_SYS_TIME 1
+
+/* Set if headless mode is to be used when starting the JVM */
+#define USE_HEADLESS_INIT 1
+
+/* Define to empty if `const' does not conform to ANSI C. */
+/* #undef const */
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/config.h.in b/com.oracle.truffle.r.pkgs/rJava/src/config.h.in
new file mode 100644
index 0000000000000000000000000000000000000000..061556a70e4bf3046ded455fad75718cba47aaeb
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/config.h.in
@@ -0,0 +1,93 @@
+/* src/config.h.in.  Generated from configure.ac by autoheader.  */
+
+/* define if callbacks support is enabled. */
+#undef ENABLE_JRICB
+
+/* Define to 1 if you have the declaration of `siglongjmp', and to 0 if you
+   don't. */
+#undef HAVE_DECL_SIGLONGJMP
+
+/* Define to 1 if you have the declaration of `sigsetjmp', and to 0 if you
+   don't. */
+#undef HAVE_DECL_SIGSETJMP
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#undef HAVE_INTTYPES_H
+
+/* Define to 1 if you have the <memory.h> header file. */
+#undef HAVE_MEMORY_H
+
+/* Define if you have POSIX.1 compatible sigsetjmp/siglongjmp. */
+#undef HAVE_POSIX_SETJMP
+
+/* Define to 1 when static inline works */
+#undef HAVE_STATIC_INLINE
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#undef HAVE_STDINT_H
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#undef HAVE_STDLIB_H
+
+/* Define to 1 if you have the <strings.h> header file. */
+#undef HAVE_STRINGS_H
+
+/* Define to 1 if you have the <string.h> header file. */
+#undef HAVE_STRING_H
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#undef HAVE_SYS_STAT_H
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+#undef HAVE_SYS_TIME_H
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#undef HAVE_SYS_TYPES_H
+
+/* Define to 1 if you have <sys/wait.h> that is POSIX.1 compatible. */
+#undef HAVE_SYS_WAIT_H
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#undef HAVE_UNISTD_H
+
+/* Set if the Java parameter -Xrs is supported */
+#undef HAVE_XRS
+
+/* Set if caching JNI environment is enabled. */
+#undef JNI_CACHE
+
+/* memory profiling is enabled when defined */
+#undef MEMPROF
+
+/* Define to the address where bug reports for this package should be sent. */
+#undef PACKAGE_BUGREPORT
+
+/* Define to the full name of this package. */
+#undef PACKAGE_NAME
+
+/* Define to the full name and version of this package. */
+#undef PACKAGE_STRING
+
+/* Define to the one symbol short name of this package. */
+#undef PACKAGE_TARNAME
+
+/* Define to the home page for this package. */
+#undef PACKAGE_URL
+
+/* Define to the version of this package. */
+#undef PACKAGE_VERSION
+
+/* Define to 1 if you have the ANSI C header files. */
+#undef STDC_HEADERS
+
+/* Set if threading support should be enabled. */
+#undef THREADS
+
+/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
+#undef TIME_WITH_SYS_TIME
+
+/* Set if headless mode is to be used when starting the JVM */
+#undef USE_HEADLESS_INIT
+
+/* Define to empty if `const' does not conform to ANSI C. */
+#undef const
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/fields.c b/com.oracle.truffle.r.pkgs/rJava/src/fields.c
new file mode 100644
index 0000000000000000000000000000000000000000..8bfdd0c8e991a106b21524ce7e67fe8b31a9210b
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/fields.c
@@ -0,0 +1,382 @@
+/* R-callable functions to get/set fields
+ *
+ * rJava R/Java interface  (C)Copyright 2003-2007 Simon Urbanek
+ * (see rJava project root for licensing details)
+ */
+
+#include "rJava.h"
+#include <Rdefines.h>
+
+static char *classToJNI(const char *cl) {
+  if (*cl=='[') {
+    char *d = strdup(cl);
+    char *c = d;
+    while (*c) { if (*c=='.') *c='/'; c++; }
+    return d;
+  }
+  if (!strcmp(cl, "boolean")) return strdup("Z");
+  if (!strcmp(cl, "byte"))    return strdup("B");
+  if (!strcmp(cl, "int"))     return strdup("I");
+  if (!strcmp(cl, "long"))    return strdup("J");
+  if (!strcmp(cl, "double"))  return strdup("D");
+  if (!strcmp(cl, "short"))   return strdup("S");
+  if (!strcmp(cl, "float"))   return strdup("F");
+  if (!strcmp(cl, "char"))    return strdup("C");
+ 
+  /* anything else is a real class -> wrap into L..; */
+  char *jc = malloc(strlen(cl)+3);
+  *jc='L';
+  strcpy(jc+1, cl);
+  strcat(jc, ";");
+  { char *c=jc; while (*c) { if (*c=='.') *c='/'; c++; } }
+  return jc;
+}
+
+/* find field signature using reflection. Basically it is the same as:
+   cls.getField(fnam).getType().getName()
+   + class2JNI mangling */
+/* TODO; use the mid_RJavaTools_getFieldTypeName method ID instead */
+static char *findFieldSignature(JNIEnv *env, jclass cls, const char *fnam) {
+  char *detsig = 0;
+  jstring s = newString(env, fnam);
+  if (s) {
+    jobject f = (*env)->CallObjectMethod(env, cls, mid_getField, s);
+    _mp(MEM_PROF_OUT("  %08x LNEW object getField result value\n", (int) f))
+    if (f) {
+      jobject fcl = (*env)->CallObjectMethod(env, f, mid_getType);
+      _mp(MEM_PROF_OUT("  %08x LNEW object getType result value\n", (int) f))
+      if (fcl) {
+	jobject fcns = (*env)->CallObjectMethod(env, fcl, mid_getName);
+	releaseObject(env, fcl);
+	if (fcns) {
+	  const char *fcn = (*env)->GetStringUTFChars(env, fcns, 0);
+	  detsig = classToJNI(fcn);
+	  _dbg(Rprintf("class '%s' -> '%s' sig\n", fcn, detsig));
+	  (*env)->ReleaseStringUTFChars(env, fcns, fcn);
+	  releaseObject(env, fcns);
+	  /* fid = (*env)->FromReflectedField(env, f); */
+	}
+      } else
+	releaseObject(env, fcl);
+      releaseObject(env, f);
+    }
+    releaseObject(env, s);
+  }
+  return detsig;
+}
+
+/** get value of a field of an object or class
+    object (int), return signature (string), field name (string)
+    arrays and objects are returned as IDs (hence not evaluated)
+    class name can be in either form / or .
+*/
+REPC SEXP RgetField(SEXP obj, SEXP sig, SEXP name, SEXP trueclass) {
+  jobject o = 0;
+  SEXP e;
+  const char *retsig, *fnam;
+  char *clnam = 0, *detsig = 0;
+  jfieldID fid;
+  jclass cls;
+  int tc = asInteger(trueclass);
+  JNIEnv *env=getJNIEnv();
+
+  if (obj == R_NilValue) return R_NilValue;
+  if ( IS_JOBJREF(obj) )
+    obj = GET_SLOT(obj, install("jobj"));
+  if (TYPEOF(obj)==EXTPTRSXP) {
+    jverify(obj);
+    o=(jobject)EXTPTR_PTR(obj);
+  } else if (TYPEOF(obj)==STRSXP && LENGTH(obj)==1)
+    clnam = strdup(CHAR(STRING_ELT(obj, 0)));
+  else
+    error("invalid object parameter");
+  if (!o && !clnam)
+    error("cannot access a field of a NULL object");
+#ifdef RJ_DEBUG
+  if (o) {
+    rjprintf("RgetField.object: "); printObject(env, o);
+  } else {
+    rjprintf("RgetField.class: %s\n", clnam);
+  }
+#endif
+  if (o)
+    cls = objectClass(env, o);
+  else {
+    char *c = clnam;
+    while(*c) { if (*c=='/') *c='.'; c++; }
+    cls = findClass(env, clnam, oClassLoader);
+    free(clnam);
+    if (!cls) {
+      error("cannot find class %s", CHAR(STRING_ELT(obj, 0)));
+    }
+  }
+  if (!cls)
+    error("cannot determine object class");
+#ifdef RJ_DEBUG
+  rjprintf("RgetField.class: "); printObject(env, cls);
+#endif
+  if (TYPEOF(name)!=STRSXP || LENGTH(name)!=1) {
+    releaseObject(env, cls);
+    error("invalid field name");
+  }
+  fnam = CHAR(STRING_ELT(name,0));
+  if (sig == R_NilValue) {
+    retsig = detsig = findFieldSignature(env, cls, fnam);
+    if (!retsig) {
+      releaseObject(env, cls);
+      error("unable to detect signature for field '%s'", fnam);
+    }
+  } else {
+    if (TYPEOF(sig)!=STRSXP || LENGTH(sig)!=1) {
+      releaseObject(env, cls);
+      error("invalid signature parameter");
+    }
+    retsig = CHAR(STRING_ELT(sig,0));
+  }
+  _dbg(rjprintf("field %s signature is %s\n",fnam,retsig));
+  
+  if (o) { /* first try non-static fields */
+    fid = (*env)->GetFieldID(env, cls, fnam, retsig);
+    checkExceptionsX(env, 1);
+    if (!fid) { /* if that fails, try static ones */
+      o = 0;
+      fid = (*env)->GetStaticFieldID(env, cls, fnam, retsig);
+    }
+  } else /* no choice if the object was a string */
+    fid = (*env)->GetStaticFieldID(env, cls, fnam, retsig);
+
+  if (!fid) {
+    checkExceptionsX(env, 1);
+    releaseObject(env, cls);
+    if (detsig) free(detsig);
+    error("RgetField: field %s not found", fnam);
+  }
+  switch (*retsig) {
+  case 'I': {
+    int r=o?
+      (*env)->GetIntField(env, o, fid):
+      (*env)->GetStaticIntField(env, cls, fid);
+    e = allocVector(INTSXP, 1);
+    INTEGER(e)[0] = r;
+    releaseObject(env, cls);
+    if (detsig) free(detsig);
+    return e;
+  }
+  case 'S': {
+    jshort r=o?
+      (*env)->GetShortField(env, o, fid):
+      (*env)->GetStaticShortField(env, cls, fid);
+    e = allocVector(INTSXP, 1);
+    INTEGER(e)[0] = r;
+    releaseObject(env, cls);
+    if (detsig) free(detsig);
+    return e;
+  }
+  case 'C': {
+    int r=(int) (o?
+		 (*env)->GetCharField(env, o, fid):
+		 (*env)->GetStaticCharField(env, cls, fid));
+    e = allocVector(INTSXP, 1);
+    INTEGER(e)[0] = r;
+    releaseObject(env, cls);
+    if (detsig) free(detsig);
+    return e;
+  }
+  case 'B': {
+    int r=(int) (o?
+		 (*env)->GetByteField(env, o, fid):
+		 (*env)->GetStaticByteField(env, cls, fid));
+    e = allocVector(INTSXP, 1);
+    INTEGER(e)[0] = r;
+    releaseObject(env, cls);
+    if (detsig) free(detsig);
+    return e;
+  }
+  case 'J': {
+    jlong r=o?
+      (*env)->GetLongField(env, o, fid):
+      (*env)->GetStaticLongField(env, cls, fid);
+    e = allocVector(REALSXP, 1);
+    REAL(e)[0] = (double)r;
+    releaseObject(env, cls);
+    if (detsig) free(detsig);
+    return e;
+  }
+  case 'Z': {
+    jboolean r=o?
+      (*env)->GetBooleanField(env, o, fid):
+      (*env)->GetStaticBooleanField(env, cls, fid);
+    e = allocVector(LGLSXP, 1);
+    LOGICAL(e)[0] = r?1:0;
+    releaseObject(env, cls);
+    if (detsig) free(detsig);
+    return e;
+  }
+  case 'D': {
+    double r=o?
+      (*env)->GetDoubleField(env, o, fid):
+      (*env)->GetStaticDoubleField(env, cls, fid);
+    e = allocVector(REALSXP, 1);
+    REAL(e)[0] = r;
+    releaseObject(env, cls);
+    if (detsig) free(detsig);
+    return e;
+  }
+  case 'F': {
+    double r = (double) (o?
+      (*env)->GetFloatField(env, o, fid):
+      (*env)->GetStaticFloatField(env, cls, fid));
+    e = allocVector(REALSXP, 1);
+    REAL(e)[0] = r;
+    releaseObject(env, cls);
+    if (detsig) free(detsig);
+    return e;
+  }
+  case 'L':
+  case '[': {
+    SEXP rv;
+    jobject r = o?
+      (*env)->GetObjectField(env, o, fid):
+      (*env)->GetStaticObjectField(env, cls, fid);
+    _mp(MEM_PROF_OUT("  %08x LNEW field value\n", (int) r))
+    releaseObject(env, cls);
+    if (tc) {
+      if (detsig) free(detsig);
+      return new_jobjRef(env, r, 0);
+    }
+    if (*retsig=='L') { /* need to fix the class name */      
+      char *d = strdup(retsig), *c = d;
+      while (*c) { if (*c==';') { *c=0; break; }; c++; }
+      rv = new_jobjRef(env, r, d+1);
+      free(d);
+    } else
+      rv = new_jobjRef(env, r, retsig);
+    if (detsig) free(detsig);
+    return rv;
+  }
+  } /* switch */
+  releaseObject(env, cls);
+  if (detsig) {
+    free(detsig);
+    error("unknown field signature");
+  }
+  error("unknown field signature '%s'", retsig);
+  return R_NilValue;
+}
+
+REPC SEXP RsetField(SEXP ref, SEXP name, SEXP value) {
+  jobject o = 0, otr;
+  SEXP obj = ref;
+  const char *fnam;
+  sig_buffer_t sig;
+  char *clnam = 0;
+  jfieldID fid;
+  jclass cls;
+  jvalue jval;
+  JNIEnv *env=getJNIEnv();
+
+  if (TYPEOF(name)!=STRSXP && LENGTH(name)!=1)
+    error("invalid field name");
+  fnam = CHAR(STRING_ELT(name, 0));
+  if (obj == R_NilValue) error("cannot set a field of a NULL object");
+  if (IS_JOBJREF(obj))
+    obj = GET_SLOT(obj, install("jobj"));
+  if (TYPEOF(obj)==EXTPTRSXP) {
+    jverify(obj);
+    o=(jobject)EXTPTR_PTR(obj);
+  } else if (TYPEOF(obj)==STRSXP && LENGTH(obj)==1)
+    clnam = strdup(CHAR(STRING_ELT(obj, 0)));
+  else
+    error("invalid object parameter");
+  if (!o && !clnam)
+    error("cannot set a field of a NULL object");
+#ifdef RJ_DEBUG
+  if (o) {
+    rjprintf("RsetField.object: "); printObject(env, o);
+  } else {
+    rjprintf("RsetField.class: %s\n", clnam);
+  }
+#endif
+  if (o)
+    cls = objectClass(env, o);
+  else {
+    char *c = clnam;
+    while(*c) { if (*c=='/') *c='.'; c++; }
+    cls = findClass(env, clnam, oClassLoader);
+    if (!cls) {
+      error("cannot find class %s", CHAR(STRING_ELT(obj, 0)));
+    }
+  }
+  if (!cls)
+    error("cannot determine object class");
+#ifdef RJ_DEBUG
+  rjprintf("RsetField.class: "); printObject(env, cls);
+#endif
+  init_sigbuf(&sig);
+  jval = R1par2jvalue(env, value, &sig, &otr);
+  
+  if (o) {
+    fid = (*env)->GetFieldID(env, cls, fnam, sig.sig);
+    if (!fid) {
+      checkExceptionsX(env, 1);
+      o = 0;
+      fid = (*env)->GetStaticFieldID(env, cls, fnam, sig.sig);
+    }
+  } else
+    fid = (*env)->GetStaticFieldID(env, cls, fnam, sig.sig);
+  if (!fid) {
+    checkExceptionsX(env, 1);
+    releaseObject(env, cls);
+    if (otr) releaseObject(env, otr);
+    done_sigbuf(&sig);
+    error("cannot find field %s with signature %s", fnam, sig.sigbuf);
+  }
+  switch(sig.sig[0]) {
+  case 'Z':
+    o?(*env)->SetBooleanField(env, o, fid, jval.z):
+      (*env)->SetStaticBooleanField(env, cls, fid, jval.z);
+    break;
+  case 'C':
+    o?(*env)->SetCharField(env, o, fid, jval.c):
+      (*env)->SetStaticCharField(env, cls, fid, jval.c);
+    break;
+  case 'B':
+    o?(*env)->SetByteField(env, o, fid, jval.b):
+      (*env)->SetStaticByteField(env, cls, fid, jval.b);
+    break;
+  case 'I':
+    o?(*env)->SetIntField(env, o, fid, jval.i):
+      (*env)->SetStaticIntField(env, cls, fid, jval.i);
+    break;
+  case 'D':
+    o?(*env)->SetDoubleField(env, o, fid, jval.d):
+      (*env)->SetStaticDoubleField(env, cls, fid, jval.d);
+    break;
+  case 'F':
+    o?(*env)->SetFloatField(env, o, fid, jval.f):
+      (*env)->SetStaticFloatField(env, cls, fid, jval.f);
+    break;
+  case 'J':
+    o?(*env)->SetLongField(env, o, fid, jval.j):
+      (*env)->SetStaticLongField(env, cls, fid, jval.j);
+    break;
+  case 'S':
+    o?(*env)->SetShortField(env, o, fid, jval.s):
+      (*env)->SetStaticShortField(env, cls, fid, jval.s);
+    break;
+  case '[':
+  case 'L':
+    o?(*env)->SetObjectField(env, o, fid, jval.l):
+      (*env)->SetStaticObjectField(env, cls, fid, jval.l);
+    break;
+  default:
+    releaseObject(env, cls);
+    if (otr) releaseObject(env, otr);
+    done_sigbuf(&sig);
+    error("unknown field sighanture %s", sig.sigbuf);
+  }
+  done_sigbuf(&sig);
+  releaseObject(env, cls);
+  if (otr) releaseObject(env, otr);
+  return ref;
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/init.c b/com.oracle.truffle.r.pkgs/rJava/src/init.c
new file mode 100644
index 0000000000000000000000000000000000000000..091a29ecd079818c5a6344c502a68d4332e01641
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/init.c
@@ -0,0 +1,734 @@
+#include "rJava.h"
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+
+/* global variables */
+JavaVM *jvm;
+
+/* this will be set when Java tries to exit() but we carry on */
+int java_is_dead = 0;
+
+/* cached, global objects */
+
+jclass javaStringClass;
+jclass javaObjectClass;
+jclass javaClassClass;
+jclass javaFieldClass;
+
+/* cached, global method IDs */
+jmethodID mid_forName;
+jmethodID mid_getName;
+jmethodID mid_getSuperclass;
+jmethodID mid_getType;
+jmethodID mid_getField;
+
+/* internal classes and methods */
+jclass rj_RJavaTools_Class = (jclass)0;
+jmethodID mid_rj_getSimpleClassNames = (jmethodID)0 ;
+jmethodID mid_RJavaTools_getFieldTypeName = (jmethodID)0 ;
+
+
+jclass rj_RJavaImport_Class = (jclass)0;
+jmethodID mid_RJavaImport_getKnownClasses = (jmethodID)0 ;
+jmethodID mid_RJavaImport_lookup = (jmethodID)0 ;
+jmethodID mid_RJavaImport_exists = (jmethodID)0 ;
+
+int rJava_initialized = 0;
+
+
+static int    jvm_opts=0;
+static char **jvm_optv=0;
+
+#ifdef JNI_VERSION_1_2 
+static JavaVMOption *vm_options;
+static JavaVMInitArgs vm_args;
+#else  
+#error "Java/JNI 1.2 or higher is required!"
+#endif
+
+#define H_OUT  1
+#define H_EXIT 2
+
+#ifdef Win32
+/* the hooks are reportedly causing problems on Windows, so disable them by default */
+static int default_hooks = 0;
+#else
+static int default_hooks = H_OUT|H_EXIT;
+#endif
+
+static int JNICALL vfprintf_hook(FILE *f, const char *fmt, va_list ap) {
+#ifdef Win32
+  /* on Windows f doesn't refer to neither stderr nor stdout,
+     so we have no way of finding out the target, so we assume stderr */
+  REvprintf(fmt, ap);
+  return 0;
+#else
+  if (f==stderr) {
+    REvprintf(fmt, ap);
+    return 0;
+  } else if (f==stdout) {
+    Rvprintf(fmt, ap);
+    return 0;
+  }
+  return vfprintf(f, fmt, ap);
+#endif
+}
+
+static void JNICALL exit_hook(int status) {
+    /* REprintf("\nJava requested System.exit(%d), trying to raise R error - this may crash if Java is in a bad state.\n", status); */
+    java_is_dead = 1;
+    Rf_error("Java called System.exit(%d) requesting R to quit - trying to recover", status);
+    /* FIXME: we could do something smart here such as running a call-back
+       into R ... jump into R event loop ... at any rate we cannot return,
+       but we don't want to kill R ... */
+    exit(status);
+}
+
+/* in reality WIN64 implies WIN32 but to make sure ... */
+#if defined(_WIN64) || defined(_WIN32)
+#include <io.h>
+#include <fcntl.h>
+#endif
+
+static int initJVM(const char *user_classpath, int opts, char **optv, int hooks) {
+  int total_num_properties, propNum = 0;
+  jint res;
+  char *classpath;
+  
+  if(!user_classpath)
+    /* use the CLASSPATH environment variable as default */
+    user_classpath = getenv("CLASSPATH");
+  if(!user_classpath) user_classpath = "";
+  
+  vm_args.version = JNI_VERSION_1_2;
+  if(JNI_GetDefaultJavaVMInitArgs(&vm_args) != JNI_OK) {
+    error("JNI 1.2 or higher is required");
+    return -1;    
+  }
+    
+  /* leave room for class.path, and optional jni args */
+  total_num_properties = 6 + opts;
+    
+  vm_options = (JavaVMOption *) calloc(total_num_properties, sizeof(JavaVMOption));
+  vm_args.version = JNI_VERSION_1_2; /* should we do that or keep the default? */
+  vm_args.options = vm_options;
+  vm_args.ignoreUnrecognized = JNI_TRUE;
+  
+  classpath = (char*) calloc(24 + strlen(user_classpath), sizeof(char));
+  sprintf(classpath, "-Djava.class.path=%s", user_classpath);
+  
+  vm_options[propNum++].optionString = classpath;   
+  
+  /*   print JNI-related messages */
+  /* vm_options[propNum++].optionString = "-verbose:class,jni"; */
+  
+  if (optv) {
+    int i=0;
+    while (i<opts) {
+      if (optv[i]) vm_options[propNum++].optionString = optv[i];
+      i++;
+    }
+  }
+  if (hooks&H_OUT) {
+    vm_options[propNum].optionString = "vfprintf";
+    vm_options[propNum++].extraInfo  = vfprintf_hook;
+  }
+  if (hooks&H_EXIT) {
+    vm_options[propNum].optionString = "exit";
+    vm_options[propNum++].extraInfo  = exit_hook;
+  }
+  vm_args.nOptions = propNum;
+
+  /* Create the Java VM */
+  res = JNI_CreateJavaVM(&jvm,(void **)&eenv, &vm_args);
+  
+  if (res != 0)
+    error("Cannot create Java virtual machine (%d)", res);
+  if (!eenv)
+    error("Cannot obtain JVM environemnt");
+
+#if defined(_WIN64) || defined(_WIN32)
+  _setmode(0, _O_TEXT);
+#endif
+
+  return 0;
+}
+
+#ifdef THREADS
+#include <pthread.h>
+
+#ifdef XXDARWIN
+#include <Carbon/Carbon.h>
+#include <CoreFoundation/CoreFoundation.h>
+#include <CoreFoundation/CFRunLoop.h>
+#endif
+
+pthread_t initJVMpt;
+pthread_mutex_t initMutex = PTHREAD_MUTEX_INITIALIZER;
+
+int thInitResult = 0;
+int initAWT = 0;
+
+static void *initJVMthread(void *classpath)
+{
+  int ws;
+  jclass c;
+  JNIEnv *lenv;
+
+  thInitResult=initJVM((char*)classpath, jvm_opts, jvm_optv, default_hooks);
+  if (thInitResult) return 0;
+
+  init_rJava();
+
+  lenv = eenv; /* we make a local copy before unlocking just in case
+		  someone messes with it before we can use it */
+
+  _dbg(rjprintf("initJVMthread: unlocking\n"));
+  pthread_mutex_unlock(&initMutex);
+
+  if (initAWT) {
+    _dbg(rjprintf("initJVMthread: get AWT class\n"));
+    /* we are still on the same thread, so we can safely use eenv */
+    c = (*lenv)->FindClass(lenv, "java/awt/Frame");
+  }
+
+  _dbg(rjprintf("initJVMthread: returning from the init thread.\n"));
+  return 0;
+}
+
+#endif
+
+
+
+/* initialize internal structures/variables of rJava.
+   The JVM initialization was performed before (but may have failed)
+*/
+HIDE void init_rJava(void) {
+  jclass c;
+  JNIEnv *env = getJNIEnv();
+  if (!env) return; /* initJVMfailed, so we cannot proceed */
+  
+  /* get global classes. we make the references explicitely global (although unloading of String/Object is more than unlikely) */
+  c=(*env)->FindClass(env, "java/lang/String");
+  if (!c) error("unable to find the basic String class");
+  javaStringClass=(*env)->NewGlobalRef(env, c);
+  if (!javaStringClass) error("unable to create a global reference to the basic String class");
+  (*env)->DeleteLocalRef(env, c);
+
+  c=(*env)->FindClass(env, "java/lang/Object");
+  if (!c) error("unable to find the basic Object class");
+  javaObjectClass=(*env)->NewGlobalRef(env, c);
+  if (!javaObjectClass) error("unable to create a global reference to the basic Object class");
+  (*env)->DeleteLocalRef(env, c);
+
+  c = (*env)->FindClass(env, "java/lang/Class");
+  if (!c) error("unable to find the basic Class class");
+  javaClassClass=(*env)->NewGlobalRef(env, c);
+  if (!javaClassClass) error("unable to create a global reference to the basic Class class");
+  (*env)->DeleteLocalRef(env, c);
+
+  c = (*env)->FindClass(env, "java/lang/reflect/Field");
+  if (!c) error("unable to find the basic Field class");
+  javaFieldClass=(*env)->NewGlobalRef(env, c);
+  if (!javaFieldClass) error("unable to create a global reference to the basic Class class");
+  (*env)->DeleteLocalRef(env, c);
+
+  mid_forName  = (*env)->GetStaticMethodID(env, javaClassClass, "forName", "(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;");
+  if (!mid_forName) error("cannot obtain Class.forName method ID");
+  
+  mid_getName  = (*env)->GetMethodID(env, javaClassClass, "getName", "()Ljava/lang/String;");
+  if (!mid_getName) error("cannot obtain Class.getName method ID");
+  
+  mid_getSuperclass =(*env)->GetMethodID(env, javaClassClass, "getSuperclass", "()Ljava/lang/Class;");
+  if (!mid_getSuperclass) error("cannot obtain Class.getSuperclass method ID");
+  
+  mid_getField = (*env)->GetMethodID(env, javaClassClass, "getField",
+				     "(Ljava/lang/String;)Ljava/lang/reflect/Field;");
+  if (!mid_getField) error("cannot obtain Class.getField method ID");
+ 
+  mid_getType  = (*env)->GetMethodID(env, javaFieldClass, "getType",
+				     "()Ljava/lang/Class;");
+  if (!mid_getType) error("cannot obtain Field.getType method ID");
+
+  rJava_initialized = 1;
+}
+
+
+static SEXP RinitJVM_real(SEXP par)
+{
+  const char *c=0;
+  SEXP e=CADR(par);
+  int r=0;
+  JavaVM *jvms[32];
+  jsize vms=0;
+  
+  jvm_opts=0;
+  jvm_optv=0;
+  
+  if (TYPEOF(e)==STRSXP && LENGTH(e)>0)
+	  c=CHAR(STRING_ELT(e,0));
+
+  e = CADDR(par);
+  if (TYPEOF(e)==STRSXP && LENGTH(e)>0) {
+      int len = LENGTH(e), add_xrs = 1, joi = 0;
+      jvm_optv = (char**)malloc(sizeof(char*) * (len + 3));
+      if (!jvm_optv) Rf_error("Cannot allocate options buffer - out of memory");
+#ifdef USE_HEADLESS_INIT
+      /* prepend headless so the user can still override it */
+      jvm_optv[jvm_opts++] = "-Djava.awt.headless=true";
+#endif
+      while (joi < len) {
+	  jvm_optv[jvm_opts] = strdup(CHAR(STRING_ELT(e, joi++)));
+#ifdef HAVE_XRS
+	  /* check if Xrs is already used */
+	  if (!strcmp(jvm_optv[jvm_opts], "-Xrs"))
+	      add_xrs = 0;
+#endif
+	  jvm_opts++;
+      }
+#ifdef HAVE_XRS
+      if (add_xrs)
+	  jvm_optv[jvm_opts++] = "-Xrs";
+#endif
+  } else {
+#ifdef USE_HEADLESS_INIT
+      jvm_optv = (char**)malloc(sizeof(char*) * 3);
+      if (!jvm_optv) Rf_error("Cannot allocate options buffer - out of memory");
+      jvm_optv[jvm_opts++] = "-Djava.awt.headless=true";
+#endif
+#ifdef HAVE_XRS
+      if (!jvm_optv) jvm_optv = (char**)malloc(sizeof(char*) * 2);
+      if (!jvm_optv) Rf_error("Cannot allocate options buffer - out of memory");
+      jvm_optv[jvm_opts++] = "-Xrs";
+#endif
+  }
+  if (jvm_opts)
+      jvm_optv[jvm_opts] = 0;
+  
+  r=JNI_GetCreatedJavaVMs(jvms, 32, &vms);
+  if (r) {
+    Rf_error("JNI_GetCreatedJavaVMs returned %d\n", r);
+  } else {
+    if (vms>0) {
+      int i=0;
+      _dbg(rjprintf("RinitJVM: Total %d JVMs found. Trying to attach the current thread.\n", (int)vms));
+      while (i<vms) {
+	if (jvms[i]) {
+	  if (!(*jvms[i])->AttachCurrentThread(jvms[i], (void**)&eenv, NULL)) {
+            _dbg(rjprintf("RinitJVM: Attached to existing JVM #%d.\n", i+1));
+	    break;
+	  }
+	}
+	i++;
+      }
+      if (i==vms) Rf_error("Failed to attach to any existing JVM.");
+      else {
+	jvm = jvms[i];
+	init_rJava();
+      }
+      PROTECT(e=allocVector(INTSXP,1));
+      INTEGER(e)[0]=(i==vms)?-2:1;
+      UNPROTECT(1);
+      return e;
+    }
+  }
+
+#ifdef THREADS
+  if (getenv("R_GUI_APP_VERSION") || getenv("RJAVA_INIT_AWT"))
+    initAWT=1;
+
+  _dbg(rjprintf("RinitJVM(threads): launching thread\n"));
+  pthread_mutex_lock(&initMutex);
+  pthread_create(&initJVMpt, 0, initJVMthread, c);
+  _dbg(rjprintf("RinitJVM(threads): waiting for mutex\n"));
+  pthread_mutex_lock(&initMutex);
+  pthread_mutex_unlock(&initMutex);
+  /* pthread_join(initJVMpt, 0); */
+  _dbg(rjprintf("RinitJVM(threads): attach\n"));
+  /* since JVM was initialized by another thread, we need to attach ourselves */
+  (*jvm)->AttachCurrentThread(jvm, (void**)&eenv, NULL);
+  _dbg(rjprintf("RinitJVM(threads): done.\n"));
+  r = thInitResult;
+#else
+  profStart();
+  r=initJVM(c, jvm_opts, jvm_optv, default_hooks);
+  init_rJava();
+  _prof(profReport("init_rJava:"));
+  _dbg(rjprintf("RinitJVM(non-threaded): initJVM returned %d\n", r));
+#endif
+  if (jvm_optv) free(jvm_optv);
+  jvm_opts=0;
+  PROTECT(e=allocVector(INTSXP,1));
+  INTEGER(e)[0]=r;
+  UNPROTECT(1);
+  return e;
+}
+
+/* This is a workaround for another workaround in Oracle JVM.  On Linux, the
+   JVM would insert protected guard pages into the C stack of the R process
+   that initializes the JVM, thus effectively reducing the stack size.
+   Worse yet, R does not find out about this and fails to detect infinite
+   recursion. Without the workaround, this code crashes R after .jinit() is called
+
+   x <- 1; f <- function() { x <<- x + 1 ; print(x) ; f() } ; tryCatch(f(), error=function(e) x)
+
+   and various packages fail/segfault unpredictably as they reach the stack
+   limit.
+
+   This workaround in rJava can detect the reduction of the R stack and can
+   adjust R_CStack* variables so that the detection of infinite recursion
+   still works.  Moreover, the workaround in rJava can prevent significant
+   shrinking of the stack by allocating at least 2M from the C stack before
+   initializing the JVM.  This makes the JVM think that the current thread
+   is actually not the initial thread (os::Linux::is_initial_thread()
+   returns false), because is_initial_thread will run outside what the JVM
+   assumes is the stack for the initial thread (the JVM caps the stack to
+   2M).  Consequently, the JVM will not install guard pages.  The stack size
+   limit is implemented in os::Linux::capture_initial_stack (the limit 4M on
+   Itanium which is ignored here by rJava and 2M on other Linux systems) and
+   is claimed to be a workaround for issues in RH7.2.  The problem is still
+   present in JVM 9.  Moreover, on Linux the JVM inserts guard pages also
+   based on the setting of -Xss.
+*/
+
+#undef JVM_STACK_WORKAROUND
+#if defined(linux) || defined(__linux__) || defined(__linux)
+#define JVM_STACK_WORKAROUND
+#endif
+
+#ifdef JVM_STACK_WORKAROUND
+
+#include <stdint.h>
+
+ /* unfortunately this needs (write!) access to R internals */
+extern uintptr_t R_CStackLimit;
+extern uintptr_t R_CStackStart;
+extern int R_CStackDir;
+
+#include <sys/types.h>
+#include <sys/time.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include <errno.h>
+#include <sys/resource.h>
+#include <inttypes.h>
+
+/*
+  Find a new limit for the C stack, within the existing limit.  Looks for
+  the first address in the stack area that is not accessible to the current
+  process.  This code could easily be made to work on different Unix
+  systems, not just on Linux, but it does not seem necessary at the moment.
+
+  from is the first address to access
+  limit is the first address not to access
+  bound is the new first address not to access
+  dir is 1 (stack grows up) or -1 (stack grows down, the usual)
+    so, incrementing by dir one traverses from stack start, from the oldest
+    things on the stace; note that in R_CStackDir, 1 means stack grows down
+
+  returns NULL in case of error, limit when no new limit is found,
+    a new limit when found
+
+  returns NULL when from == limit
+*/
+
+volatile int globald = 0;
+static char* findBound(char *from, char *limit, int dir)
+{
+  int pipefd[2];
+  pid_t cpid;
+    /* any positive size could be used, using page size is a heuristic */
+  int psize = (int) sysconf(_SC_PAGESIZE);
+  char buf[psize];
+
+  if ((dir==-1 && from<=limit) || (dir == 1 && from>=limit))
+    return NULL;
+
+  if (pipe(pipefd) == -1)
+    return NULL; /* error */
+
+  cpid = fork();
+  if (cpid == -1)
+    return NULL; /* error */
+
+  if (cpid == 0) {
+    /* child process, reads from the pipe */
+    close(pipefd[1]);
+
+    while (read(pipefd[0], &buf, psize) > 0);
+    _exit(0);
+  } else {
+    /* Parent process, writes data to the pipe looking for EFAULT error which
+       indicates an inaccesible page. For performance, the reading is first
+       done using a buffer (of the size of a page), but once EFAULT is reached,
+       it is re-tried byte-by-byte for the last buffer not read successfully.
+    */
+    close(pipefd[0]);
+    intmax_t diff = imaxabs(from-limit);
+    int step = (diff < psize) ? diff : psize;
+    int failed = 0;
+    int reached_fault = 0;
+    char *origfrom = from;
+
+    /* start search at bigger granularity for performance */
+    for(; (dir == -1) ? (from-step+1 >= limit) : (from+step-1 <= limit)
+        ; from += dir * step)
+
+      if (write(pipefd[1], (dir == -1) ? (from-step+1) : from, step) == -1) {
+        if (errno == EFAULT)
+          reached_fault = 1;
+        else
+          failed = 1;
+        break;
+      }
+
+    /* finetune with step 1 */
+    if (reached_fault && step > 1 && origfrom != from)
+      for(from -= dir * step; from != limit ; from += dir)
+        if (write(pipefd[1], from, 1) == -1) {
+          if (errno != EFAULT)
+            failed = 1;
+          break;
+        }
+    close(pipefd[1]);
+    wait(NULL);
+    return failed ? NULL : from;
+  }
+}
+
+/* Add certain amount of padding to the C stack before invoking RinitJVM.
+   The recursion turned out more reliable in face of compiler optimizations
+   than allocating large arrays on the C stack, both via definition and
+   alloca. */
+static SEXP RinitJVM_with_padding(SEXP par, intptr_t padding, char *last) {
+  char dummy[1];
+    /* reduce the risk that dummy will be optimized out */
+  dummy[0] = (char) (uintptr_t) &dummy;
+  padding -= (last - dummy) * R_CStackDir;
+  if (padding <= 0)
+    return RinitJVM_real(par);
+  else
+    return RinitJVM_with_padding(par, padding, dummy);
+}
+
+/* Run RinitJVM with the Java stack workaround */
+static SEXP RinitJVM_jsw(SEXP par) {
+
+  /* One can disable the workaround using environment variable
+     RJAVA_JVM_STACK_WORKAROUND
+
+     this support exists for diagnostics and as a way to disable the
+     workaround without re-compiling rJava.  In normal cases it only makes
+     sense to use the default value of 3.
+   */
+
+  #define JSW_DISABLED 0
+  #define JSW_DETECT   1
+  #define JSW_ADJUST   2
+  #define JSW_PREVENT  3
+
+  #define JSW_PADDING 2*1024*1024
+  #define JSW_CHECK_BOUND 16*1024*1024
+
+  /* 0 - disabled
+     1 - detect guard pages
+     2 - detect guard pages and adjust R stack size
+     3 - prevent guard page creation, detect, and adjust */
+  int val = JSW_PREVENT;
+  char *vval = getenv("RJAVA_JVM_STACK_WORKAROUND");
+  if (vval != NULL)
+    val = atoi(vval);
+  if (val < 0 || val > 3)
+    error("Invalid value for RJAVA_JVM_STACK_WORKAROUND");
+
+  _dbg(rjprintf("JSW workaround: (level %d)\n", val));
+
+  if (val == JSW_DISABLED)
+    return RinitJVM_real(par);
+
+  /* Figure out the original stack limit */
+  uintptr_t rlimsize = 0;
+
+  struct rlimit rlim;
+  if (getrlimit(RLIMIT_STACK, &rlim) == 0) {
+    rlim_t lim = rlim.rlim_cur;
+    if (lim != RLIM_INFINITY) {
+      rlimsize = (uintptr_t)lim;
+       _dbg(rjprintf("  RLIMIT_STACK (rlimsize) %lu\n",
+                     (unsigned long) rlimsize));
+    } else {
+       _dbg(rjprintf("  RLIMIT_STACK unlimited\n"));
+    }
+  }
+
+  if (rlimsize == 0 && R_CStackLimit != -1) {
+    /* getrlimit should work on linux, so this should only happen
+       when stack size is unlimited */
+    rlimsize = (uintptr_t) (R_CStackLimit / 0.95);
+    _dbg(rjprintf("  expanded R_CStackLimit (rlimsize) %lu\n",
+                  (unsigned long) rlimsize));
+  }
+
+  if (rlimsize == 0 || rlimsize > JSW_CHECK_BOUND) {
+    /* use a reasonable limit when looking for guard pages when
+       stack size is unlimited or very large  */
+    rlimsize = JSW_CHECK_BOUND;
+    _dbg(rjprintf("  hardcoded rlimsize %lu\n",
+                  (unsigned long) rlimsize));
+  }
+
+  _dbg(rjprintf("  R_CStackStart %p\n", R_CStackStart));
+  _dbg(rjprintf("  R_CStackLimit %lu\n", (unsigned long)R_CStackLimit));
+  char *maxBound = (char *)((intptr_t)R_CStackStart - (intptr_t)R_CStackDir*rlimsize);
+  char *oldBound = findBound((char*)R_CStackStart - R_CStackDir, maxBound, -R_CStackDir);
+  _dbg(rjprintf("  maxBound %p\n", maxBound));
+  _dbg(rjprintf("  oldBound %p\n", oldBound));
+
+  /* it is expected that newBound < maxBound, because not all of the "rlim"
+     stack may be accessible even before JVM initialization, which can be e.g.
+     because of an imprecise detection of the stack start */
+
+  intptr_t padding = 0;
+  if (val >= JSW_PREVENT) {
+    int dummy;
+    intptr_t usage = R_CStackDir * (R_CStackStart - (uintptr_t)&dummy);
+    usage += JSW_PADDING + 512; /* 512 is a buffer for C recursive calls */
+    if(R_CStackLimit == -1 || usage < ((intptr_t) R_CStackLimit))
+      padding = JSW_PADDING;
+  }
+
+  char dummy[1];
+    /* reduce the risk that dummy will be optimized out */
+  dummy[0] = (char) (uintptr_t) &dummy;
+  SEXP ans = PROTECT(RinitJVM_with_padding(par, padding, dummy));
+  _dbg(rjprintf("JSW workaround (ctd): (level %d)\n", val));
+
+  if (val >= JSW_DETECT) {
+
+    char *newBound = findBound((char*)R_CStackStart - R_CStackDir, oldBound, -R_CStackDir);
+    _dbg(rjprintf("  newBound %p\n", newBound));
+    if (oldBound == newBound) {
+      /* No guard pages inserted, keep the original stack size.
+         This includes the case when the original stack size was
+         unlimited. */
+      UNPROTECT(1); /* ans */
+      return ans;
+    }
+
+    intptr_t newb = (intptr_t)newBound;
+    intptr_t lim = ((intptr_t)R_CStackStart - newb) * R_CStackDir;
+    uintptr_t newlim = (uintptr_t) (lim * 0.95);
+
+    uintptr_t oldlim = R_CStackLimit;
+    if (val >= JSW_ADJUST) {
+      R_CStackLimit = newlim;
+      _dbg(rjprintf("  new R_CStackLimit %lu\n", (unsigned long)R_CStackLimit));
+    }
+
+    /* Only report when the loss is big. There may be some bytes
+       lost because even with the original setting of R_CStackLimit before
+       initializing the JVM, one may not be able to access all bytes of stack
+       (e.g. because of imprecise detection of the stack start). */
+
+    int bigloss = 0;
+    if (oldlim == -1) {
+      /* the message may be confusing when R_CStackLimit was set to -1
+         because the original stack size was too large */
+      REprintf("Rjava.init.warning: stack size reduced from unlimited to"
+        " %u bytes after JVM initialization.\n", newlim);
+      bigloss = 1;
+    } else {
+      unsigned lost = (unsigned) (oldlim - newlim);
+      if (lost > oldlim * 0.01) {
+        REprintf("Rjava.init.warning: lost %u bytes of stack after JVM"
+          " initialization.\n", lost);
+        bigloss = 1;
+      }
+    }
+
+    if (bigloss) {
+      if (val >= JSW_PREVENT && padding == 0)
+        REprintf("Rjava.init.warning: re-try with increased"
+          " stack size via ulimit -s to allow for a work-around.\n");
+      if (val < JSW_ADJUST)
+        REprintf("Rjava.init.warning: R may crash in recursive calls.\n");
+    }
+  }
+
+  UNPROTECT(1); /* ans */
+  return ans;
+}
+
+#endif /* JVM_STACK_WORKAROUND */
+
+/** RinitJVM(classpath)
+    initializes JVM with the specified class path */
+REP SEXP RinitJVM(SEXP par) {
+
+#ifndef JVM_STACK_WORKAROUND
+  return RinitJVM_real(par);
+#else
+  return RinitJVM_jsw(par);
+#endif
+}
+
+REP void doneJVM() {
+  (*jvm)->DestroyJavaVM(jvm);
+  jvm = 0;
+  eenv = 0;
+}
+
+/**
+ * Initializes the cached values of classes and methods used internally
+ * These classes and methods are the ones that are in rJava (RJavaTools, ...)
+ * not java standard classes (Object, Class)
+ */ 
+REPC SEXP initRJavaTools(){
+
+	JNIEnv *env=getJNIEnv();
+	jclass c; 
+	
+	/* classes */
+	
+	/* RJavaTools class */
+	c = findClass(env, "RJavaTools", oClassLoader);
+	if (!c) error("unable to find the RJavaTools class");
+	rj_RJavaTools_Class=(*env)->NewGlobalRef(env, c);
+	if (!rj_RJavaTools_Class) error("unable to create a global reference to the RJavaTools class");
+	(*env)->DeleteLocalRef(env, c);
+	
+	/* RJavaImport */
+	c = findClass(env, "RJavaImport", oClassLoader); 
+	if (!c) error("unable to find the RJavaImport class");
+	rj_RJavaImport_Class=(*env)->NewGlobalRef(env, c);
+	if (!rj_RJavaImport_Class) error("unable to create a global reference to the RJavaImport class");
+	(*env)->DeleteLocalRef(env, c);
+	
+	
+	/* methods */
+	
+	mid_RJavaTools_getFieldTypeName  = (*env)->GetStaticMethodID(env, rj_RJavaTools_Class, 
+		"getFieldTypeName", "(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/String;");
+	if (!mid_RJavaTools_getFieldTypeName) error("cannot obtain RJavaTools.getFieldTypeName method ID");
+	
+	mid_rj_getSimpleClassNames  = (*env)->GetStaticMethodID(env, rj_RJavaTools_Class, 
+		"getSimpleClassNames", "(Ljava/lang/Object;Z)[Ljava/lang/String;");
+	if (!mid_rj_getSimpleClassNames) error("cannot obtain RJavaTools.getDimpleClassNames method ID");
+	
+	mid_RJavaImport_getKnownClasses = (*env)->GetMethodID(env, rj_RJavaImport_Class, 
+		"getKnownClasses", "()[Ljava/lang/String;");
+	if (!mid_RJavaImport_getKnownClasses) error("cannot obtain RJavaImport.getKnownClasses method ID");
+	
+	mid_RJavaImport_lookup = (*env)->GetMethodID(env, rj_RJavaImport_Class, 
+		"lookup", "(Ljava/lang/String;)Ljava/lang/Class;");
+	if( !mid_RJavaImport_lookup) error("cannot obtain RJavaImport.lookup method ID");
+	
+	mid_RJavaImport_exists = (*env)->GetMethodID(env, rj_RJavaImport_Class, 
+		"exists", "(Ljava/lang/String;)Z");
+	if( ! mid_RJavaImport_exists ) error("cannot obtain RJavaImport.exists method ID");
+	// maybe add RJavaArrayTools, ...
+	
+	return R_NilValue; 
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/install.libs.R b/com.oracle.truffle.r.pkgs/rJava/src/install.libs.R
new file mode 100644
index 0000000000000000000000000000000000000000..e9eb97ac3328f5063e1f99b888a7326badcc6dc6
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/install.libs.R
@@ -0,0 +1,53 @@
+## the first part just replicates the default installation of libs
+libarch <- if (nzchar(R_ARCH)) paste("libs", R_ARCH, sep='') else "libs"
+dest <- file.path(R_PACKAGE_DIR, libarch)
+files <- Sys.glob(paste("*", SHLIB_EXT, sep=''))
+if (length(files)) {
+  dir.create(dest, recursive = TRUE, showWarnings = FALSE)
+  file.copy(files, dest, overwrite = TRUE)
+  if (nzchar(Sys.getenv("PKG_MAKE_DSYM")) && length(grep("^darwin", R.version$os))) {
+    message('generating debug symbols (dSYM)')
+    dylib <- Sys.glob(paste(dest, "/*", SHLIB_EXT, sep=''))
+    if (length(dylib)) for (file in dylib) system(paste("dsymutil ", file, sep=''))
+  }
+}
+
+# just a wrapper to system() that shows what we are doing ...
+sys <- function(x, ...) {
+  message(x)
+  s <- system(x, ...)
+#  if (!isTRUE(s == 0L)) message("-> FAILED")
+  s
+}
+
+## the next part is about JRI
+## on OS X we need to merge architectures into one fat file
+if (length(grep("^darwin", R.version$os))) {
+  is.fat <- function(fn) { a <- 0L; try({f <- file(fn, "rb"); a <- readBin(f, 1L, 1L); close(f)}, silent=TRUE); isTRUE(a[1] == -1095041334L || a[1] == -889275714L) } ## fat magic is 0xCAFEBABE - either endianness
+  jni <- "../jri/libjri.jnilib"
+  if (isTRUE(file.exists(jni))) { ## continue only if JRI was actually compiled
+    dir.create(file.path(R_PACKAGE_DIR, "jri"), recursive = TRUE, showWarnings = FALSE)
+    dest <- file.path(R_PACKAGE_DIR, "jri", "libjri.jnilib")
+    if (is.fat(jni) || !file.exists(dest)) {
+      ## if the new file is fat we assume it has all archs so we copy; if there is no dest, copy as well
+      file.copy(jni, dest, overwrite = TRUE)
+    } else { ## new file is single arch, so merge
+      ## we try lipo -create first and fall back to -replace if it doesn't work (becasue the arch exists already)
+      if (sys(paste("/usr/bin/lipo -create", shQuote(dest), jni, "-o", shQuote(dest), ">/dev/null 2>&1")) != 0) {
+        if (is.fat(dest)) { # if the file is fat, replace, otherwise it means we have the same arch so copy
+          arch <- gsub("/", "", R_ARCH, fixed=TRUE)
+          sys(paste("/usr/bin/lipo -replace", arch, jni, shQuote(dest), "-o", shQuote(dest), ">/dev/null 2>&1"))
+        } else file.copy(jni, dest, overwrite = TRUE)
+      }
+    }
+  }
+} else { ## on other platforms we simply install in jri$(R_ARCH)
+  jri <- if (WINDOWS) "jri.dll" else "libjri.so"
+  jni <- file.path("..", "jri", jri)
+  if (isTRUE(file.exists(jni))) { ## continue only if JRI was actually compiled
+    libarch <- if (nzchar(R_ARCH)) paste("jri", R_ARCH, sep='') else "jri"
+    dir.create(file.path(R_PACKAGE_DIR, libarch), recursive = TRUE, showWarnings = FALSE)
+    dest <- file.path(R_PACKAGE_DIR, libarch, jri)
+    file.copy(jni, dest, overwrite = TRUE)
+  }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/ArrayDimensionException.java b/com.oracle.truffle.r.pkgs/rJava/src/java/ArrayDimensionException.java
new file mode 100644
index 0000000000000000000000000000000000000000..b8aaf4de65be91c25f92fa09031de93fe47198a4
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/ArrayDimensionException.java
@@ -0,0 +1,5 @@
+public class ArrayDimensionException extends Exception{
+	public ArrayDimensionException(String message){
+		super( message ) ; 
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/ArrayWrapper.java b/com.oracle.truffle.r.pkgs/rJava/src/java/ArrayWrapper.java
new file mode 100644
index 0000000000000000000000000000000000000000..1b45bce9a9ed1a02df5f77054b0f3e86464a6523
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/ArrayWrapper.java
@@ -0,0 +1,376 @@
+// :tabSize=2:indentSize=2:noTabs=false:folding=explicit:collapseFolds=1:
+
+import java.lang.reflect.Array ; 
+
+/** 
+ * Utility class to deal with arrays
+ */
+public class ArrayWrapper extends RJavaArrayIterator {
+
+	/**
+	 * is this array rectangular
+	 */ 
+	private boolean isRect ;
+	
+	/**
+	 * The type name of the objects stored
+	 */
+	private String typeName ;
+	
+	/**
+	 * true if the array stores primitive types
+	 */
+	private boolean primitive ;
+	
+	private int length ; 
+	
+	/**
+	 * Constructor
+	 *
+	 * @param array the array to check
+	 * @throws NotAnArrayException if array is not an array
+	 */
+	public ArrayWrapper(Object array) throws NotAnArrayException {
+		super( RJavaArrayTools.getDimensions(array) );
+		this.array = array ;
+		typeName = RJavaArrayTools.getObjectTypeName(array );
+		primitive = RJavaArrayTools.isPrimitiveTypeName( typeName ) ;
+		if( dimensions.length == 1){
+			isRect = true ;
+		} else{
+			isRect = isRectangular_( array, 0 );
+		}
+		// reset the dimensions if the array is not rectangular
+		if( !isRect ){
+			dimensions = null ;
+			length = -1; 
+		} else{
+			length = 1; 
+			for( int i=0; i<dimensions.length; i++) {
+				length *= dimensions[i] ;
+			}
+		}
+	}
+	
+	// making java < 1.5 happy
+	public ArrayWrapper(int x)      throws NotAnArrayException { throw new NotAnArrayException("primitive type") ; }
+	public ArrayWrapper(boolean x)  throws NotAnArrayException { throw new NotAnArrayException("primitive type") ; }
+	public ArrayWrapper(byte x)     throws NotAnArrayException { throw new NotAnArrayException("primitive type") ; }
+	public ArrayWrapper(long x)     throws NotAnArrayException { throw new NotAnArrayException("primitive type") ; }
+	public ArrayWrapper(short x)    throws NotAnArrayException { throw new NotAnArrayException("primitive type") ; }
+	public ArrayWrapper(double x)   throws NotAnArrayException { throw new NotAnArrayException("primitive type") ; }
+	public ArrayWrapper(char x)     throws NotAnArrayException { throw new NotAnArrayException("primitive type") ; }
+	public ArrayWrapper(float x)    throws NotAnArrayException { throw new NotAnArrayException("primitive type") ; }
+	
+	
+	/**
+	 * @return true if the array is rectangular
+	 */
+	public boolean isRectangular( ){
+		return isRect ;
+	}
+	
+	/**
+	 * Recursively check all dimensions to see if an array is rectangular
+	 */
+	private boolean isRectangular_(Object o, int depth){
+		if( depth == dimensions.length ) return true ; 
+		int n = Array.getLength(o) ;
+		if( n != dimensions[depth] ) return false ;
+		for( int i=0; i<n; i++){
+			if( !isRectangular_(Array.get(o, i),  depth+1) ){
+				return false;
+			}
+		}
+		return true ;
+	}
+	
+	/**
+	 * @return the type name of the objects stored in the wrapped array
+	 */
+	public String getObjectTypeName(){
+		return typeName; 
+	}
+	
+	/** 
+	 * @return true if the array contains java primitive types
+	 */ 
+	public boolean isPrimitive(){
+		return primitive ; 
+	}
+	
+	// {{{ flat_* methods
+	
+	// {{{ flat_int
+	/**
+	 * Flattens the array into a single dimensionned int array
+	 */ 
+	public int[] flat_int() throws PrimitiveArrayException,FlatException {
+		
+		if( ! "I".equals(typeName) ) throw new PrimitiveArrayException("int"); 
+		if( !isRect ) throw new FlatException(); 
+		if( dimensions.length == 1 ){
+			return (int[])array ;
+		} else{
+			int[] payload = new int[length] ;
+			
+			int k; 
+			while( hasNext() ){
+				int[] current = (int[])next() ;
+				k = start ; 
+				for( int j=0; j<current.length; j++, k+=increment){
+					payload[k] = current[j] ;
+				}
+			}
+			return payload ; 
+		}
+	}
+	// }}}
+	
+	// {{{ flat_boolean
+	/**
+	 * Flattens the array into a single dimensionned boolean array
+	 * 
+	 */ 
+	public boolean[] flat_boolean() throws PrimitiveArrayException,FlatException {
+		
+		if( ! "Z".equals(typeName) ) throw new PrimitiveArrayException("boolean"); 
+		if( !isRect ) throw new FlatException(); 
+		if( dimensions.length == 1 ){
+			return (boolean[])array ;
+		} else{
+			boolean[] payload = new boolean[length] ;
+			
+			int k; 
+			while( hasNext() ){
+				boolean[] current = (boolean[])next() ;
+				k = start ; 
+				for( int j=0; j<current.length; j++, k+=increment){
+					payload[k] = current[j] ;
+				}
+			}
+			return payload ;
+		}
+	}
+	// }}}
+	
+	// {{{ flat_byte
+	/**
+	 * Flattens the array into a single dimensionned byte array
+	 * 
+	 */ 
+	public byte[] flat_byte() throws PrimitiveArrayException,FlatException {
+		
+		if( ! "B".equals(typeName) ) throw new PrimitiveArrayException("byte"); 
+		if( !isRect ) throw new FlatException(); 
+		if( dimensions.length == 1 ){
+			return (byte[])array ;
+		} else{
+			byte[] payload = new byte[length] ;
+			int k; 
+			while( hasNext() ){
+				byte[] current = (byte[])next() ;
+				k = start ; 
+				for( int j=0; j<current.length; j++, k+=increment){
+					payload[k] = current[j] ;
+				}
+			}
+			return payload ;  
+		}
+	}
+
+	// }}}
+	
+	// {{{ flat_long
+	/**
+	 * Flattens the array into a single dimensionned long array
+	 * 
+	 */ 
+	public long[] flat_long() throws PrimitiveArrayException,FlatException {
+		
+		if( ! "J".equals(typeName) ) throw new PrimitiveArrayException("long"); 
+		if( !isRect ) throw new FlatException(); 
+		if( dimensions.length == 1 ){
+			return (long[])array ;
+		} else{
+			long[] payload = new long[length] ;
+			int k; 
+			while( hasNext() ){
+				long[] current = (long[])next() ;
+				k = start ; 
+				for( int j=0; j<current.length; j++, k+=increment){
+					payload[k] = current[j] ;
+				}
+			}
+			return payload ; 
+		}
+	}
+	
+	// }}}
+	
+	// {{{ flat_short
+	/**
+	 * Flattens the array into a single dimensionned short array
+	 * 
+	 */ 
+		public short[] flat_short() throws PrimitiveArrayException,FlatException {
+		
+		if( ! "S".equals(typeName) ) throw new PrimitiveArrayException("short"); 
+		if( !isRect ) throw new FlatException(); 
+		if( dimensions.length == 1 ){
+			return (short[])array ;
+		} else{
+			short[] payload = new short[length] ;
+			int k; 
+			while( hasNext() ){
+				short[] current = (short[])next() ;
+				k = start ; 
+				for( int j=0; j<current.length; j++, k+=increment){
+					payload[k] = current[j] ;
+				}
+			}
+			return payload ;
+ 		}
+	}
+// }}}
+
+	// {{{ flat_double
+	/**
+	 * Flattens the array into a single dimensionned double array
+	 * 
+	 */ 
+	public double[] flat_double() throws PrimitiveArrayException,FlatException {
+		
+		if( ! "D".equals(typeName) ) throw new PrimitiveArrayException("double"); 
+		if( !isRect ) throw new FlatException(); 
+		if( dimensions.length == 1 ){
+			return (double[])array ;
+		} else{
+			double[] payload= new double[length] ;
+			int k; 
+			while( hasNext() ){
+				double[] current = (double[])next() ;
+				k = start ; 
+				for( int j=0; j<current.length; j++, k+=increment){
+					payload[k] = current[j] ;
+				}
+			}
+			return payload ;
+ 		}
+	}
+
+	// }}}
+	
+	// {{{ flat_char
+	/**
+	 * Flattens the array into a single dimensionned double array
+	 * 
+	 */ 
+	public char[] flat_char() throws PrimitiveArrayException,FlatException {
+		
+		if( ! "C".equals(typeName) ) throw new PrimitiveArrayException("char"); 
+		if( !isRect ) throw new FlatException(); 
+		if( dimensions.length == 1 ){
+			return (char[])array ;
+		} else{
+			char[] payload = new char[length] ;
+			int k; 
+			while( hasNext() ){
+				char[] current = (char[])next() ;
+				k = start ; 
+				for( int j=0; j<current.length; j++, k+=increment){
+					payload[k] = current[j] ;
+				}
+			}
+			return payload ; 
+		}
+	}
+	
+	// }}}
+
+	// {{{ flat_float
+	/**
+	 * Flattens the array into a single dimensionned float array
+	 * 
+	 */ 
+	public float[] flat_float() throws PrimitiveArrayException,FlatException {
+		
+		if( ! "F".equals(typeName) ) throw new PrimitiveArrayException("float"); 
+		if( !isRect ) throw new FlatException(); 
+		if( dimensions.length == 1 ){
+			return (float[])array ;
+		} else{
+			float[] payload = new float[length] ;
+			int k; 
+			while( hasNext() ){
+				float[] current = (float[])next() ;
+				k = start ; 
+				for( int j=0; j<current.length; j++, k+=increment){
+					payload[k] = current[j] ;
+				}
+			}
+			return payload ; 
+		}
+	}
+	
+	// }}}
+	
+	// {{{ flat_Object
+	public Object[] flat_Object() throws FlatException, ObjectArrayException {
+		if( isPrimitive() ) throw new ObjectArrayException( typeName) ; 
+		if( !isRect ) throw new FlatException(); 
+		if( dimensions.length == 1 ){
+			return (Object[])array ;
+		} else{
+			ClassLoader loader = array.getClass().getClassLoader() ;
+			Class type = Object.class; 
+			try{
+				type = Class.forName( typeName, true, array.getClass().getClassLoader() );
+			} catch( ClassNotFoundException e){}
+			
+			Object[] payload = (Object[])Array.newInstance( type,  length ) ; 
+			int k; 
+			while( hasNext() ){
+				Object[] current = (Object[])next() ;
+				k = start ; 
+				for( int j=0; j<current.length; j++, k+=increment){
+					payload[k] = type.cast( current[j] );
+				}
+			}
+			return payload ; 
+		}
+	}
+	// }}}
+	
+	// {{{ flat_String
+	/**
+	 * Flattens the array into a single dimensionned String array
+	 * 
+	 */ 
+	// this is technically not required as this can be handled
+	// by flat_Object but this is slightly more efficient so ...
+	public String[] flat_String() throws PrimitiveArrayException,FlatException {
+		
+		if( ! "java.lang.String".equals(typeName) ) throw new PrimitiveArrayException("java.lang.String"); 
+		if( !isRect ) throw new FlatException(); 
+		if( dimensions.length == 1 ){
+			return (String[])array ;
+		} else{
+			String[] payload = new String[length] ;
+			int k; 
+			while( hasNext() ){
+				String[] current = (String[])next() ;
+				k = start ; 
+				for( int j=0; j<current.length; j++, k+=increment){
+					payload[k] = current[j] ;
+				}
+			}
+			return payload ; 
+		}
+	}
+	// }}}
+	
+	// }}}
+	
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/ArrayWrapper_Test.java b/com.oracle.truffle.r.pkgs/rJava/src/java/ArrayWrapper_Test.java
new file mode 100644
index 0000000000000000000000000000000000000000..8a4c78262d2347ee145ad5f4273b2574e857c4d2
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/ArrayWrapper_Test.java
@@ -0,0 +1,1562 @@
+// :tabSize=2:indentSize=2:noTabs=false:folding=explicit:collapseFolds=1:
+
+/**
+ * Test suite for ArrayWrapper 
+ */
+public class ArrayWrapper_Test {
+
+	// {{{ main
+	public static void main(String[] args ){
+		try{
+			runtests() ;
+		} catch( TestException e){
+			e.printStackTrace(); 
+			System.exit(1); 
+		}
+		System.out.println( "\nALL PASSED\n" ) ; 
+		System.exit( 0 ); 
+	}
+	// }}}
+	
+	// {{{ runtests
+	public static void runtests() throws TestException {
+		
+		// {{{ multi dim array of primitives 
+		
+		// {{{ flat_int
+		System.out.println( "flatten int[]" ); 
+		flatten_int_1(); 
+		System.out.println( "PASSED" ); 
+		
+		System.out.println( "flatten int[][]" ); 
+		flatten_int_2(); 
+		System.out.println( "PASSED" ); 
+		
+		System.out.println( "flatten int[][][]" ); 
+		flatten_int_3(); 
+		System.out.println( "PASSED" );
+		// }}}
+		
+		// {{{ flat_boolean
+		System.out.println( "flatten boolean[]" ); 
+		flatten_boolean_1(); 
+		System.out.println( "PASSED" ); 
+		
+		System.out.println( "flatten boolean[][]" ); 
+		flatten_boolean_2(); 
+		System.out.println( "PASSED" ); 
+		
+		System.out.println( "flatten boolean[][][]" ); 
+		flatten_boolean_3(); 
+		System.out.println( "PASSED" );
+		// }}}
+		
+		// {{{ flat_byte
+		System.out.println( "flatten byte[]" ); 
+		flatten_byte_1(); 
+		System.out.println( "PASSED" ); 
+		
+		System.out.println( "flatten byte[][]" ); 
+		flatten_byte_2(); 
+		System.out.println( "PASSED" ); 
+		
+		System.out.println( "flatten byte[][][]" ); 
+		flatten_byte_3(); 
+		System.out.println( "PASSED" );
+		// }}}
+		
+		// {{{ flat_long
+		System.out.println( "flatten long[]" ); 
+		flatten_long_1(); 
+		System.out.println( "PASSED" ); 
+		
+		System.out.println( "flatten long[][]" ); 
+		flatten_long_2(); 
+		System.out.println( "PASSED" ); 
+		
+		System.out.println( "flatten long[][][]" ); 
+		flatten_long_3(); 
+		System.out.println( "PASSED" );
+		// }}}
+		
+		// {{{ flat_long
+		System.out.println( "flatten short[]" ); 
+		flatten_short_1(); 
+		System.out.println( "PASSED" ); 
+		
+		System.out.println( "flatten short[][]" ); 
+		flatten_short_2(); 
+		System.out.println( "PASSED" ); 
+		
+		System.out.println( "flatten short[][][]" ); 
+		flatten_short_3(); 
+		System.out.println( "PASSED" );
+		// }}}
+
+		// {{{ flat_double
+		System.out.println( "flatten double[]" ); 
+		flatten_double_1(); 
+		System.out.println( "PASSED" ); 
+		
+		System.out.println( "flatten double[][]" ); 
+		flatten_double_2(); 
+		System.out.println( "PASSED" ); 
+		
+		System.out.println( "flatten double[][][]" ); 
+		flatten_double_3(); 
+		System.out.println( "PASSED" );
+		// }}}
+
+		// {{{ flat_char
+		System.out.println( "flatten char[]" ); 
+		flatten_char_1(); 
+		System.out.println( "PASSED" ); 
+		
+		System.out.println( "flatten char[][]" ); 
+		flatten_char_2(); 
+		System.out.println( "PASSED" ); 
+		
+		System.out.println( "flatten char[][][]" ); 
+		flatten_char_3(); 
+		System.out.println( "PASSED" );
+		// }}}
+		
+		// {{{ flat_float
+		System.out.println( "flatten float[]" ); 
+		flatten_float_1(); 
+		System.out.println( "PASSED" ); 
+		
+		System.out.println( "flatten float[][]" ); 
+		flatten_float_2(); 
+		System.out.println( "PASSED" ); 
+		
+		System.out.println( "flatten float[][][]" ); 
+		flatten_float_3(); 
+		System.out.println( "PASSED" );
+		// }}}
+		// }}}
+		
+		// {{{ multi dim array of Object
+		// {{{ flat_String
+		System.out.println( "flatten String[]" ); 
+		flatten_String_1(); 
+		System.out.println( "PASSED" ); 
+		
+		System.out.println( "flatten String[][]" ); 
+		flatten_String_2(); 
+		System.out.println( "PASSED" ); 
+		
+		System.out.println( "flatten String[][][]" ); 
+		flatten_String_3(); 
+		System.out.println( "PASSED" );
+		// }}}
+		
+			// {{{ flat_String
+		System.out.println( "flatten Point[]" ); 
+		flatten_Point_1(); 
+		System.out.println( "PASSED" ); 
+		
+		System.out.println( "flatten Point[][]" ); 
+		flatten_Point_2(); 
+		System.out.println( "PASSED" ); 
+		
+		System.out.println( "flatten Point[][][]" ); 
+		flatten_Point_3(); 
+		System.out.println( "PASSED" );
+		// }}}
+	
+		// }}}
+	}
+	//}}}
+	
+	// {{{ flat multi dimen array of java primitives
+	
+	// {{{ flatten_int_1
+	private static void flatten_int_1() throws TestException{
+		
+		int[] o = new int[5] ;
+		for( int i=0;i<5;i++) o[i] = i ;
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( int[] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(int[]) >> NotAnArrayException ") ; 
+		} 
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(int[]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("I") ){
+			throw new TestException( "ArrayWrapper(int[]).getObjectTypeName() != 'I'" ) ;
+		}
+		System.out.println( " I : ok" ); 
+		
+		System.out.print( "  >> flat_int()" ) ;
+		int[] flat;
+		try{
+			flat = wrapper.flat_int() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(int[]) >> FlatException") ;
+		}
+		
+		for( int i=0; i<5; i++){
+			if( flat[i] != i ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	
+	// {{{ flatten_int_2
+	private static void flatten_int_2() throws TestException{
+		
+		int[][] o = RectangularArrayExamples.getIntDoubleRectangularArrayExample(); 
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( int[][] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(int[][]) >> NotAnArrayException ") ; 
+		} 
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(int[][]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("I") ){
+			throw new TestException( "ArrayWrapper(int[][]).getObjectTypeName() != 'I'" ) ;
+		}
+		System.out.println( " I : ok" ); 
+		
+		System.out.print( "  >> flat_int()" ) ;
+		int[] flat;
+		try{
+			flat = wrapper.flat_int() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(int[][]) >> FlatException") ;
+		}
+		
+		
+		for( int i=0; i<10; i++){
+			if( flat[i] != i ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	
+  // {{{ flatten_int_3
+	private static void flatten_int_3() throws TestException{
+		
+		int[][][] o = RectangularArrayExamples.getIntTripleRectangularArrayExample(); 
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( int[][][] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(int[][][]) >> NotAnArrayException ") ; 
+		}
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(int[][][]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("I") ){
+			throw new TestException( "ArrayWrapper(int[][][]).getObjectTypeName() != 'I'" ) ;
+		}
+		System.out.println( " I : ok" ); 
+		
+		System.out.print( "  >> flat_int()" ) ;
+		int[] flat;
+		try{
+			flat = wrapper.flat_int() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(int[][][]) >> FlatException") ;
+		}
+		
+		for( int i=0; i<30; i++){
+			if( flat[i] != i ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+
+	
+	
+		
+	// {{{ flatten_boolean_1
+	private static void flatten_boolean_1() throws TestException{
+		
+		boolean[] o = new boolean[5] ; 
+		boolean current = false; 
+		for( int i=0;i<5;i++){
+			o[i] = current ;
+			current = !current ;
+		}
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( boolean[] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(boolean[]) >> NotAnArrayException ") ; 
+		} 
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(boolean[]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("Z") ){
+			throw new TestException( "ArrayWrapper(boolean[]).getObjectTypeName() != 'Z'" ) ;
+		}
+		System.out.println( " Z : ok" ); 
+		
+		System.out.print( "  >> flat_boolean()" ) ;
+		boolean[] flat;
+		try{
+			flat = wrapper.flat_boolean() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(int[]) >> FlatException") ;
+		}
+		
+		current = false ;
+		for( int i=0; i<5; i++){
+			if( flat[i] != current ) throw new TestException( "flat[" + i + "] = " + flat [i] );
+			current = !current ;
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+
+	// {{{ flatten_boolean_2
+	private static void flatten_boolean_2() throws TestException{
+		
+		boolean[][] o = RectangularArrayExamples.getBooleanDoubleRectangularArrayExample();
+			
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( boolean[][] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(boolean[][]) >> NotAnArrayException ") ; 
+		} 
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(boolean[][]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("Z") ){
+			throw new TestException( "ArrayWrapper(boolean[][]).getObjectTypeName() != 'Z'" ) ;
+		}
+		System.out.println( " Z : ok" ); 
+		
+		System.out.print( "  >> flat_boolean()" ) ;
+		boolean[] flat;
+		try{
+			flat = wrapper.flat_boolean() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(boolean[][]) >> FlatException") ;
+		}
+		
+		boolean current = false ;
+		for( int i=0; i<10; i++){
+			if( flat[i] != current ) throw new TestException( "flat[" + i + "] = " + flat [i] );
+			current = !current ;
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	
+  // {{{ flatten_boolean_3
+	private static void flatten_boolean_3() throws TestException{
+		
+		boolean[][][] o = RectangularArrayExamples.getBooleanTripleRectangularArrayExample();
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( boolean[][][] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(boolean[][][]) >> NotAnArrayException ") ; 
+		}
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(boolean[][][]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("Z") ){
+			throw new TestException( "ArrayWrapper(int[][][]).getObjectTypeName() != 'Z'" ) ;
+		}
+		System.out.println( " Z : ok" ); 
+		
+		System.out.print( "  >> flat_boolean()" ) ;
+		boolean[] flat;
+		try{
+			flat = wrapper.flat_boolean() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(boolean[][][]) >> FlatException") ;
+		}
+		
+		boolean current = false ;
+		for( int i=0; i<30; i++){
+			if( flat[i] != current ) throw new TestException( "flat[" + i + "] = " + flat [i] );
+			current = !current ;
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+
+
+	
+	
+	// {{{ flatten_byte_1
+	private static void flatten_byte_1() throws TestException{
+		
+		byte[] o = new byte[5] ;
+		for( int i=0;i<5;i++) o[i] = (byte)i ;
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( byte[] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(byte[]) >> NotAnArrayException ") ; 
+		} 
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(byte[]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("B") ){
+			throw new TestException( "ArrayWrapper(byte[]).getObjectTypeName() != 'I'" ) ;
+		}
+		System.out.println( " B : ok" ); 
+		
+		System.out.print( "  >> flat_byte()" ) ;
+		byte[] flat;
+		try{
+			flat = wrapper.flat_byte() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(byte[]) >> FlatException") ;
+		}
+		
+		for( int i=0; i<5; i++){
+			if( flat[i] != (byte)i ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	
+	// {{{ flatten_byte_2
+	private static void flatten_byte_2() throws TestException{
+		
+		byte[][] o = RectangularArrayExamples.getByteDoubleRectangularArrayExample();
+		
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( byte[][] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(byte[][]) >> NotAnArrayException ") ; 
+		} 
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(byte[][]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("B") ){
+			throw new TestException( "ArrayWrapper(byte[][]).getObjectTypeName() != 'B'" ) ;
+		}
+		System.out.println( " B : ok" ); 
+		
+		System.out.print( "  >> flat_byte()" ) ;
+		byte[] flat;
+		try{
+			flat = wrapper.flat_byte() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(byte[][]) >> FlatException") ;
+		}
+		
+		
+		for( int i=0; i<10; i++){
+			if( flat[i] != (byte)i ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	
+  // {{{ flatten_byte_3
+	private static void flatten_byte_3() throws TestException{
+		
+		byte[][][] o = RectangularArrayExamples.getByteTripleRectangularArrayExample();
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( byte[][][] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(byte[][][]) >> NotAnArrayException ") ; 
+		}
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(byte[][][]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("B") ){
+			throw new TestException( "ArrayWrapper(int[][][]).getObjectTypeName() != 'B'" ) ;
+		}
+		System.out.println( " B : ok" ); 
+		
+		System.out.print( "  >> flat_byte()" ) ;
+		byte[] flat;
+		try{
+			flat = wrapper.flat_byte() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(byte[][][]) >> FlatException") ;
+		}
+		
+		
+		for( int i=0; i<30; i++){
+			if( flat[i] != (byte)i ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+  
+	
+	// {{{ flatten_long_1
+	private static void flatten_long_1() throws TestException{
+		
+		long[] o = new long[5] ;
+		for( int i=0;i<5;i++) o[i] = (long)i ;
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( long[] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(long[]) >> NotAnArrayException ") ; 
+		} 
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(long[]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("J") ){
+			throw new TestException( "ArrayWrapper(long[]).getObjectTypeName() != 'J'" ) ;
+		}
+		System.out.println( " J : ok" ); 
+		
+		System.out.print( "  >> flat_long()" ) ;
+		long[] flat;
+		try{
+			flat = wrapper.flat_long() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(long[]) >> FlatException") ;
+		}
+		
+		for( int i=0; i<5; i++){
+			if( flat[i] != (long)i ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	
+	// {{{ flatten_long_2
+	private static void flatten_long_2() throws TestException{
+		
+		long[][] o = RectangularArrayExamples.getLongDoubleRectangularArrayExample();
+		
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( long[][] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(long[][]) >> NotAnArrayException ") ; 
+		} 
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(long[][]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("J") ){
+			throw new TestException( "ArrayWrapper(long[][]).getObjectTypeName() != 'J'" ) ;
+		}
+		System.out.println( " J : ok" ); 
+		
+		System.out.print( "  >> flat_long()" ) ;
+		long[] flat;
+		try{
+			flat = wrapper.flat_long() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(long[][]) >> FlatException") ;
+		}
+		
+		
+		for( int i=0; i<10; i++){
+			if( flat[i] != (long)i ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	
+  // {{{ flatten_long_3
+	private static void flatten_long_3() throws TestException{
+		
+		long[][][] o = RectangularArrayExamples.getLongTripleRectangularArrayExample();
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( long[][][] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(long[][][]) >> NotAnArrayException ") ; 
+		}
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(long[][][]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("J") ){
+			throw new TestException( "ArrayWrapper(long[][][]).getObjectTypeName() != 'J'" ) ;
+		}
+		System.out.println( " J : ok" ); 
+		
+		System.out.print( "  >> flat_long()" ) ;
+		long[] flat;
+		try{
+			flat = wrapper.flat_long() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(long[][][]) >> FlatException") ;
+		}
+		
+		
+		for( int i=0; i<30; i++){
+			if( flat[i] != (long)i ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+
+
+
+	// {{{ flatten_short_1
+	private static void flatten_short_1() throws TestException{
+		
+		short[] o = new short[5] ;
+		for( int i=0;i<5;i++) o[i] = (short)i ;
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( short[] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(short[]) >> NotAnArrayException ") ; 
+		} 
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(short[]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("S") ){
+			throw new TestException( "ArrayWrapper(long[]).getObjectTypeName() != 'S'" ) ;
+		}
+		System.out.println( " S : ok" ); 
+		
+		System.out.print( "  >> flat_short()" ) ;
+		short[] flat;
+		try{
+			flat = wrapper.flat_short() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(short[]) >> FlatException") ;
+		}
+		
+		for( int i=0; i<5; i++){
+			if( flat[i] != (double)i ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	
+	// {{{ flatten_short_2
+	private static void flatten_short_2() throws TestException{
+		
+		short[][] o = RectangularArrayExamples.getShortDoubleRectangularArrayExample();
+		
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( short[][] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(short[][]) >> NotAnArrayException ") ; 
+		} 
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(short[][]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("S") ){
+			throw new TestException( "ArrayWrapper(short[][]).getObjectTypeName() != 'S'" ) ;
+		}
+		System.out.println( " S : ok" ); 
+		
+		System.out.print( "  >> flat_short()" ) ;
+		short[] flat;
+		try{
+			flat = wrapper.flat_short() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(short[][]) >> FlatException") ;
+		}
+		
+		
+		for( int i=0; i<10; i++){
+			if( flat[i] != (double)i ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	
+  // {{{ flatten_short_3
+	private static void flatten_short_3() throws TestException{
+		
+		short[][][] o = RectangularArrayExamples.getShortTripleRectangularArrayExample();
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( short[][][] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(short[][][]) >> NotAnArrayException ") ; 
+		}
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(short[][][]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("S") ){
+			throw new TestException( "ArrayWrapper(short[][][]).getObjectTypeName() != 'S'" ) ;
+		}
+		System.out.println( " S : ok" ); 
+		
+		System.out.print( "  >> flat_short()" ) ;
+		short[] flat;
+		try{
+			flat = wrapper.flat_short() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(short[][][]) >> FlatException") ;
+		}
+		
+		
+		for( int i=0; i<30; i++){
+			if( flat[i] != (double)i ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+
+	
+
+	// {{{ flatten_double_1
+	private static void flatten_double_1() throws TestException{
+		
+		double[] o = new double[5] ;
+		for( int i=0;i<5;i++) o[i] = i+0.0 ;
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( double[] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(double[]) >> NotAnArrayException ") ; 
+		} 
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(double[]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("D") ){
+			throw new TestException( "ArrayWrapper(double[]).getObjectTypeName() != 'D'" ) ;
+		}
+		System.out.println( " D : ok" ); 
+		
+		System.out.print( "  >> flat_double()" ) ;
+		double[] flat;
+		try{
+			flat = wrapper.flat_double() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(double[]) >> FlatException") ;
+		}
+		
+		for( int i=0; i<5; i++){
+			if( flat[i] != (i+0.0) ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	
+	// {{{ flatten_double_2
+	private static void flatten_double_2() throws TestException{
+		
+		double[][] o = RectangularArrayExamples.getDoubleDoubleRectangularArrayExample();
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( double[][] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(double[][]) >> NotAnArrayException ") ; 
+		} 
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(double[][]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("D") ){
+			throw new TestException( "ArrayWrapper(double[][]).getObjectTypeName() != 'D'" ) ;
+		}
+		System.out.println( " D : ok" ); 
+		
+		System.out.print( "  >> flat_double()" ) ;
+		double[] flat;
+		try{
+			flat = wrapper.flat_double() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(double[][]) >> FlatException") ;
+		}
+		
+		
+		for( int i=0; i<10; i++){
+			if( flat[i] != (i+0.0) ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	
+  // {{{ flatten_double_3
+	private static void flatten_double_3() throws TestException{
+		
+		double[][][] o = RectangularArrayExamples.getDoubleTripleRectangularArrayExample();
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( double[][][] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(double[][][]) >> NotAnArrayException ") ; 
+		}
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(double[][][]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("D") ){
+			throw new TestException( "ArrayWrapper(double[][][]).getObjectTypeName() != 'D'" ) ;
+		}
+		System.out.println( " D : ok" ); 
+		
+		System.out.print( "  >> flat_double()" ) ;
+		double[] flat;
+		try{
+			flat = wrapper.flat_double() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(double[][][]) >> FlatException") ;
+		}
+		
+		
+		for( int i=0; i<30; i++){
+			if( flat[i] != (i+0.0) ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	
+	
+	// {{{ flatten_char_1
+	private static void flatten_char_1() throws TestException{
+		
+		char[] o = new char[5] ;
+		for( int i=0;i<5;i++) o[i] = (char)i ;
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( char[] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(char[]) >> NotAnArrayException ") ; 
+		} 
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(char[]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("C") ){
+			throw new TestException( "ArrayWrapper(char[]).getObjectTypeName() != 'C'" ) ;
+		}
+		System.out.println( " C : ok" ); 
+		
+		System.out.print( "  >> flat_char()" ) ;
+		char[] flat;
+		try{
+			flat = wrapper.flat_char() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(char[]) >> FlatException") ;
+		}
+		
+		for( int i=0; i<5; i++){
+			if( flat[i] != (char)i ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	
+	// {{{ flatten_char_2
+	private static void flatten_char_2() throws TestException{
+		
+		char[][] o = RectangularArrayExamples.getCharDoubleRectangularArrayExample();
+		
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( char[][] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(char[][]) >> NotAnArrayException ") ; 
+		} 
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(char[][]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("C") ){
+			throw new TestException( "ArrayWrapper(char[][]).getObjectTypeName() != 'C'" ) ;
+		}
+		System.out.println( " C : ok" ); 
+		
+		System.out.print( "  >> flat_char()" ) ;
+		char[] flat;
+		try{
+			flat = wrapper.flat_char() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(char[][]) >> FlatException") ;
+		}
+		
+		
+		for( int i=0; i<10; i++){
+			if( flat[i] != (i+0.0) ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	
+  // {{{ flatten_char_3
+	private static void flatten_char_3() throws TestException{
+		
+		char[][][] o = RectangularArrayExamples.getCharTripleRectangularArrayExample();
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( char[][][] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(char[][][]) >> NotAnArrayException ") ; 
+		}
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(char[][][]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("C") ){
+			throw new TestException( "ArrayWrapper(char[][][]).getObjectTypeName() != 'C'" ) ;
+		}
+		System.out.println( " C : ok" ); 
+		
+		System.out.print( "  >> flat_char()" ) ;
+		char[] flat;
+		try{
+			flat = wrapper.flat_char() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(char[][][]) >> FlatException") ;
+		}
+		
+		
+		for( int i=0; i<30; i++){
+			if( flat[i] != (char)i ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+
+	
+
+	// {{{ flatten_float_1
+	private static void flatten_float_1() throws TestException{
+		
+		float[] o = new float[5] ;
+		for( int i=0;i<5;i++) o[i] = (float)(i+0.0) ;
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( float[] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(float[]) >> NotAnArrayException ") ; 
+		} 
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(float[]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("F") ){
+			throw new TestException( "ArrayWrapper(float[]).getObjectTypeName() != 'F'" ) ;
+		}
+		System.out.println( " F : ok" ); 
+		
+		System.out.print( "  >> flat_float()" ) ;
+		float[] flat;
+		try{
+			flat = wrapper.flat_float() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(float[]) >> FlatException") ;
+		}
+		
+		for( int i=0; i<5; i++){
+			if( flat[i] != (i+0.0) ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	
+	// {{{ flatten_float_2
+	private static void flatten_float_2() throws TestException{
+		
+		float[][] o = RectangularArrayExamples.getFloatDoubleRectangularArrayExample();
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( float[][] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(float[][]) >> NotAnArrayException ") ; 
+		} 
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(float[][]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("F") ){
+			throw new TestException( "ArrayWrapper(float[][]).getObjectTypeName() != 'F'" ) ;
+		}
+		System.out.println( " F : ok" ); 
+		
+		System.out.print( "  >> flat_float()" ) ;
+		float[] flat;
+		try{
+			flat = wrapper.flat_float() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(float[][]) >> FlatException") ;
+		}
+		
+		
+		for( int i=0; i<10; i++){
+			if( flat[i] != (i+0.0) ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	
+  // {{{ flatten_float_3
+	private static void flatten_float_3() throws TestException{
+		
+		float[][][] o = RectangularArrayExamples.getFloatTripleRectangularArrayExample();
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( float[][][] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(float[][][]) >> NotAnArrayException ") ; 
+		}
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( !wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(float[][][]) not primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("F") ){
+			throw new TestException( "ArrayWrapper(float[][][]).getObjectTypeName() != 'F'" ) ;
+		}
+		System.out.println( " F : ok" ); 
+		
+		System.out.print( "  >> flat_float()" ) ;
+		float[] flat;
+		try{
+			flat = wrapper.flat_float() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(float[][][]) >> FlatException") ;
+		}
+		
+		
+		for( int i=0; i<30; i++){
+			if( flat[i] != (float)(i+0.0) ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+		
+	// }}}
+
+	// {{{ flat array of String
+	
+	// {{{ flatten_String_1
+	private static void flatten_String_1() throws TestException{
+		
+		String[] o = new String[5] ;
+		for( int i=0;i<5;i++) o[i] = ""+i ;
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( String[] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(String[]) >> NotAnArrayException ") ; 
+		} 
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(String[]) is primitive" ) ; 
+		}
+		System.out.println( " false : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("java.lang.String") ){
+			throw new TestException( "ArrayWrapper(float[]).getObjectTypeName() != 'java.lang.String'" ) ;
+		}
+		System.out.println( " java.lang.String : ok" ); 
+		
+		System.out.print( "  >> flat_String()" ) ;
+		String[] flat;
+		try{
+			flat = wrapper.flat_String() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(String[]) >> FlatException") ;
+		}
+		
+		for( int i=0; i<5; i++){
+			if( ! flat[i].equals(""+i) ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	
+	// {{{ flatten_String_2
+	private static void flatten_String_2() throws TestException{
+		
+		String[][] o = RectangularArrayExamples.getStringDoubleRectangularArrayExample();
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( String[][] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(String[][]) >> NotAnArrayException ") ; 
+		} 
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(String[][]) is primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("java.lang.String") ){
+			throw new TestException( "ArrayWrapper(float[][]).getObjectTypeName() != 'java.lang.String'" ) ;
+		}
+		System.out.println( " java.lang.String : ok" ); 
+		
+		System.out.print( "  >> flat_String()" ) ;
+		String[] flat;
+		try{
+			flat = wrapper.flat_String() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(String[][]) >> FlatException") ;
+		}
+		
+		
+		for( int i=0; i<10; i++){
+			if( ! flat[i].equals( ""+i) ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	
+  // {{{ flatten_String_3
+	private static void flatten_String_3() throws TestException{
+		
+		String[][][] o = RectangularArrayExamples.getStringTripleRectangularArrayExample();
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( String[][][] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(String[][][]) >> NotAnArrayException ") ; 
+		}
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(String[][][]) is primitive" ) ; 
+		}
+		System.out.println( " true : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("java.lang.String") ){
+			throw new TestException( "ArrayWrapper(String[][][]).getObjectTypeName() != 'java.lang.String'" ) ;
+		}
+		System.out.println( " java.lang.String : ok" ); 
+		
+		System.out.print( "  >> flat_String()" ) ;
+		String[] flat;
+		try{
+			flat = wrapper.flat_String() ; 
+		} catch( PrimitiveArrayException e){
+			throw new TestException( "PrimitiveArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(String[][][]) >> FlatException") ;
+		}
+		
+		
+		for( int i=0; i<30; i++){
+			if( !flat[i].equals( ""+i) ) throw new TestException( "flat[" + i + "] = " + flat [i] + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	// }}}
+	
+	// {{{ flat array of Point
+	// {{{ flatten_Point_1
+	private static void flatten_Point_1() throws TestException{
+		
+		DummyPoint[] o = new DummyPoint[5] ;
+		for( int i=0;i<5;i++) o[i] = new DummyPoint(i,i) ;
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( DummyPoint[] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(DummyPoint[]) >> NotAnArrayException ") ; 
+		} 
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(DummyPoint[]) is primitive" ) ; 
+		}
+		System.out.println( " false : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("DummyPoint") ){
+			throw new TestException( "ArrayWrapper(DummyPoint[]).getObjectTypeName() != 'DummyPoint'" ) ;
+		}
+		System.out.println( " DummyPoint : ok" ); 
+		
+		System.out.print( "  >> flat_Object()" ) ;
+		DummyPoint[] flat ;
+		try{
+			flat = (DummyPoint[])wrapper.flat_Object() ;
+		} catch( ObjectArrayException e){
+			throw new TestException( "ObjectArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(DummyPoint[]) >> FlatException") ;
+		}
+		
+		DummyPoint p ; 
+		for( int i=0; i<5; i++){
+			p = flat[i] ;
+			if( p.x != i || p.y != i) throw new TestException( "flat[" + i + "].x = " + p.x + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	
+	// {{{ flatten_Point_2
+	private static void flatten_Point_2() throws TestException{
+		
+		DummyPoint[][] o = RectangularArrayExamples.getDummyPointDoubleRectangularArrayExample(); 
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( DummyPoint[][] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(DummyPoint[][]) >> NotAnArrayException ") ; 
+		} 
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(DummyPoint[][]) is primitive" ) ; 
+		}
+		System.out.println( " false : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("DummyPoint") ){
+			throw new TestException( "ArrayWrapper(DummyPoint[][]).getObjectTypeName() != 'DummyPoint'" ) ;
+		}
+		System.out.println( " DummyPoint : ok" ); 
+		
+		System.out.print( "  >> flat_Object()" ) ;
+		DummyPoint[] flat;
+		try{
+			flat = (DummyPoint[])wrapper.flat_Object() ; 
+		} catch( ObjectArrayException e){
+			throw new TestException( "ObjectArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(DummyPoint[][]) >> FlatException") ;
+		}
+		
+		DummyPoint p; 
+		for( int i=0; i<10; i++){
+			p = flat[i] ;
+			if( p.x != i || p.y != i) throw new TestException( "flat[" + i + "].x = " + p.x + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	
+  // {{{ flatten_Point_3
+	private static void flatten_Point_3() throws TestException{
+		
+		DummyPoint[][][] o = RectangularArrayExamples.getDummyPointTripleRectangularArrayExample();
+		
+		ArrayWrapper wrapper = null ; 
+		System.out.print( "  >> new ArrayWrapper( DummyPoint[][][] ) " ); 
+		try{
+			wrapper = new ArrayWrapper(o); 
+		} catch( NotAnArrayException e){
+			throw new TestException("new ArrayWrapper(DummyPoint[][][]) >> NotAnArrayException ") ; 
+		}
+		System.out.println( "ok"); 
+		
+		System.out.print( "  >> isPrimitive()" ) ;
+		if( wrapper.isPrimitive() ){
+			throw new TestException( "ArrayWrapper(DummyPoint[][][]) is primitive" ) ; 
+		}
+		System.out.println( " false : ok" ); 
+		
+		System.out.print( "  >> getObjectTypeName()" ) ;
+		if( !wrapper.getObjectTypeName().equals("DummyPoint") ){
+			throw new TestException( "ArrayWrapper(DummyPoint[][][]).getObjectTypeName() != 'DummyPoint'" ) ;
+		}
+		System.out.println( " DummyPoint : ok" ); 
+		
+		System.out.print( "  >> flat_Object()" ) ;
+		DummyPoint[] flat;
+		try{         
+			flat = (DummyPoint[])wrapper.flat_Object() ; 
+		} catch( ObjectArrayException e){
+			throw new TestException( "ObjectArrayException" ) ;
+		} catch( FlatException e){
+			throw new TestException("new ArrayWrapper(Object[][][]) >> FlatException") ;
+		}
+		
+		DummyPoint p; 
+		for( int i=0; i<30; i++){
+			p = flat[i]; 
+			if( p.x != i || p.y != i ) throw new TestException( "flat[" + i + "].x = " + p.x + "!=" + i); 
+		}
+		System.out.println( "  ok" ) ;
+		
+	}
+	// }}}
+	
+	// }}}
+
+	
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/DummyPoint.java b/com.oracle.truffle.r.pkgs/rJava/src/java/DummyPoint.java
new file mode 100644
index 0000000000000000000000000000000000000000..9407bd9732413641097c8516dccd1e13d3e1d424
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/DummyPoint.java
@@ -0,0 +1,20 @@
+
+public class DummyPoint implements Cloneable {
+	public int x; 
+	public int y ;
+	public DummyPoint(){
+		this( 0, 0 ) ;
+	}
+	public DummyPoint( int x, int y){
+		this.x = x ;
+		this.y = y ;
+	}
+	public double getX(){
+		return (double)x ;
+	}
+	public void move(int x, int y){
+		this.x += x ;
+		this.y += y ;
+	}
+	
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/FlatException.java b/com.oracle.truffle.r.pkgs/rJava/src/java/FlatException.java
new file mode 100644
index 0000000000000000000000000000000000000000..4b4330b30a877c9fb690792e6652d73ad085a949
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/FlatException.java
@@ -0,0 +1,9 @@
+
+/**
+ * Generated when one attemps to flatten an array that is not rectangular
+ */
+public class FlatException extends Exception{
+	public FlatException(){
+		super( "Can only flatten rectangular arrays" ); 
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/Makefile b/com.oracle.truffle.r.pkgs/rJava/src/java/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..4ac3e6a36e9b92b8d5922ef0c15faf4412441afd
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/Makefile
@@ -0,0 +1,34 @@
+JAVA_SRC=$(wildcard *.java)
+JFLAGS=-source 1.6 -target 1.6
+JAVAC=javac
+JAVA=java
+JAVADOC=javadoc
+JAVADOCFLAGS=-author -version -breakiterator -link http://java.sun.com/j2se/1.4.2/docs/api
+
+all: compile test
+
+compile: $(JAVA_SRC)
+	$(JAVAC) $(JFLAGS) $(JAVA_SRC)
+
+test_RJavaTools: compile
+	$(JAVA) RJavaTools_Test
+
+test_RJavaArrayTools: compile
+	$(JAVA) RJavaArrayTools_Test
+
+test_ArrayWrapper:
+	$(JAVA) ArrayWrapper_Test
+
+test_RectangularArrayBuilder:
+	$(JAVA) RectangularArrayBuilder_Test
+
+test: compile test_RJavaTools test_RJavaArrayTools test_ArrayWrapper test_RectangularArrayBuilder
+
+javadoc:
+	$(JAVADOC) $(JAVADOCFLAGS) -d javadoc $(JAVA_SRC)
+
+clean:
+	rm -rfv *.class *~
+
+.PHONY: all clean
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/NotAnArrayException.java b/com.oracle.truffle.r.pkgs/rJava/src/java/NotAnArrayException.java
new file mode 100644
index 0000000000000000000000000000000000000000..2be5327ed6ccfa4b3b536bccc2f1468650eb1155
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/NotAnArrayException.java
@@ -0,0 +1,12 @@
+/**
+ * Exception indicating that an object is not a java array
+ */
+public class NotAnArrayException extends Exception{
+	public NotAnArrayException(Class clazz){
+		super( "not an array : " + clazz.getName() ) ;
+	}
+	public NotAnArrayException(String message){
+		super( message ) ;
+	}
+}
+	
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/NotComparableException.java b/com.oracle.truffle.r.pkgs/rJava/src/java/NotComparableException.java
new file mode 100644
index 0000000000000000000000000000000000000000..48824de1317a02ed6d27aba7b4d66a6cec210af0
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/NotComparableException.java
@@ -0,0 +1,24 @@
+/**
+ * Exception generated when two objects cannot be compared
+ * 
+ * Such cases happen when an object does not implement the Comparable 
+ * interface or when the comparison produces a ClassCastException
+ */
+public class NotComparableException extends Exception{
+	public NotComparableException(Object a, Object b){
+		super( "objects of class " + a.getClass().getName() + 
+			" and " + b.getClass().getName() + " are not comparable"  ) ;
+	}
+	public NotComparableException( Object o){
+		this( o.getClass().getName() ) ;
+	}
+	
+	public NotComparableException( Class cl){
+		this( cl.getName() ) ;
+	}
+	
+	public NotComparableException( String type ){
+		super( "class " + type + " does not implement java.util.Comparable" ) ; 
+	}
+	
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/ObjectArrayException.java b/com.oracle.truffle.r.pkgs/rJava/src/java/ObjectArrayException.java
new file mode 100644
index 0000000000000000000000000000000000000000..33524834b5e506b65e5d4d3d930f665f98dd1bf0
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/ObjectArrayException.java
@@ -0,0 +1,10 @@
+/**
+ * Generated when one tries to access an array of primitive
+ * values as an array of Objects
+ */
+public class ObjectArrayException extends Exception{
+	public ObjectArrayException(String type){
+		super( "array is of primitive type : " + type ) ; 
+	}
+	
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/PrimitiveArrayException.java b/com.oracle.truffle.r.pkgs/rJava/src/java/PrimitiveArrayException.java
new file mode 100644
index 0000000000000000000000000000000000000000..2a89856333ed15704e53779fd57d1d6eaaea7200
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/PrimitiveArrayException.java
@@ -0,0 +1,10 @@
+/**
+ * Generated when one tries to convert an arrays into 
+ * a primitive array of the wrong type
+ */
+public class PrimitiveArrayException extends Exception{
+	public PrimitiveArrayException(String type){
+		super( "cannot convert to single dimension array of primitive type" + type ) ; 
+	}
+	
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaArrayIterator.java b/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaArrayIterator.java
new file mode 100644
index 0000000000000000000000000000000000000000..3b0df629b574f9b19c118f5a1e727a45150de7e2
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaArrayIterator.java
@@ -0,0 +1,86 @@
+import java.lang.reflect.Array ;
+
+public abstract class RJavaArrayIterator {
+
+	protected int[] dimensions; 
+	protected int nd ; 
+	protected int[] index ;
+	protected int[] dimprod ;
+	protected Object array ;
+	protected int increment; 
+	protected int position ;
+	protected int start ;
+	
+	public Object getArray(){
+		return array ; 
+	}
+	
+	/**
+	 * @return the class name of the array
+	 */
+	public String getArrayClassName(){
+		return array.getClass().getName();
+	}
+	
+	public int[] getDimensions(){
+		return dimensions; 
+	}
+	
+	public RJavaArrayIterator(){
+		dimensions = null; 
+		index = null ;
+		dimprod = null ;
+		array = null ;
+	}
+	
+	public RJavaArrayIterator(int[] dimensions){
+		this.dimensions = dimensions ; 
+		nd = dimensions.length ;
+		if( nd > 1){
+			index = new int[ nd-1 ] ;
+			dimprod = new int[ nd-1 ] ;
+			for( int i=0; i<(nd-1); i++){
+				index[i] = 0 ;
+				dimprod[i] = (i==0) ? dimensions[i] : ( dimensions[i]*dimprod[i-1] );
+				increment = dimprod[i] ;
+			}
+		}
+		position = 0 ;
+		start = 0; 
+	}
+	public RJavaArrayIterator(int d1){
+		this( new int[]{ d1} ) ;
+	}
+	
+	protected Object next( ){
+		
+		/* get the next array and the position of the first elemtn in the flat array */
+		Object o = array ;
+		for( int i=0; i<index.length; i++){
+			o = Array.get( o, index[i] ) ;
+			if( i == 0 ) {
+				start = index[i]; 
+			} else {
+				start += index[i] * dimprod[i-1] ;
+			}
+		}
+		
+		/* increment the index */
+		for( int i=index.length-1; i>=0; i--){
+			if( (index[i] + 1) == dimensions[i] ){
+				index[i] = 0 ; 
+			} else{
+				index[i] = index[i] + 1 ;
+			}
+		}
+				
+		position++ ;
+		return o; 
+	}
+	
+	protected boolean hasNext( ){
+		return position < increment ;
+	}
+	
+	
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaArrayTools.java b/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaArrayTools.java
new file mode 100644
index 0000000000000000000000000000000000000000..6f1098a94cda90af35e0c6eafc9ab431288602a9
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaArrayTools.java
@@ -0,0 +1,748 @@
+// RJavaTools.java: rJava - low level R to java interface
+//
+// :tabSize=2:indentSize=2:noTabs=false:folding=explicit:collapseFolds=1:
+//
+// Copyright (C) 2009 - 2010	Simon Urbanek and Romain Francois
+//
+// This file is part of rJava.
+//
+// rJava 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.
+//
+// rJava 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 rJava.  If not, see <http://www.gnu.org/licenses/>.
+
+import java.lang.reflect.Array ; 
+import java.util.Map; 
+import java.util.HashMap;
+import java.util.Vector ;
+import java.util.Arrays ;
+import java.util.Iterator;
+
+import java.lang.reflect.Method ;
+import java.lang.reflect.InvocationTargetException ;
+
+public class RJavaArrayTools {
+
+	// TODO: maybe factor this out of this class
+	private static Map primitiveClasses = initPrimitiveClasses() ;
+	private static Map initPrimitiveClasses(){
+		Map primitives = new HashMap(); 
+		primitives.put( "I", Integer.TYPE ); 
+		primitives.put( "Z", Boolean.TYPE );
+		primitives.put( "B", Byte.TYPE );
+		primitives.put( "J", Long.TYPE );
+		primitives.put( "S", Short.TYPE );
+		primitives.put( "D", Double.TYPE );
+		primitives.put( "C", Character.TYPE );
+		primitives.put( "F", Float.TYPE );
+		return primitives; 
+	}
+	
+	// {{{ getObjectTypeName
+	/**
+	 * Get the object type name of an multi dimensional array.
+	 * 
+	 * @param o object
+	 * @throws NotAnArrayException if the object is not an array
+	 */
+	public static String getObjectTypeName(Object o) throws NotAnArrayException {
+		Class o_clazz = o.getClass();
+		if( !o_clazz.isArray() ) throw new NotAnArrayException( o_clazz ); 
+		
+		String cl = o_clazz.getName();
+		return cl.replaceFirst("\\[+L?", "").replace(";", "") ; 
+	}
+	public static int getObjectTypeName(int x)     throws NotAnArrayException { throw new NotAnArrayException("primitive type : int     ") ; }
+	public static int getObjectTypeName(boolean x) throws NotAnArrayException { throw new NotAnArrayException("primitive type : boolean ") ; }
+	public static int getObjectTypeName(byte x)    throws NotAnArrayException { throw new NotAnArrayException("primitive type : byte    ") ; }
+	public static int getObjectTypeName(long x)    throws NotAnArrayException { throw new NotAnArrayException("primitive type : long    ") ; }
+	public static int getObjectTypeName(short x)   throws NotAnArrayException { throw new NotAnArrayException("primitive type : short   ") ; }
+	public static int getObjectTypeName(double x)  throws NotAnArrayException { throw new NotAnArrayException("primitive type : double  ") ; }
+	public static int getObjectTypeName(char x)    throws NotAnArrayException { throw new NotAnArrayException("primitive type : char    ") ; }
+	public static int getObjectTypeName(float x)   throws NotAnArrayException { throw new NotAnArrayException("primitive type : float   ") ; }
+	// }}}
+	
+	// {{{ makeArraySignature
+	// TODO: test
+	public static String makeArraySignature( String typeName, int depth ){
+		StringBuffer buffer = new StringBuffer() ;
+		for( int i=0; i<depth; i++){
+			buffer.append( '[' ) ; 
+		}
+		buffer.append( typeName ); 
+		if( ! isPrimitiveTypeName( typeName ) ){
+			buffer.append( ';') ;
+		}
+		return buffer.toString(); 
+	}
+	// }}}
+	
+	// {{{ getClassForSignature
+	public static Class getClassForSignature(String signature, ClassLoader loader) throws ClassNotFoundException {
+		if( primitiveClasses.containsKey(signature) ){
+			return (Class)primitiveClasses.get( signature ) ;
+		}
+		return Class.forName(signature, true, loader) ;
+	}
+	// }}}
+	
+	// {{{ isSingleDimensionArray
+	public static boolean isSingleDimensionArray( Object o) throws NotAnArrayException{
+		if( !isArray(o) ) throw new NotAnArrayException( o.getClass() ) ;
+		
+		String cn = o.getClass().getName() ; 
+		if( cn.lastIndexOf('[') != 0 ) return false; 
+		return true ; 
+	}
+	// }}}
+	
+	// {{{ isPrimitiveTypeName
+	public static boolean isPrimitiveTypeName(String name){
+		if( name.length() > 1 ) return false; 
+		if( name.equals("I") ) return true ;
+		if( name.equals("Z") ) return true ;
+		if( name.equals("B") ) return true ;
+		if( name.equals("J") ) return true ;
+		if( name.equals("S") ) return true ;
+		if( name.equals("D") ) return true ;
+		if( name.equals("C") ) return true ;
+		if( name.equals("F") ) return true ;
+		return false; 
+	}
+	// }}}
+	
+	// {{{ isRectangularArray
+	/**
+	 * Indicates if o is a rectangular array
+	 * 
+	 * @param o an array
+	 * @deprecated use new ArrayWrapper(o).isRectangular() instead
+	 */
+	public static boolean isRectangularArray(Object o) {
+		if( !isArray(o) ) return false; 
+		boolean res = false; 
+		try{
+			if( getDimensionLength( o ) == 1 ) return true ;
+			res = ( new ArrayWrapper(o) ).isRectangular() ;
+		} catch( NotAnArrayException e){
+			res = false; 
+		}
+		return res ;
+	}
+	
+	
+	// thoose below make java < 1.5 happy and me unhappy ;-)
+	public static boolean isRectangularArray(int x)      { return false ; }
+	public static boolean isRectangularArray(boolean x)  { return false ; }
+	public static boolean isRectangularArray(byte x)     { return false ; }
+	public static boolean isRectangularArray(long x)     { return false ; }
+	public static boolean isRectangularArray(short x)    { return false ; }
+	public static boolean isRectangularArray(double x)   { return false ; }
+	public static boolean isRectangularArray(char x)     { return false ; }
+	public static boolean isRectangularArray(float x)    { return false ; }
+	
+	// }}}
+	
+	// {{{ getDimensionLength
+	/** 
+	 * Returns the number of dimensions of an array
+	 *
+	 * @param o an array
+	 * @throws NotAnArrayException if this is not an array
+	 */
+	public static int getDimensionLength( Object o) throws NotAnArrayException, NullPointerException {
+		if( o == null ) throw new NullPointerException( "array is null" ) ;
+		Class clazz = o.getClass();
+		if( !clazz.isArray() ) throw new NotAnArrayException(clazz) ;
+		int n = 0; 
+		while( clazz.isArray() ){
+			n++ ; 
+			clazz = clazz.getComponentType() ;
+		}
+		return n ; 
+	}
+	// thoose below make java < 1.5 happy and me unhappy ;-)
+	public static int getDimensionLength(int x)     throws NotAnArrayException { throw new NotAnArrayException("primitive type : int     ") ; }
+	public static int getDimensionLength(boolean x) throws NotAnArrayException { throw new NotAnArrayException("primitive type : boolean ") ; }
+	public static int getDimensionLength(byte x)    throws NotAnArrayException { throw new NotAnArrayException("primitive type : byte    ") ; }
+	public static int getDimensionLength(long x)    throws NotAnArrayException { throw new NotAnArrayException("primitive type : long    ") ; }
+	public static int getDimensionLength(short x)   throws NotAnArrayException { throw new NotAnArrayException("primitive type : short   ") ; }
+	public static int getDimensionLength(double x)  throws NotAnArrayException { throw new NotAnArrayException("primitive type : double  ") ; }
+	public static int getDimensionLength(char x)    throws NotAnArrayException { throw new NotAnArrayException("primitive type : char    ") ; }
+	public static int getDimensionLength(float x)   throws NotAnArrayException { throw new NotAnArrayException("primitive type : float   ") ; }
+	// }}}                                                                                          
+	
+	// {{{ getDimensions
+	/** 
+	 * Returns the dimensions of an array
+	 *
+	 * @param o an array
+	 * @throws NotAnArrayException if this is not an array
+	 * @return the dimensions of the array or null if the object is null
+	 */
+	public static int[] getDimensions( Object o) throws NotAnArrayException, NullPointerException {
+		if( o == null ) throw new NullPointerException( "array is null" )  ;
+		
+		Class clazz = o.getClass();
+		if( !clazz.isArray() ) throw new NotAnArrayException(clazz) ;
+		Object a = o ;
+		
+		int n = getDimensionLength( o ) ; 
+		int[] dims = new int[n] ;
+		int i=0;
+		int current ; 
+		while( clazz.isArray() ){
+			current = Array.getLength( a ) ;
+			dims[i] = current ;
+			i++;
+			if( current == 0 ){
+				break ; // the while loop 
+			} else {
+				a = Array.get( a, 0 ) ;
+				clazz = clazz.getComponentType() ;
+			}
+		}
+		
+		/* in case of premature stop, we fill the rest of the array with 0 */
+		// this might not be true: 
+		// Object[][] = new Object[0][10] will return c(0,0)
+		while( i < dims.length){
+			dims[i] = 0 ;
+			i++ ;
+		}
+		return dims ; 
+	}
+	// thoose below make java < 1.5 happy and me unhappy ;-)
+	public static int[] getDimensions(int x)     throws NotAnArrayException { throw new NotAnArrayException("primitive type : int     ") ; }
+	public static int[] getDimensions(boolean x) throws NotAnArrayException { throw new NotAnArrayException("primitive type : boolean ") ; }
+	public static int[] getDimensions(byte x)    throws NotAnArrayException { throw new NotAnArrayException("primitive type : byte    ") ; }
+	public static int[] getDimensions(long x)    throws NotAnArrayException { throw new NotAnArrayException("primitive type : long    ") ; }
+	public static int[] getDimensions(short x)   throws NotAnArrayException { throw new NotAnArrayException("primitive type : short   ") ; }
+	public static int[] getDimensions(double x)  throws NotAnArrayException { throw new NotAnArrayException("primitive type : double  ") ; }
+	public static int[] getDimensions(char x)    throws NotAnArrayException { throw new NotAnArrayException("primitive type : char    ") ; }
+	public static int[] getDimensions(float x)   throws NotAnArrayException { throw new NotAnArrayException("primitive type : float   ") ; }
+	// }}}                                                                                          
+	
+	// {{{ getTrueLength
+	/** 
+	 * Returns the true length of an array (the product of its dimensions)
+	 *
+	 * @param o an array
+	 * @throws NotAnArrayException if this is not an array
+	 * @return the number of objects in the array (the product of its dimensions).
+	 */
+	public static int getTrueLength( Object o) throws NotAnArrayException, NullPointerException {
+		if( o == null ) throw new NullPointerException( "array is null" ) ;
+		
+		Class clazz = o.getClass();
+		if( !clazz.isArray() ) throw new NotAnArrayException(clazz) ;
+		Object a = o ;
+		
+		int len = 1 ;
+		int i = 0; 
+		while( clazz.isArray() ){
+			len = len * Array.getLength( a ) ;
+			if( len == 0 ) return 0 ; /* no need to go further */
+			i++;
+			a = Array.get( a, 0 ) ;
+			clazz = clazz.getComponentType() ;
+		}
+		return len ; 
+	}
+	// thoose below make java < 1.5 happy and me unhappy ;-)
+	public static int getTrueLength(int x)     throws NotAnArrayException { throw new NotAnArrayException("primitive type : int     ") ; }
+	public static int getTrueLength(boolean x) throws NotAnArrayException { throw new NotAnArrayException("primitive type : boolean ") ; }
+	public static int getTrueLength(byte x)    throws NotAnArrayException { throw new NotAnArrayException("primitive type : byte    ") ; }
+	public static int getTrueLength(long x)    throws NotAnArrayException { throw new NotAnArrayException("primitive type : long    ") ; }
+	public static int getTrueLength(short x)   throws NotAnArrayException { throw new NotAnArrayException("primitive type : short   ") ; }
+	public static int getTrueLength(double x)  throws NotAnArrayException { throw new NotAnArrayException("primitive type : double  ") ; }
+	public static int getTrueLength(char x)    throws NotAnArrayException { throw new NotAnArrayException("primitive type : char    ") ; }
+	public static int getTrueLength(float x)   throws NotAnArrayException { throw new NotAnArrayException("primitive type : float   ") ; }
+	// }}}                                                                                          
+	
+	// {{{ isArray
+	/**
+	 * Indicates if a java object is an array
+	 * 
+	 * @param o object
+	 * @return true if the object is an array
+	 * @deprecated use RJavaArrayTools#isArray
+	 */
+	public static boolean isArray(Object o){
+		if( o == null) return false ; 
+		return o.getClass().isArray() ; 
+	}
+	// thoose below make java < 1.5 happy and me unhappy ;-)
+	public static boolean isArray(int x){ return false ; }
+	public static boolean isArray(boolean x){ return false ; }
+	public static boolean isArray(byte x){ return false ; }
+	public static boolean isArray(long x){ return false ; }
+	public static boolean isArray(short x){ return false ; }
+	public static boolean isArray(double x){ return false ; }
+	public static boolean isArray(char x){ return false ; }
+	public static boolean isArray(float x){ return false ; }
+	// }}}
+	
+	// {{{ ArrayDimensionMismatchException
+	public static class ArrayDimensionMismatchException extends Exception {
+		public ArrayDimensionMismatchException( int index_dim, int actual_dim ){
+			super( "dimension of indexer (" + index_dim + ") too large for array (depth ="+ actual_dim+ ")") ;
+		}
+	}
+	// }}}
+	
+	// {{{ get
+	/**
+	 * Gets a single object from a multi dimensional array
+	 *
+	 * @param array java array
+	 * @param position
+	 */
+	public static Object get( Object array, int[] position ) throws NotAnArrayException, ArrayDimensionMismatchException {
+		return Array.get( getArray( array, position ), position[ position.length -1] ); 
+	}
+	
+	public static int getInt( Object array, int[] position ) throws NotAnArrayException, ArrayDimensionMismatchException {
+		return Array.getInt( getArray( array, position ), position[ position.length -1] ); 
+	}
+	public static boolean getBoolean( Object array, int[] position ) throws NotAnArrayException, ArrayDimensionMismatchException {
+		return Array.getBoolean( getArray( array, position ), position[ position.length -1] ); 
+	}
+	public static byte getByte( Object array, int[] position ) throws NotAnArrayException, ArrayDimensionMismatchException {
+		return Array.getByte( getArray( array, position ), position[ position.length -1] ); 
+	}
+	public static long getLong( Object array, int[] position ) throws NotAnArrayException, ArrayDimensionMismatchException {
+		return Array.getLong( getArray( array, position ), position[ position.length -1] ); 
+	}
+	public static short getShort( Object array, int[] position ) throws NotAnArrayException, ArrayDimensionMismatchException {
+		return Array.getShort( getArray( array, position ), position[ position.length -1] ); 
+	}
+	public static double getDouble( Object array, int[] position ) throws NotAnArrayException, ArrayDimensionMismatchException {
+		return Array.getDouble( getArray( array, position ), position[ position.length -1] ); 
+	}
+	public static char getChar( Object array, int[] position ) throws NotAnArrayException, ArrayDimensionMismatchException {
+		return Array.getChar( getArray( array, position ), position[ position.length -1] ); 
+	}
+	public static float getFloat( Object array, int[] position ) throws NotAnArrayException, ArrayDimensionMismatchException {
+		return Array.getFloat( getArray( array, position ), position[ position.length -1] ); 
+	}
+
+	
+	public static Object get( Object array, int position ) throws NotAnArrayException, ArrayDimensionMismatchException {
+		return get( array, new int[]{position} ) ;
+	}
+	public static int getInt( Object array, int position ) throws NotAnArrayException, ArrayDimensionMismatchException {
+		return getInt( array, new int[]{position} ) ; 
+	}
+	public static boolean getBoolean( Object array, int position ) throws NotAnArrayException, ArrayDimensionMismatchException {
+		return getBoolean( array, new int[]{position} ) ; 
+	}
+	public static byte getByte( Object array, int position ) throws NotAnArrayException, ArrayDimensionMismatchException {
+		return getByte( array, new int[]{position} ) ; 
+	}
+	public static long getLong( Object array, int position ) throws NotAnArrayException, ArrayDimensionMismatchException {
+		return getLong( array, new int[]{position} ) ; 
+	}
+	public static short getShort( Object array, int position ) throws NotAnArrayException, ArrayDimensionMismatchException {
+		return getShort( array, new int[]{position} ) ; 
+	}
+	public static double getDouble( Object array, int position ) throws NotAnArrayException, ArrayDimensionMismatchException {
+		return getDouble( array, new int[]{position} ) ; 
+	}
+	public static char getChar( Object array, int position ) throws NotAnArrayException, ArrayDimensionMismatchException {
+		return getChar( array, new int[]{position} ) ;
+	}
+	public static float getFloat( Object array, int position ) throws NotAnArrayException, ArrayDimensionMismatchException {
+		return getFloat( array, new int[]{position} ) ; 
+	}
+	
+	private static void checkDimensions(Object array, int[] position) throws NotAnArrayException, ArrayDimensionMismatchException {
+		int poslength = position.length ;
+		int actuallength = getDimensionLength(array); 
+		if( poslength > actuallength ){
+			throw new ArrayDimensionMismatchException( poslength, actuallength ) ; 
+		}
+	}
+	
+	// }}}
+	
+	// {{{ set
+	/**
+	 * Replaces a single value of the array 
+	 *
+	 * @param array array 
+	 * @param position index
+	 * @param value the new value
+	 * 
+	 * @throws NotAnArrayException if array is not an array
+	 * @throws ArrayDimensionMismatchException if the length of position is too big
+	 */
+	public static void set( Object array, int[] position, Object value ) throws NotAnArrayException, ArrayDimensionMismatchException{
+		Array.set( getArray( array, position ), position[ position.length - 1], value ) ;
+	}
+	
+	/* primitive versions */
+	public static void set( Object array, int[] position, int value ) throws NotAnArrayException, ArrayDimensionMismatchException{
+		Array.setInt( getArray( array, position ), position[ position.length - 1], value ) ;
+	}
+	public static void set( Object array, int[] position, boolean value ) throws NotAnArrayException, ArrayDimensionMismatchException{
+		Array.setBoolean( getArray( array, position ), position[ position.length - 1], value ) ;
+	}
+	public static void set( Object array, int[] position, byte value ) throws NotAnArrayException, ArrayDimensionMismatchException{
+		Array.setByte( getArray( array, position ), position[ position.length - 1], value ) ;
+	}
+	public static void set( Object array, int[] position, long value ) throws NotAnArrayException, ArrayDimensionMismatchException{
+		Array.setLong( getArray( array, position ), position[ position.length - 1], value ) ;
+	}
+	public static void set( Object array, int[] position, short value ) throws NotAnArrayException, ArrayDimensionMismatchException{
+		Array.setShort( getArray( array, position ), position[ position.length - 1], value ) ;
+	}
+	public static void set( Object array, int[] position, double value ) throws NotAnArrayException, ArrayDimensionMismatchException{
+		Array.setDouble( getArray( array, position ), position[ position.length - 1], value ) ;
+	}
+	public static void set( Object array, int[] position, char value ) throws NotAnArrayException, ArrayDimensionMismatchException{
+		Array.setChar( getArray( array, position ), position[ position.length - 1], value ) ;
+	}
+	public static void set( Object array, int[] position, float value ) throws NotAnArrayException, ArrayDimensionMismatchException{
+		Array.setFloat( getArray( array, position ), position[ position.length - 1], value ) ;
+	}
+
+	
+	public static void set( Object array, int position, Object value ) throws NotAnArrayException, ArrayDimensionMismatchException{
+		set( array, new int[]{ position }, value ); 
+	}
+	public static void set( Object array, int position, int value ) throws NotAnArrayException, ArrayDimensionMismatchException{
+		set( array, new int[]{ position }, value );
+	}
+	public static void set( Object array, int position, boolean value ) throws NotAnArrayException, ArrayDimensionMismatchException{
+		set( array, new int[]{ position }, value );
+	}
+	public static void set( Object array, int position, byte value ) throws NotAnArrayException, ArrayDimensionMismatchException{
+		set( array, new int[]{ position }, value );
+	}
+	public static void set( Object array, int position, long value ) throws NotAnArrayException, ArrayDimensionMismatchException{
+		set( array, new int[]{ position }, value );
+	}
+	public static void set( Object array, int position, short value ) throws NotAnArrayException, ArrayDimensionMismatchException{
+		set( array, new int[]{ position }, value );
+	}
+	public static void set( Object array, int position, double value ) throws NotAnArrayException, ArrayDimensionMismatchException{
+		set( array, new int[]{ position }, value );
+	}
+	public static void set( Object array, int position, char value ) throws NotAnArrayException, ArrayDimensionMismatchException{
+		set( array, new int[]{ position }, value );
+	}
+	public static void set( Object array, int position, float value ) throws NotAnArrayException, ArrayDimensionMismatchException{
+		set( array, new int[]{ position }, value );
+	}
+
+
+	
+	private static Object getArray( Object array, int[] position ) throws NotAnArrayException, ArrayDimensionMismatchException{
+		checkDimensions( array, position ) ;
+		int poslength = position.length ;
+		
+		Object o = array ;
+		int i=0 ;
+		if( poslength > 1 ){
+			while( i< (poslength-1) ){
+					o = Array.get( o, position[i] ) ;
+					i++ ;
+			}
+		}
+		return o ;
+	}
+	
+	// TODO: also have primitive types in value
+	// }}}
+	
+
+	// {{{ unique
+	// TODO: cannot use LinkedHashSet because it first was introduced in 1.4 
+	//       and code in this area needs to work on 1.2 jvm
+	public static Object[] unique( Object[] array ){
+		int n = array.length ;
+		boolean[] unique = new boolean[ array.length ];
+		for( int i=0; i<array.length; i++){
+			unique[i] = true ; 
+		}
+		
+		Vector res = new Vector();
+		boolean added ;
+		for( int i=0; i<n; i++){
+			if( !unique[i] ) continue ;
+			Object current = array[i];
+			added = false; 
+			
+			for( int j=i+1; j<n; j++){
+				Object o_j = array[j] ;
+				if( unique[j] && current.equals( o_j ) ){
+					if( !added ){
+						unique[i] = false; 
+						res.add( current ); 
+						added = true ;
+					}
+					unique[j] = false;
+				}
+			}
+		}
+		// build the array using newInstance so that it has the same
+		// component type as the original array and not just Object
+		Object[] res_array = (Object[])Array.newInstance( array.getClass().getComponentType(), res.size() ) ;
+		res.toArray( res_array ); 
+		return res_array ;
+	}
+	// }}}
+	
+	// {{{ duplicated
+	public static boolean[] duplicated( Object[] array ){
+		int n = array.length ;
+		boolean[] duplicated = new boolean[ array.length ];
+		for( int i=0; i<array.length; i++){
+			duplicated[i] = false ; 
+		}
+		
+		for( int i=0; i<n; i++){
+			if( duplicated[i] ) continue ;
+			Object current = array[i];
+			
+			for( int j=i+1; j<n; j++){
+				Object o_j = array[j] ;
+				if( !duplicated[j] && current.equals( o_j ) ){
+					duplicated[j] = true;
+				}
+			}
+		}
+		
+		return duplicated ;
+	}	
+	// }}}
+	
+	// {{{ anyDuplicated
+	public static int anyDuplicated( Object[] array ){
+		int n = array.length ;
+		
+		for( int i=0; i<n; i++){
+			Object current = array[i];
+			
+			for( int j=i+1; j<n; j++){
+				Object o_j = array[j] ;
+				if( current.equals( o_j ) ){
+					return j ;
+				}
+			}
+		}
+		
+		return -1 ;
+	}	
+	// }}}
+	
+	// {{{ sort
+	/**
+	 * Returns a copy of the array where elements are sorted
+	 *
+	 * @param array array of Objects.  
+	 * @param decreasing if true the sort is in decreasing order
+	 * 
+	 * @throws NotComparableException if the component type of the array does not
+	 * implement the Comparable interface
+	 */
+	public static Object[] sort( Object[] array, boolean decreasing ) throws NotComparableException {
+		Class ct = array.getClass().getComponentType() ;
+		if( Comparable.class.isAssignableFrom( ct ) ){
+			throw new NotComparableException( ct ) ; 
+		}
+		int n = array.length ;
+		Object[] res = copy( array ) ; 
+		Arrays.sort( res ) ;
+		
+		if( !decreasing ){
+			return res ;
+		} else{
+			Object current ;
+			int top = (res.length) / 2 ; 
+			for( int i=0; i<top ; i++ ){
+				current = res[i] ;
+				res[ i ] = res[ n-i-1 ] ;
+				res[ n-i-1 ] = current ; 
+			}
+		}
+		return res ;
+	}
+	// }}}
+	
+	// {{{ rev
+	/**
+	 * Returns a copy of the input array with elements in
+	 * reverse order
+	 * 
+	 * @param original input array
+	 */
+	public static Object[] rev( Object[] original ){
+		int n = original.length ;
+		Object[] copy = (Object[])Array.newInstance( original.getClass().getComponentType() , n ); 
+		for( int i=0; i<n ; i++ ){
+			copy[n-i-1] = original[i] ;
+		}
+		return copy ;
+	}    
+	// }}}
+	    
+	// {{{ copy
+	public static Object[] copy( Object[] original ){
+		int n = original.length ;
+		Object[] copy = (Object[])Array.newInstance( original.getClass().getComponentType() , n ); 
+		for( int i=0; i<n ; i++ ){
+			copy[i] = original[i] ;
+		}
+		return copy ;
+	}
+	// }}}
+	
+	// {{{ getIterableContent
+	public static Object[] getIterableContent( Iterable o){
+		Vector v = new Vector(); 
+		Iterator iterator = o.iterator(); 
+		while( iterator.hasNext() ){
+			v.add( iterator.next() ); 
+		}
+		return v.toArray(); 
+	}
+	// }}}
+	
+	// {{{ rep
+	/**
+	 * Creates a java array by cloning o several times
+	 * 
+	 * @param o object to clone
+	 * @param size number of times to replicate the object
+	 */
+	public static Object[] rep( Object o, int size ) throws Throwable {
+		Object[] res = (Object[])Array.newInstance( o.getClass(), size ) ;
+		if( ! ( o instanceof Cloneable )){
+			return res ;
+		}
+		
+		Method m = getCloneMethod( o.getClass() ) ;
+		boolean access = m.isAccessible() ; 
+		m.setAccessible( true ) ;
+		try{
+			for( int i=0; i<size; i++){
+				Object cloned = o.getClass().cast( m.invoke( o, (Object[])null ) );
+				res[i] = cloned ;
+			}
+		} catch( IllegalAccessException e) {
+			m.setAccessible( access );
+			/* should not happen */
+		} catch( InvocationTargetException e){
+			m.setAccessible( access );
+			throw e.getCause() ; 
+		} 
+		return res ;
+	}
+	
+	private static Method getCloneMethod(Class cl){
+		Method[] methodz ;
+		Method m = null ;
+		while( cl != null ){
+			methodz = cl.getDeclaredMethods( ) ;
+			for( int i=0; i<methodz.length; i++){
+				m = methodz[i];
+				if( "clone".equals( m.getName() ) && m.getParameterTypes().length == 0 ){
+					return m ;
+				}
+			}
+			cl = cl.getSuperclass();        
+		}
+		return null ; /* never happens */
+	}
+	// }}}
+	
+	// {{{ cloneObject
+	public static Object cloneObject( Object o) throws Throwable {
+		Method m = getCloneMethod( o.getClass() ) ;
+		boolean access = m.isAccessible() ; 
+		m.setAccessible( true ) ;
+		
+		Object copy = null ; 
+		
+		try{
+				copy = o.getClass().cast( m.invoke( o, (Object[])null ) );
+		} catch( IllegalAccessException e) {
+			m.setAccessible( access );
+			/* should not happen */
+		} catch( InvocationTargetException e){
+			m.setAccessible( access );
+			throw e.getCause() ; 
+		}
+		return copy ;
+	}
+	// }}}
+	
+	/// boxing and unboxing for Double[] and Integer[]
+        public static final int NA_INTEGER = -2147483648;
+	public static final double NA_REAL = Double.longBitsToDouble(0x7ff00000000007a2L);
+        static final long NA_bits = Double.doubleToRawLongBits(Double.longBitsToDouble(0x7ff00000000007a2L));
+
+	public static double[] unboxDoubles(Double[] o) {
+		if (o == null) return null;
+		int i = 0, n = o.length;
+		double d[] = new double[n];
+		for (i = 0; i < n; i++) d[i] = (o[i] == null) ? NA_REAL : o[i].doubleValue();
+		return d;
+	}
+
+	public static int[] unboxIntegers(Integer[] o) {
+		if (o == null) return null;
+		int i = 0, n = o.length;
+		int d[] = new int[n];
+		for (i = 0; i < n; i++) d[i] = (o[i] == null) ? NA_INTEGER : o[i].intValue();
+		return d;
+	}
+
+	public static int[] unboxBooleans(Boolean[] o) {
+		if (o == null) return null;
+		int i = 0, n = o.length;
+		int d[] = new int[n];
+		for (i = 0; i < n; i++) d[i] = (o[i] == null) ? NA_INTEGER : (o[i].booleanValue() ? 1 : 0);
+		return d;
+	}
+
+        public static boolean isNA(double value) {
+                /* on OS X i386 the MSB of the fraction is set even though R doesn't set it.
+                   Although this is technically a good idea (to make it a QNaN) it's not what R does and thus makes the comparison tricky */
+                return (Double.doubleToRawLongBits(value) & 0xfff7ffffffffffffL) == (NA_bits & 0xfff7ffffffffffffL);
+        }
+
+	public static Double[] boxDoubles(double[] d) {
+		if (d == null) return null;
+		int i = 0, n = d.length;
+		Double o[] = new Double[i];
+		for (i = 0; i < n; i++) if (!isNA(d[i])) o[i] = new Double(d[i]);
+		return o;
+	}
+
+	public static Integer[] boxIntegers(int[] d) {
+		if (d == null) return null;
+		int i = 0, n = d.length;
+		Integer o[] = new Integer[i];
+		for (i = 0; i < n; i++) if (d[i] != NA_INTEGER) o[i] = new Integer(d[i]);
+		return o;
+	}
+
+	public static Boolean[] boxBooleans(int[] d) {
+		if (d == null) return null;
+		int i = 0, n = d.length;
+		Boolean o[] = new Boolean[i];
+		for (i = 0; i < n; i++) if (d[i] != NA_INTEGER) o[i] = new Boolean((d[i] == 0) ? false : true);
+		return o;
+	}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaArrayTools_Test.java b/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaArrayTools_Test.java
new file mode 100644
index 0000000000000000000000000000000000000000..06d3ccf0992c4579626f92a52aec6016b8135736
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaArrayTools_Test.java
@@ -0,0 +1,1476 @@
+// :tabSize=2:indentSize=2:noTabs=false:folding=explicit:collapseFolds=1:
+
+public class RJavaArrayTools_Test {
+	
+	// {{{ main 
+	public static void main(String[] args){
+		System.out.println( "Test suite for RJavaArrayTools" ) ;
+		
+		try{
+			runtests() ; 
+		} catch( TestException e){
+			fails( e ) ; 
+			System.exit(1); 
+		}
+		System.exit(0);
+	}
+	// }}}
+	
+	// {{{ runtests
+	public static void runtests() throws TestException {
+		System.out.println( "Test suite for RJavaArrayTools" ) ;
+		
+		System.out.println( "Testing RJavaArrayTools.isArray" ) ;
+		isarray(); 
+		success() ; 
+		
+		System.out.println( "Testing RJavaArrayTools.isRectangularArray" ) ;
+		isrect();                                
+		success() ; 
+		
+		System.out.println( "Testing RJavaArrayTools.getDimensionLength" ) ;
+		getdimlength();                                
+		success() ; 
+		
+		System.out.println( "Testing RJavaArrayTools.getDimensions" ) ;
+		getdims();                                
+		success() ; 
+		
+		System.out.println( "Testing RJavaArrayTools.getTrueLength" ) ;
+		gettruelength();                                
+		success() ;
+		
+		System.out.println( "Testing RJavaArrayTools.getObjectTypeName" ) ;
+		gettypename();                                
+		success() ;
+		
+		System.out.println( "Testing RJavaArrayTools.isPrimitiveTypeName" ) ;
+		isprim();                                
+		success() ;
+	
+		System.out.println( "Testing RJavaTools.rep" ) ;
+		rep();                                
+		success() ;
+	
+	}
+	// }}}
+	
+	// {{{ fails 
+	private static void fails( TestException e ){
+		System.err.println( "\n" ) ;
+		e.printStackTrace() ;
+		System.err.println( "FAILED" ) ; 
+	}
+	// }}}
+	
+	// {{{ success
+	private static void success(){
+		System.out.println( "PASSED" ) ;    
+	}
+	// }}}
+
+	// {{{ isarray
+	private static void isarray() throws TestException {
+		
+		// {{{ int
+		System.out.print( " isArray( int )" ) ;
+		if( RJavaArrayTools.isArray( 0 ) ){
+			throw new TestException( " isArray( int ) " );
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+		
+		// {{{ boolean
+		System.out.print( " isArray( boolean )" ) ;
+		if( RJavaArrayTools.isArray( true ) ){
+			throw new TestException( " isArray( boolean ) " );
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+		
+		// {{{ byte
+		System.out.print( " isArray( byte )" ) ;
+		if( RJavaArrayTools.isArray( (byte)0 ) ){
+			throw new TestException( " isArray( byte ) " );
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+
+		// {{{ long
+		System.out.print( " isArray( long )" ) ;
+		if( RJavaArrayTools.isArray( (long)0 ) ){
+			throw new TestException( " isArray( long ) " );
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+		
+		// {{{ short
+		System.out.print( " isArray( short )" ) ;
+		if( RJavaArrayTools.isArray( (double)0 ) ){
+			throw new TestException( " isArray( short ) " );
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+
+		// {{{ double
+		System.out.print( " isArray( double )" ) ;
+		if( RJavaArrayTools.isArray( 0.0 ) ){
+			throw new TestException( " isArray( double ) " );
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+		
+		// {{{ char
+		System.out.print( " isArray( char )" ) ;
+		if( RJavaArrayTools.isArray( 'a' ) ){
+			throw new TestException( " isArray( char ) " );
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+		
+		// {{{ float
+		System.out.print( " isArray( float )" ) ;
+		if( RJavaArrayTools.isArray( 0.0f ) ){
+			throw new TestException( " isArray( float ) " ) ;
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+
+		// {{{ String
+		System.out.print( " isArray( String )" ) ;
+		if( RJavaArrayTools.isArray( "dd" ) ){
+			throw new TestException( " isArray( String ) " ) ;
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+		
+		// {{{ int[]
+		int[] x = new int[2] ;
+		System.out.print( " isArray( int[] )" ) ;
+		if( ! RJavaArrayTools.isArray( x ) ){
+			throw new TestException( " !isArray( int[] ) " ) ;
+		}
+		System.out.println( " true : ok" ) ;
+		// }}}
+		
+		// {{{ Object o = new double[2]
+		Object o = new double[2]; 
+		System.out.print( " isArray( double[]   (but declared as 0bject) )" ) ;
+		if( ! RJavaArrayTools.isArray( o ) ){
+			throw new TestException( " !isArray( Object o = new double[2]; ) " ) ;
+		}
+		System.out.println( " true : ok" ) ;
+		// }}}
+		
+		// {{{ null
+		System.out.print( " isArray( null )" ) ;
+		if( RJavaArrayTools.isArray( null ) ){
+			throw new TestException( " isArray( null) " ) ;
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+		
+		
+	}
+	// }}}
+	
+	// {{{ getdimlength
+	private static void getdimlength() throws TestException{
+		
+		System.out.println( "  >> actual arrays" ) ;
+		
+		// {{{ int[] o = new int[10] ;
+		int[] o = new int[10] ;
+		System.out.print( "  int[] o = new int[10] ;" ) ;
+		try{
+			if( RJavaArrayTools.getDimensionLength( o ) != 1 ){
+				throw new TestException( "getDimensionLength( int[10] ) != 1" ); 
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array int[10]" ) ;
+		}
+		System.out.println( " 1 : ok " ); 
+		// }}}           
+
+		// {{{ int[] o = new int[0] ;
+		o = new int[0] ;
+		System.out.print( "  int[] o = new int[0] ;" ) ;
+		try{
+			if( RJavaArrayTools.getDimensionLength( o ) != 1 ){
+				throw new TestException( "getDimensionLength( int[0] ) != 1" ); 
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array int[0]" ) ;
+		}
+		System.out.println( " 1 : ok " ); 
+		// }}}           
+
+		// {{{ Object[][] = new Object[10][10] ;
+		Object[][] ob = new Object[10][10] ;
+		System.out.print( "  new Object[10][10]" ) ;
+		try{
+			if( RJavaArrayTools.getDimensionLength( ob ) != 2 ){
+				throw new TestException( "getDimensionLength( new Object[10][10] ) != 2" ); 
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array Object[10][10]" ) ;
+		}
+		System.out.println( " 2 : ok " ); 
+		// }}}
+
+		// {{{ Object[][] = new Object[10][10][10] ;
+		Object[][][] obj = new Object[10][10][10] ;
+		System.out.print( "  new Object[10][10][10]" ) ;
+		try{
+			if( RJavaArrayTools.getDimensionLength( obj ) != 3 ){
+				throw new TestException( "getDimensionLength( new Object[10][10][3] ) != 3" ); 
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array Object[10][10][3]" ) ;
+		}
+		System.out.println( " 3 : ok " ); 
+		// }}}
+		
+		// {{{ Object 
+		System.out.println( "  >> Object" ) ;
+		
+		System.out.print( "  new Double('10.2') " ) ;
+		boolean ok = false; 
+		try{
+			RJavaArrayTools.getDimensionLength( new Double("10.3") ) ;
+		} catch( NotAnArrayException e){
+			ok = true ; 
+		}
+		if( !ok ){
+			throw new TestException( "getDimensionLength(Double) did not throw exception" ); 
+		}
+		System.out.println( " -> NotAnArrayException : ok " ); 
+		// }}}
+		
+		// {{{ primitives
+		System.out.println( "  >> Testing primitive types" ) ;
+		// {{{ int
+		
+		System.out.print( "  getDimensionLength( int )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getDimensionLength( 0 ) ; 
+		} catch( NotAnArrayException e){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getDimensionLength( int ) not throwing exception" );
+		System.out.println( " ok" ) ;
+		// }}}
+		
+		// {{{ boolean
+		System.out.print( "  getDimensionLength( boolean )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getDimensionLength( true ) ; 
+		} catch( NotAnArrayException e){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getDimensionLength( boolean ) not throwing exception" );
+		System.out.println( " : ok" ) ;
+		// }}}
+		
+		// {{{ byte
+		System.out.print( "  getDimensionLength( byte )" ) ;
+		ok = false;
+		try{
+			RJavaArrayTools.getDimensionLength( (byte)0 ) ;
+		} catch( NotAnArrayException e){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getDimensionLength( byte ) not throwing exception" );
+		System.out.println( " : ok" ) ;
+		// }}}
+
+		// {{{ long
+		System.out.print( "  getDimensionLength( long )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getDimensionLength( (long)0 ); 
+		} catch( NotAnArrayException e){
+			ok = true; 
+		}
+		if( !ok) throw new TestException( " getDimensionLength( long ) not throwing exception" );
+		System.out.println( " ok" ) ;
+		// }}}
+		
+		// {{{ short
+		System.out.print( "  getDimensionLength( short )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getDimensionLength( (double)0 ) ;
+		} catch( NotAnArrayException e ){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getDimensionLength( short ) not throwing exception" );
+		System.out.println( "  : ok" ) ;
+		// }}}
+
+		// {{{ double
+		System.out.print( "  getDimensionLength( double )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getDimensionLength( 0.0 ); 
+		} catch( NotAnArrayException e ){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getDimensionLength( double ) not throwing exception" );
+		System.out.println( " : ok" ) ;
+		// }}}
+		
+		// {{{ char
+		System.out.print( "  getDimensionLength( char )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getDimensionLength( 'a' ) ; 
+		} catch( NotAnArrayException e ){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getDimensionLength( char ) not throwing exception " );
+		System.out.println( " : ok" ) ;
+		// }}}
+		
+		// {{{ float
+		System.out.print( "  getDimensionLength( float )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getDimensionLength( 0.0f ) ;
+		} catch( NotAnArrayException e ){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getDimensionLength( float ) not throwing exception " ) ;
+		System.out.println( " : ok" ) ;
+		// }}}
+
+		// }}}
+		
+		// {{{ null 
+		System.out.print( "  getDimensionLength( null )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getDimensionLength( null ) ;
+		} catch( NullPointerException e ){
+			ok = true; 
+		} catch( NotAnArrayException e ){
+			throw new TestException("getDimensionLength( null ) throwing wrong kind of exception") ; 
+		}
+		if( !ok ) throw new TestException( " getDimensionLength( null ) not throwing exception " ) ;
+		System.out.println( " : ok" ) ;
+		
+		// }}}
+	}
+	// }}}
+	
+	// {{{ getdims
+	private static void getdims() throws TestException{
+		int[] res = null ;
+		
+		// {{{ actual arrays
+		// {{{ int[] o = new int[10] ;
+		int[] o = new int[10] ;
+		System.out.print( "  int[] o = new int[10] ;" ) ;
+		try{
+			res = RJavaArrayTools.getDimensions( o ); 
+			if( res.length != 1 ){
+				throw new TestException( "getDimensions( int[10]).length != 1" );  
+			}
+			if( res[0] != 10 ){
+				throw new TestException( "getDimensions( int[10])[0] != 10" );
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array int[10]" ) ;
+		}
+		System.out.println( " c( 10 ) : ok " ); 
+		// }}}           
+
+		// {{{ Object[][] = new Object[10][10] ;
+		Object[][] ob = new Object[10][10] ;
+		System.out.print( "  new Object[10][10]" ) ;
+		try{
+			res = RJavaArrayTools.getDimensions( ob ) ;
+			if( res.length != 2 ){
+				throw new TestException( "getDimensions( Object[10][10] ).length != 2" ); 
+			}
+			if( res[0] != 10 ){
+				throw new TestException( "getDimensions( Object[10][10] )[0] != 10" );
+			}
+			if( res[1] != 10 ){
+				throw new TestException( "getDimensions( Object[10][10] )[1] != 10" );
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array Object[10][10]" ) ;
+		}
+		System.out.println( " c(10,10) : ok " ); 
+		// }}}
+
+		// {{{ Object[][] = new Object[10][10][10] ;
+		Object[][][] obj = new Object[10][10][10] ;
+		System.out.print( "  new Object[10][10][10]" ) ;
+		try{
+			res = RJavaArrayTools.getDimensions( obj ) ;
+			if( res.length != 3 ){
+				throw new TestException( "getDimensions( Object[10][10][10] ).length != 3" ); 
+			}
+			if( res[0] != 10 ){
+				throw new TestException( "getDimensions( Object[10][10][10] )[0] != 10" );
+			}
+			if( res[1] != 10 ){
+				throw new TestException( "getDimensions( Object[10][10][10] )[1] != 10" );
+			}
+			if( res[2] != 10 ){
+				throw new TestException( "getDimensions( Object[10][10][10] )[1] != 10" );
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array Object[10][10][10]" ) ;
+		}
+		System.out.println( " c(10,10,10) : ok " ); 
+		// }}}
+		// }}}
+
+		// {{{ zeroes
+		System.out.println( "  >> zeroes " ) ;
+		
+		// {{{ int[] o = new int[0] ;
+		o = new int[0] ;
+		System.out.print( "  int[] o = new int[0] ;" ) ;
+		try{
+			res = RJavaArrayTools.getDimensions( o ) ; 
+			if( res.length != 1 ){
+				throw new TestException( "getDimensions( int[0]).length != 1" ); 
+			}
+			if( res[0] != 0){
+				throw new TestException( "getDimensions( int[0])[0] != 0" );
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array int[0]" ) ;
+		}
+		System.out.println( " c(0) : ok " ); 
+		// }}}      
+		
+		// {{{ Object[][] = new Object[10][10][0] ;
+		obj = new Object[10][10][0] ;
+		System.out.print( "  new Object[10][10][0]" ) ;
+		try{
+			res = RJavaArrayTools.getDimensions( obj ) ;
+			if( res.length != 3 ){
+				throw new TestException( "getDimensions( Object[10][10][0] ).length != 3" ); 
+			}
+			if( res[0] != 10 ){
+				throw new TestException( "getDimensions( Object[10][10][0] )[0] != 10" );
+			}
+			if( res[1] != 10 ){
+				throw new TestException( "getDimensions( Object[10][10][0] )[1] != 10" );
+			}
+			if( res[2] != 0 ){
+				throw new TestException( "getDimensions( Object[10][10][0] )[1] != 0" );
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array Object[10][10][0]" ) ;
+		}
+		System.out.println( " c(10,10,0) : ok " ); 
+		// }}}
+		
+		// {{{ Object[][] = new Object[10][0][10] ;
+		obj = new Object[10][0][10] ;
+		System.out.print( "  new Object[10][0][10]" ) ;
+		try{
+			res = RJavaArrayTools.getDimensions( obj ) ;
+			if( res.length != 3 ){
+				throw new TestException( "getDimensions( Object[10][0][0] ).length != 3" ); 
+			}
+			if( res[0] != 10 ){
+				throw new TestException( "getDimensions( Object[10][0][0] )[0] != 10" );
+			}
+			if( res[1] != 0 ){
+				throw new TestException( "getDimensions( Object[10][0][0] )[1] != 0" );
+			}
+			if( res[2] != 0 ){
+				throw new TestException( "getDimensions( Object[10][0][0] )[1] != 0" );
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array Object[10][0][10]" ) ;
+		}
+		System.out.println( " c(10,0,0) : ok " ); 
+		// }}}
+		
+		// }}}
+
+		// {{{ Object 
+		System.out.println( "  >> Object" ) ;
+		
+		System.out.print( "  new Double('10.2') " ) ;
+		boolean ok = false; 
+		try{
+			res = RJavaArrayTools.getDimensions( new Double("10.3") ) ;
+		} catch( NotAnArrayException e){
+			ok = true ; 
+		}
+		if( !ok ){
+			throw new TestException( "getDimensions(Double) did not throw exception" ); 
+		}
+		System.out.println( " -> NotAnArrayException : ok " ); 
+		// }}}
+		
+		// {{{ primitives
+		System.out.println( "  >> Testing primitive types" ) ;
+		// {{{ int
+		
+		System.out.print( "  getDimensions( int )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getDimensions( 0 ) ; 
+		} catch( NotAnArrayException e){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getDimensions( int ) not throwing exception" );
+		System.out.println( " ok" ) ;
+		// }}}
+		
+		// {{{ boolean
+		System.out.print( "  getDimensions( boolean )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getDimensions( true ) ; 
+		} catch( NotAnArrayException e){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getDimensions( boolean ) not throwing exception" );
+		System.out.println( " : ok" ) ;
+		// }}}
+		
+		// {{{ byte
+		System.out.print( "  getDimensions( byte )" ) ;
+		ok = false;
+		try{
+			RJavaArrayTools.getDimensions( (byte)0 ) ;
+		} catch( NotAnArrayException e){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getDimensions( byte ) not throwing exception" );
+		System.out.println( " : ok" ) ;
+		// }}}
+
+		// {{{ long
+		System.out.print( "  getDimensions( long )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getDimensions( (long)0 ); 
+		} catch( NotAnArrayException e){
+			ok = true; 
+		}
+		if( !ok) throw new TestException( " getDimensions( long ) not throwing exception" );
+		System.out.println( " ok" ) ;
+		// }}}
+		
+		// {{{ short
+		System.out.print( "  getDimensions( short )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getDimensions( (double)0 ) ;
+		} catch( NotAnArrayException e ){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getDimensions( short ) not throwing exception" );
+		System.out.println( "  : ok" ) ;
+		// }}}
+
+		// {{{ double
+		System.out.print( "  getDimensions( double )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getDimensions( 0.0 ); 
+		} catch( NotAnArrayException e ){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getDimensions( double ) not throwing exception" );
+		System.out.println( " : ok" ) ;
+		// }}}
+		
+		// {{{ char
+		System.out.print( "  getDimensions( char )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getDimensions( 'a' ) ; 
+		} catch( NotAnArrayException e ){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getDimensions( char ) not throwing exception " );
+		System.out.println( " : ok" ) ;
+		// }}}
+		
+		// {{{ float
+		System.out.print( "  getDimensions( float )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getDimensions( 0.0f ) ;
+		} catch( NotAnArrayException e ){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getDimensions( float ) not throwing exception " ) ;
+		System.out.println( " : ok" ) ;
+		// }}}
+
+		// }}}
+		
+		// {{{ null 
+		System.out.print( "  getDimensions( null )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getDimensions( null ) ;
+		} catch( NullPointerException e ){
+			ok = true; 
+		} catch( NotAnArrayException e ){
+			throw new TestException("getDimensions( null ) throwing wrong kind of exception") ; 
+		}
+		if( !ok ) throw new TestException( " getDimensions( null ) not throwing exception " ) ;
+		System.out.println( " : ok" ) ;
+		
+		// }}}
+		
+	}
+	// }}}
+	
+	// {{{ gettruelength
+	private static void gettruelength() throws TestException{
+		int res = 0 ;
+		
+		// {{{ actual arrays
+		// {{{ int[] o = new int[10] ;
+		int[] o = new int[10] ;
+		System.out.print( "  int[] o = new int[10] ;" ) ;
+		try{
+			res = RJavaArrayTools.getTrueLength( o ); 
+			if( res != 10 ){
+				throw new TestException( "getTrueLength( int[10]) != 10" );  
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array int[10]" ) ;
+		}
+		System.out.println( " 10 : ok " ); 
+		// }}}           
+
+		// {{{ Object[][] = new Object[10][10] ;
+		Object[][] ob = new Object[10][10] ;
+		System.out.print( "  new Object[10][10]" ) ;
+		try{
+			res = RJavaArrayTools.getTrueLength( ob ) ;
+			if( res != 100 ){
+				throw new TestException( "getTrueLength( Object[10][10] ) != 100" ); 
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array Object[10][10]" ) ;
+		}
+		System.out.println( " 100 : ok " ); 
+		// }}}
+
+		// {{{ Object[][] = new Object[10][10][10] ;
+		Object[][][] obj = new Object[10][10][10] ;
+		System.out.print( "  new Object[10][10][10]" ) ;
+		try{
+			res = RJavaArrayTools.getTrueLength( obj ) ;
+			if( res != 1000 ){
+				throw new TestException( "getTrueLength( Object[10][10][10] ) != 1000" ); 
+			}
+			
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array Object[10][10][10]" ) ;
+		}
+		System.out.println( " 1000 : ok " ); 
+		// }}}
+		// }}}
+
+		// {{{ zeroes
+		System.out.println( "  >> zeroes " ) ;
+		
+		// {{{ int[] o = new int[0] ;
+		o = new int[0] ;
+		System.out.print( "  int[] o = new int[0] ;" ) ;
+		try{
+			res = RJavaArrayTools.getTrueLength( o ) ; 
+			if( res != 0 ){
+				throw new TestException( "getTrueLength( int[0]) != 0" ); 
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array int[0]" ) ;
+		}
+		System.out.println( " c(0) : ok " ); 
+		// }}}      
+		
+		// {{{ Object[][] = new Object[10][10][0] ;
+		obj = new Object[10][10][0] ;
+		System.out.print( "  new Object[10][10][0]" ) ;
+		try{
+			res = RJavaArrayTools.getTrueLength( obj ) ;
+			if( res != 0 ){
+				throw new TestException( "getTrueLength( Object[10][10][0] ) != 0" ); 
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array Object[10][10][0]" ) ;
+		}
+		System.out.println( " 0 : ok " ); 
+		// }}}
+		
+		// {{{ Object[][] = new Object[10][0][10] ;
+		obj = new Object[10][0][10] ;
+		System.out.print( "  new Object[10][0][10]" ) ;
+		try{
+			res = RJavaArrayTools.getTrueLength( obj ) ;
+			if( res != 0){
+				throw new TestException( "getTrueLength( Object[10][0][0] ) != 0" ); 
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array Object[10][0][10]" ) ;
+		}
+		System.out.println( " 0 : ok " ); 
+		// }}}
+		
+		// }}}
+
+		// {{{ Object 
+		System.out.println( "  >> Object" ) ;
+		
+		System.out.print( "  new Double('10.2') " ) ;
+		boolean ok = false; 
+		try{
+			res = RJavaArrayTools.getTrueLength( new Double("10.3") ) ;
+		} catch( NotAnArrayException e){
+			ok = true ; 
+		}
+		if( !ok ){
+			throw new TestException( "getTrueLength(Double) did not throw exception" ); 
+		}
+		System.out.println( " -> NotAnArrayException : ok " ); 
+		// }}}
+		
+		
+		// {{{ primitives
+		System.out.println( "  >> Testing primitive types" ) ;
+		// {{{ int
+		
+		System.out.print( "  getTrueLength( int )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getTrueLength( 0 ) ; 
+		} catch( NotAnArrayException e){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getTrueLength( int ) not throwing exception" );
+		System.out.println( " ok" ) ;
+		// }}}
+		
+		// {{{ boolean
+		System.out.print( "  getTrueLength( boolean )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getTrueLength( true ) ; 
+		} catch( NotAnArrayException e){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getTrueLength( boolean ) not throwing exception" );
+		System.out.println( " : ok" ) ;
+		// }}}
+		
+		// {{{ byte
+		System.out.print( "  getTrueLength( byte )" ) ;
+		ok = false;
+		try{
+			RJavaArrayTools.getTrueLength( (byte)0 ) ;
+		} catch( NotAnArrayException e){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getTrueLength( byte ) not throwing exception" );
+		System.out.println( " : ok" ) ;
+		// }}}
+
+		// {{{ long
+		System.out.print( "  getTrueLength( long )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getTrueLength( (long)0 ); 
+		} catch( NotAnArrayException e){
+			ok = true; 
+		}
+		if( !ok) throw new TestException( " getTrueLength( long ) not throwing exception" );
+		System.out.println( " ok" ) ;
+		// }}}
+		
+		// {{{ short
+		System.out.print( "  getTrueLength( short )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getTrueLength( (double)0 ) ;
+		} catch( NotAnArrayException e ){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getTrueLength( short ) not throwing exception" );
+		System.out.println( "  : ok" ) ;
+		// }}}
+
+		// {{{ double
+		System.out.print( "  getTrueLength( double )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getTrueLength( 0.0 ); 
+		} catch( NotAnArrayException e ){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getTrueLength( double ) not throwing exception" );
+		System.out.println( " : ok" ) ;
+		// }}}
+		
+		// {{{ char
+		System.out.print( "  getTrueLength( char )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getTrueLength( 'a' ) ; 
+		} catch( NotAnArrayException e ){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getTrueLength( char ) not throwing exception " );
+		System.out.println( " : ok" ) ;
+		// }}}
+		
+		// {{{ float
+		System.out.print( "  getTrueLength( float )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getTrueLength( 0.0f ) ;
+		} catch( NotAnArrayException e ){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getTrueLength( float ) not throwing exception " ) ;
+		System.out.println( " : ok" ) ;
+		// }}}
+
+		// }}}
+		
+		// {{{ null 
+		System.out.print( "  getTrueLength( null )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getTrueLength( null ) ;
+		} catch( NullPointerException e ){
+			ok = true; 
+		} catch( NotAnArrayException e ){
+			throw new TestException("getTrueLength( null ) throwing wrong kind of exception") ; 
+		}
+		if( !ok ) throw new TestException( " getTrueLength( null ) not throwing exception " ) ;
+		System.out.println( " : ok" ) ;
+		
+		// }}}
+		
+	}
+	// }}}
+	
+	// {{{ isRectangular
+	private static void isrect() throws TestException {
+						
+		// {{{ int
+		System.out.print( " isRectangularArray( int )" ) ;
+		if( RJavaArrayTools.isRectangularArray( 0 ) ){
+			throw new TestException( " isRectangularArray( int ) " );
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+		
+		// {{{ boolean
+		System.out.print( " isRectangularArray( boolean )" ) ;
+		if( RJavaArrayTools.isRectangularArray( true ) ){
+			throw new TestException( " isRectangularArray( boolean ) " );
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+		
+		// {{{ byte
+		System.out.print( " isRectangularArray( byte )" ) ;
+		if( RJavaArrayTools.isRectangularArray( (byte)0 ) ){
+			throw new TestException( " isRectangularArray( byte ) " );
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+
+		// {{{ long
+		System.out.print( " isRectangularArray( long )" ) ;
+		if( RJavaArrayTools.isRectangularArray( (long)0 ) ){
+			throw new TestException( " isRectangularArray( long ) " );
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+		
+		// {{{ short
+		System.out.print( " isRectangularArray( short )" ) ;
+		if( RJavaArrayTools.isRectangularArray( (double)0 ) ){
+			throw new TestException( " isRectangularArray( short ) " );
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+
+		// {{{ double
+		System.out.print( " isRectangularArray( double )" ) ;
+		if( RJavaArrayTools.isRectangularArray( 0.0 ) ){
+			throw new TestException( " isRectangularArray( double ) " );
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+		
+		// {{{ char
+		System.out.print( " isRectangularArray( char )" ) ;
+		if( RJavaArrayTools.isRectangularArray( 'a' ) ){
+			throw new TestException( " isRectangularArray( char ) " );
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+		
+		// {{{ float
+		System.out.print( " isRectangularArray( float )" ) ;
+		if( RJavaArrayTools.isRectangularArray( 0.0f ) ){
+			throw new TestException( " isRectangularArray( float ) " ) ;
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+
+		// {{{ String
+		System.out.print( " isRectangularArray( String )" ) ;
+		if( RJavaArrayTools.isRectangularArray( "dd" ) ){
+			throw new TestException( " isRectangularArray( String ) " ) ;
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+		
+		// {{{ int[]
+		int[] x = new int[2] ;
+		System.out.print( " isRectangularArray( int[] )" ) ;
+		if( ! RJavaArrayTools.isRectangularArray( x ) ){
+			throw new TestException( " !isRectangularArray( int[] ) " ) ;
+		}
+		System.out.println( " true : ok" ) ;
+		// }}}
+		
+		// {{{ Object o = new double[2]
+		Object o = new double[2]; 
+		System.out.print( " isRectangularArray( double[]   (but declared as 0bject) )" ) ;
+		if( ! RJavaArrayTools.isRectangularArray( o ) ){
+			throw new TestException( " !isRectangularArray( Object o = new double[2]; ) " ) ;
+		}
+		System.out.println( " true : ok" ) ;
+		// }}}
+		
+		// {{{ null
+		System.out.print( " isRectangularArray( null )" ) ;
+		if( RJavaArrayTools.isRectangularArray( null ) ){
+			throw new TestException( " isRectangularArray( null) " ) ;
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+		
+		// {{{ 2d rectangular
+		int[][] x2d = new int[3][4]; 
+		System.out.print( " isRectangularArray( new int[3][4] )" ) ;
+		if( ! RJavaArrayTools.isRectangularArray( x2d ) ){
+			throw new TestException( " !isRectangularArray( new int[3][4] ) " ) ;
+		}
+		System.out.println( " true : ok" ) ;
+		// }}}
+		
+		// {{{ 2d not rectangular
+		int[][] x2d_not = new int[2][] ;
+		x2d_not[0] = new int[2] ;
+		x2d_not[1] = new int[3] ;
+		
+		System.out.print( " isRectangularArray( new int[2][2,4] )" ) ;
+		if( RJavaArrayTools.isRectangularArray( x2d_not ) ){
+			throw new TestException( " !isRectangularArray( new int[2][2,4] ) " ) ;
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+		
+		// {{{ 3d not rectangular
+		int[][][] x3d_not = new int[1][][] ;
+		x3d_not[0] = new int[2][];
+		x3d_not[0][0] = new int[1] ;
+		x3d_not[0][1] = new int[2] ;
+		
+		System.out.print( " isRectangularArray( new int[2][2][10,25] )" ) ;
+		if( RJavaArrayTools.isRectangularArray( x3d_not ) ){
+			throw new TestException( " !isRectangularArray( new int[2][2][10,25] ) " ) ;
+		}
+		System.out.println( " false : ok" ) ;
+		// }}}
+	}
+	// }}}
+	
+	// {{{ getObjectTypeName
+	private static void gettypename() throws TestException {
+		String res ;
+		
+		// {{{ actual arrays
+		// {{{ int[] o = new int[10] ;
+		System.out.print( "  int[] o = new int[10] ;" ) ;
+		try{
+			res = RJavaArrayTools.getObjectTypeName( new int[1] ); 
+			if( !res.equals("I") ){
+				throw new TestException( "getObjectTypeName(int[]) != 'I' " );  
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array int[10]" ) ;
+		}
+		System.out.println( " I : ok " ); 
+		// }}}           
+
+		// {{{ boolean[] ;
+		System.out.print( "  boolean[]" ) ;
+		try{
+			res = RJavaArrayTools.getObjectTypeName( new boolean[1] ); 
+			if( !res.equals("Z") ){
+				throw new TestException( "getObjectTypeName(boolean[]) != 'Z' " );  
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array boolean[10]" ) ;
+		}
+		System.out.println( " Z : ok " ); 
+		// }}}           
+		
+		// {{{ byte[] ;
+		System.out.print( "  byte[]" ) ;
+		try{
+			res = RJavaArrayTools.getObjectTypeName( new byte[1] ); 
+			if( !res.equals("B") ){
+				throw new TestException( "getObjectTypeName(byte[]) != 'B' " );  
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array byte[10]" ) ;
+		}
+		System.out.println( " B : ok " ); 
+		// }}}           
+		
+				// {{{ long[] ;
+		System.out.print( "  long[]" ) ;
+		try{
+			res = RJavaArrayTools.getObjectTypeName( new long[1] ); 
+			if( !res.equals("J") ){
+				throw new TestException( "getObjectTypeName(long[]) != 'J' " );  
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array long[10]" ) ;
+		}
+		System.out.println( " J : ok " ); 
+		// }}}           
+
+		// {{{ short[] ;
+		System.out.print( "  short[]" ) ;
+		try{
+			res = RJavaArrayTools.getObjectTypeName( new short[1] ); 
+			if( !res.equals("S") ){
+				throw new TestException( "getObjectTypeName(short[]) != 'S' " );  
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array short[10]" ) ;
+		}
+		System.out.println( " S : ok " ); 
+		// }}}           
+		
+				// {{{ double[] ;
+		System.out.print( "  double[]" ) ;
+		try{
+			res = RJavaArrayTools.getObjectTypeName( new double[1] ); 
+			if( !res.equals("D") ){
+				throw new TestException( "getObjectTypeName(double[]) != 'D' " );  
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array double[10]" ) ;
+		}
+		System.out.println( " D : ok " ); 
+		// }}}           
+
+				// {{{ char[] ;
+		System.out.print( "  char[]" ) ;
+		try{
+			res = RJavaArrayTools.getObjectTypeName( new char[1] ); 
+			if( !res.equals("C") ){
+				throw new TestException( "getObjectTypeName(char[]) != 'C' " );  
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array char[10]" ) ;
+		}
+		System.out.println( " C : ok " ); 
+		// }}}
+		
+				// {{{ float[] ;
+		System.out.print( "  float[]" ) ;
+		try{
+			res = RJavaArrayTools.getObjectTypeName( new float[1] ); 
+			if( !res.equals("F") ){
+				throw new TestException( "getObjectTypeName(float[]) != 'F' " );  
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array float[10]" ) ;
+		}
+		System.out.println( " F : ok " ); 
+		// }}}           
+
+		System.out.println("  >> multi dim primitive arrays" ) ;
+		
+		// {{{ int[] o = new int[10] ;
+		System.out.print( "  int[][] ;" ) ;
+		try{
+			res = RJavaArrayTools.getObjectTypeName( new int[1][1] ); 
+			if( !res.equals("I") ){
+				throw new TestException( "getObjectTypeName(int[]) != 'I' " );  
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array int[10]" ) ;
+		}
+		System.out.println( " I : ok " ); 
+		// }}}           
+
+		// {{{ boolean[] ;
+		System.out.print( "  boolean[][]" ) ;
+		try{
+			res = RJavaArrayTools.getObjectTypeName( new boolean[1][1] ); 
+			if( !res.equals("Z") ){
+				throw new TestException( "getObjectTypeName(boolean[]) != 'Z' " );  
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array boolean[10]" ) ;
+		}
+		System.out.println( " Z : ok " ); 
+		// }}}           
+		
+		// {{{ byte[] ;
+		System.out.print( "  byte[][]" ) ;
+		try{
+			res = RJavaArrayTools.getObjectTypeName( new byte[1][1] ); 
+			if( !res.equals("B") ){
+				throw new TestException( "getObjectTypeName(byte[]) != 'B' " );  
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array byte[10]" ) ;
+		}
+		System.out.println( " B : ok " ); 
+		// }}}           
+		
+				// {{{ long[] ;
+		System.out.print( "  long[][]" ) ;
+		try{
+			res = RJavaArrayTools.getObjectTypeName( new long[1][1] ); 
+			if( !res.equals("J") ){
+				throw new TestException( "getObjectTypeName(long[]) != 'J' " );  
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array long[10]" ) ;
+		}
+		System.out.println( " J : ok " ); 
+		// }}}           
+
+		// {{{ short[] ;
+		System.out.print( "  short[][]" ) ;
+		try{
+			res = RJavaArrayTools.getObjectTypeName( new short[1][1] ); 
+			if( !res.equals("S") ){
+				throw new TestException( "getObjectTypeName(short[]) != 'S' " );  
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array short[10]" ) ;
+		}
+		System.out.println( " S : ok " ); 
+		// }}}           
+		
+				// {{{ double[] ;
+		System.out.print( "  double[][]" ) ;
+		try{
+			res = RJavaArrayTools.getObjectTypeName( new double[1][1] ); 
+			if( !res.equals("D") ){
+				throw new TestException( "getObjectTypeName(double[]) != 'D' " );  
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array double[10]" ) ;
+		}
+		System.out.println( " D : ok " ); 
+		// }}}           
+
+				// {{{ char[] ;
+		System.out.print( "  char[][]" ) ;
+		try{
+			res = RJavaArrayTools.getObjectTypeName( new char[1][1] ); 
+			if( !res.equals("C") ){
+				throw new TestException( "getObjectTypeName(char[]) != 'C' " );  
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array char[10]" ) ;
+		}
+		System.out.println( " C : ok " ); 
+		// }}}
+		
+				// {{{ float[] ;
+		System.out.print( "  float[][]" ) ;
+		try{
+			res = RJavaArrayTools.getObjectTypeName( new float[1][1] ); 
+			if( !res.equals("F") ){
+				throw new TestException( "getObjectTypeName(float[]) != 'F' " );  
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array float[10]" ) ;
+		}
+		System.out.println( " F : ok " ); 
+		// }}}           
+
+		
+		
+		// {{{ Object[][] = new Object[10][10] ;
+		Object[][] ob = new Object[10][10] ;
+		System.out.print( "  new Object[10][10]" ) ;
+		try{
+			res = RJavaArrayTools.getObjectTypeName( ob ) ;
+			if( !res.equals("java.lang.Object") ){
+				throw new TestException( "getObjectTypeName(Object[][]) != 'java.lang.Object' " ); 
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array Object[10][10]" ) ;
+		}
+		System.out.println( " : ok " ); 
+		// }}}
+
+		// {{{ Object[][] = new Object[10][10][10] ;
+		Object[][][] obj = new Object[10][10][10] ;
+		System.out.print( "  new Object[10][10][10]" ) ;
+		try{
+			res = RJavaArrayTools.getObjectTypeName( obj ) ;
+			if( !res.equals("java.lang.Object") ){
+				throw new TestException( "getObjectTypeName( Object[10][10][10] ) != 'java.lang.Object' " ); 
+			}
+			
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array Object[10][10][10]" ) ;
+		}
+		System.out.println( " 1000 : ok " ); 
+		// }}}
+		// }}}
+
+		// {{{ zeroes
+		System.out.println( "  >> zeroes " ) ;
+		
+		// {{{ int[] o = new int[0] ;
+		int[] o = new int[0] ;
+		System.out.print( "  int[] o = new int[0] ;" ) ;
+		try{
+			res = RJavaArrayTools.getObjectTypeName( o ) ; 
+			if( !res.equals("I") ){
+				throw new TestException( "getObjectTypeName(int[0]) != 'I' " ); 
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array int[0]" ) ;
+		}
+		System.out.println( " : ok " ); 
+		// }}}
+		
+		// {{{ Object[][] = new Object[10][10][0] ;
+		obj = new Object[10][10][0] ;
+		System.out.print( "  new Object[10][10][0]" ) ;
+		try{
+			res = RJavaArrayTools.getObjectTypeName( obj ) ;
+			if( !res.equals("java.lang.Object") ){
+				throw new TestException( "getObjectTypeName( Object[10][10][0] ) != 'java.lang.Object' " ); 
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array Object[10][10][0]" ) ;
+		}
+		System.out.println( " : ok " ); 
+		// }}}
+		
+		// {{{ Object[][] = new Object[10][0][10] ;
+		obj = new Object[10][0][10] ;
+		System.out.print( "  new Object[10][0][10]" ) ;
+		try{
+			res = RJavaArrayTools.getObjectTypeName( obj ) ;
+			if( !res.equals("java.lang.Object") ){
+				throw new TestException( "getObjectTypeName( Object[10][0][0] ) != 'java.lang.Object' " ); 
+			}
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array Object[10][0][10]" ) ;
+		}
+		System.out.println( " 0 : ok " ); 
+		// }}}
+		
+		// }}}
+
+		// {{{ Object 
+		System.out.println( "  >> Object" ) ;
+		
+		System.out.print( "  new Double('10.2') " ) ;
+		boolean ok = false; 
+		try{
+			res = RJavaArrayTools.getObjectTypeName( new Double("10.3") ) ;
+		} catch( NotAnArrayException e){
+			ok = true ; 
+		}
+		if( !ok ){
+			throw new TestException( "getObjectTypeName(Double) did not throw exception" ); 
+		}
+		System.out.println( " -> NotAnArrayException : ok " ); 
+		// }}}
+		
+		// {{{ primitives
+		System.out.println( "  >> Testing primitive types" ) ;
+		// {{{ int
+		
+		System.out.print( "  getObjectTypeName( int )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getObjectTypeName( 0 ) ; 
+		} catch( NotAnArrayException e){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getObjectTypeName( int ) not throwing exception" );
+		System.out.println( " ok" ) ;
+		// }}}
+		
+		// {{{ boolean
+		System.out.print( "  getObjectTypeName( boolean )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getObjectTypeName( true ) ; 
+		} catch( NotAnArrayException e){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getObjectTypeName( boolean ) not throwing exception" );
+		System.out.println( " : ok" ) ;
+		// }}}
+		
+		// {{{ byte
+		System.out.print( "  getObjectTypeName( byte )" ) ;
+		ok = false;
+		try{
+			RJavaArrayTools.getObjectTypeName( (byte)0 ) ;
+		} catch( NotAnArrayException e){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getObjectTypeName( byte ) not throwing exception" );
+		System.out.println( " : ok" ) ;
+		// }}}
+
+		// {{{ long
+		System.out.print( "  getObjectTypeName( long )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getObjectTypeName( (long)0 ); 
+		} catch( NotAnArrayException e){
+			ok = true; 
+		}
+		if( !ok) throw new TestException( " getObjectTypeName( long ) not throwing exception" );
+		System.out.println( " ok" ) ;
+		// }}}
+		
+		// {{{ short
+		System.out.print( "  getObjectTypeName( short )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getObjectTypeName( (double)0 ) ;
+		} catch( NotAnArrayException e ){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getObjectTypeName( short ) not throwing exception" );
+		System.out.println( "  : ok" ) ;
+		// }}}
+
+		// {{{ double
+		System.out.print( "  getObjectTypeName( double )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getObjectTypeName( 0.0 ); 
+		} catch( NotAnArrayException e ){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getObjectTypeName( double ) not throwing exception" );
+		System.out.println( " : ok" ) ;
+		// }}}
+		
+		// {{{ char
+		System.out.print( "  getObjectTypeName( char )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getObjectTypeName( 'a' ) ; 
+		} catch( NotAnArrayException e ){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getObjectTypeName( char ) not throwing exception " );
+		System.out.println( " : ok" ) ;
+		// }}}
+		
+		// {{{ float
+		System.out.print( "  getObjectTypeName( float )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getObjectTypeName( 0.0f ) ;
+		} catch( NotAnArrayException e ){
+			ok = true; 
+		}
+		if( !ok ) throw new TestException( " getObjectTypeName( float ) not throwing exception " ) ;
+		System.out.println( " : ok" ) ;
+		// }}}
+
+		// }}}
+		
+		// {{{ null 
+		System.out.print( "  getObjectTypeName( null )" ) ;
+		ok = false; 
+		try{
+			RJavaArrayTools.getObjectTypeName( null ) ;
+		} catch( NullPointerException e ){
+			ok = true; 
+		} catch( NotAnArrayException e ){
+			throw new TestException("getObjectTypeName( null ) throwing wrong kind of exception") ; 
+		}
+		if( !ok ) throw new TestException( " getObjectTypeName( null ) not throwing exception " ) ;
+		System.out.println( " : ok" ) ;
+		
+		// }}}
+
+	}
+	// }}}
+	
+	// {{{ isPrimitiveTypeName
+	private static void isprim() throws TestException{
+		
+		System.out.print( " isPrimitiveTypeName( 'I' ) " ) ; if( !RJavaArrayTools.isPrimitiveTypeName("I") ) throw new TestException("I not primitive") ; System.out.println( " true : ok " );
+		System.out.print( " isPrimitiveTypeName( 'Z' ) " ) ; if( !RJavaArrayTools.isPrimitiveTypeName("Z") ) throw new TestException("Z not primitive") ; System.out.println( " true : ok " );
+		System.out.print( " isPrimitiveTypeName( 'B' ) " ) ; if( !RJavaArrayTools.isPrimitiveTypeName("B") ) throw new TestException("B not primitive") ; System.out.println( " true : ok " );
+		System.out.print( " isPrimitiveTypeName( 'J' ) " ) ; if( !RJavaArrayTools.isPrimitiveTypeName("J") ) throw new TestException("J not primitive") ; System.out.println( " true : ok " );
+		System.out.print( " isPrimitiveTypeName( 'S' ) " ) ; if( !RJavaArrayTools.isPrimitiveTypeName("S") ) throw new TestException("S not primitive") ; System.out.println( " true : ok " );
+		System.out.print( " isPrimitiveTypeName( 'D' ) " ) ; if( !RJavaArrayTools.isPrimitiveTypeName("D") ) throw new TestException("D not primitive") ; System.out.println( " true : ok " );
+		System.out.print( " isPrimitiveTypeName( 'C' ) " ) ; if( !RJavaArrayTools.isPrimitiveTypeName("C") ) throw new TestException("C not primitive") ; System.out.println( " true : ok " );
+		System.out.print( " isPrimitiveTypeName( 'F' ) " ) ; if( !RJavaArrayTools.isPrimitiveTypeName("F") ) throw new TestException("F not primitive") ; System.out.println( " true : ok " );
+		  
+		System.out.print( " isPrimitiveTypeName( 'java.lang.Object' ) " ) ;
+		if( RJavaArrayTools.isPrimitiveTypeName("java.lang.Object") ) throw new TestException("Object  primitive") ;
+		System.out.println( " false : ok " );
+	}
+	// }}}
+	
+	// {{{ rep
+	private static void rep() throws TestException{
+		DummyPoint p = new DummyPoint(10, 10) ;
+		
+		DummyPoint[] res = null;
+		System.out.print( "  rep( DummyPoint, 10)" ); 
+		try{
+			res = (DummyPoint[])RJavaArrayTools.rep( p, 10 );
+		} catch( Throwable e){
+			throw new TestException( "rep(DummyPoint, 10) failed" ) ;
+		}
+		if( res.length != 10 ){
+			throw new TestException( "rep(DummyPoint, 10).length != 10" ) ;
+		}
+		if( res[5].getX() != 10.0 ){
+			throw new TestException( "rep(DummyPoint, 10)[5].getX() != 10" ) ;
+		}
+		System.out.println( ": ok " );
+		
+	}
+	/// }}}
+		
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaClassLoader.java b/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaClassLoader.java
new file mode 100644
index 0000000000000000000000000000000000000000..16b6b5fb9e7fe710eab2562d94f5e8045e1924f9
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaClassLoader.java
@@ -0,0 +1,665 @@
+// :tabSize=4:indentSize=4:noTabs=false:folding=explicit:collapseFolds=1:
+
+// {{{ imports
+import java.io.*;
+import java.io.File;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.HashMap;
+import java.util.Vector;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.StringTokenizer;
+import java.util.zip.*;
+// }}}
+
+/**
+ * Class loader used internally by rJava
+ * 
+ * The class manages the class paths and the native libraries (jri, ...)
+ */
+public class RJavaClassLoader extends URLClassLoader {
+	
+	// {{{ fields 
+	/** 
+	 * path of RJava
+	 */
+	String rJavaPath ;
+	
+	/**
+	 * lib sub directory of rJava
+	 */
+	String rJavaLibPath;
+	
+	/**
+	 * map of libraries
+	 */
+	HashMap/*<String,UnixFile>*/ libMap;
+	
+	/**
+	 * The class path vector 
+	 */ 
+	Vector/*<UnixFile>*/ classPath;
+
+	/**
+	 * singleton
+	 */
+	public static RJavaClassLoader primaryLoader = null;
+
+	/**
+	 * Print debug messages if is set to <code>true</code>
+	 */
+	public static boolean verbose = false;
+
+	/**
+	 * Should the system class loader be used to resolve classes 
+	 * as well as this class loader
+	 */
+	public boolean useSystem = true;
+	// }}}
+
+	// {{{ UnixFile class
+	/**
+	 * Light extension of File that handles file separators and updates
+	 */
+	class UnixFile extends File {
+		
+		/**
+		 * cached "last time modified" stamp
+		 */ 
+		long lastModStamp;
+		
+		/** 
+		 * Constructor. Modifies the path so that 
+		 * the proper path separator is used (most useful on windows)
+		 */
+		public UnixFile(String fn) {
+			super( u2w(fn) ) ;
+			lastModStamp=0;
+		}
+		
+		/**
+		 * @return whether the file modified since last time the update method was called
+		 */
+		public boolean hasChanged() {
+			long curMod = lastModified();
+			return (curMod != lastModStamp);
+		}
+		
+		/**
+		 * Cache the result of the lastModified stamp
+		 */
+		public void update() {
+			lastModStamp = lastModified();
+		}
+	}
+	// }}}
+	
+	// {{{ UnixJarFile
+	/**
+	 * Specialization of UnixFile that deals with jar files
+	 */
+	class UnixJarFile extends UnixFile {
+		
+		/**
+		 * The cached jar file
+		 */
+		private ZipFile zfile ;
+		
+		/**
+		 * common prefix for all URLs within this jar file
+		 */
+		private String urlPrefix ;
+		
+		public UnixJarFile( String filename ){
+			super( filename );
+		}
+		
+		/* @Override */
+		public void update(){
+			try {
+				if (zfile != null){
+					zfile.close();
+				}
+				zfile = new ZipFile( this ) ;
+			} catch (Exception tryCloseX) {}
+
+			/* time stamp */
+			super.update( ) ; 
+		}
+		
+		/**
+		 * Get an input stream for a resource contained in the jar file
+		 * 
+		 * @param name file name of the resource within the jar file
+		 * @return an input stream representing the resouce if it exists or null
+		 */ 
+		public InputStream getResourceAsStream( String name ){
+			
+			if (zfile==null || hasChanged()) {
+				update(); 
+			}
+			try {
+				if (zfile == null) return null;
+				ZipEntry e = zfile.getEntry(name);
+				if (e != null)
+					return zfile.getInputStream(e);
+			} catch(Exception e) {
+				if (verbose) System.err.println("RJavaClassLoader$UnixJarFile: exception: "+e.getMessage());
+			}
+			return null;
+		}
+
+				
+		public URL getResource(String name ){
+			if( zfile == null  || zfile.getEntry( name ) == null ){
+				return null ;
+			}
+			
+			URL u = null ; 
+			if( urlPrefix == null ){
+				try{
+					urlPrefix = "jar:" + toURL().toString() + "!" ;
+				} catch( java.net.MalformedURLException ex){
+				} catch( java.io.IOException ex){
+				}
+			}
+			
+			try{
+				u = new URL( urlPrefix + name ) ;
+			} catch( java.net.MalformedURLException ex ){
+				/* not to worry */
+			}
+			return u ;
+		}
+		
+	}
+	// }}}
+	
+	// {{{ UnixDirectory class
+	/**
+	 * Specialization of UnixFile representing a directory
+	 */ 
+	/* it is not really a specialization but makes possible to dispatch on instanceof*/
+	class UnixDirectory extends UnixFile {
+		public UnixDirectory( String dirname ){
+			super( dirname ) ;
+		}
+	}
+	// }}}	
+	
+	
+	// {{{ getPrimaryLoader
+	/**
+	 * Returns the singleton instance of RJavaClassLoader
+	 */ 
+	public static RJavaClassLoader getPrimaryLoader() {
+		return primaryLoader;
+	}
+	// }}}
+
+	// {{{ constructor
+	/**
+	 * Constructor. The first time an RJavaClassLoader is created, it is
+	 * cached as the primary loader. 
+	 *
+	 * @param path path of the rJava package
+	 * @param libpath lib sub directory of the rJava package
+	 */
+	public RJavaClassLoader(String path, String libpath) {
+		super(new URL[] {});
+		// respect rJava.debug level
+		String rjd = System.getProperty("rJava.debug");
+		if (rjd != null && rjd.length() > 0 && !rjd.equals("0")) verbose = true;
+		if (verbose) System.out.println("RJavaClassLoader(\""+path+"\",\""+libpath+"\")");
+		if (primaryLoader==null) {
+			primaryLoader = this;
+			if (verbose) System.out.println(" - primary loader");
+		} else {
+			if (verbose) System.out.println(" - NOT primrary (this="+this+", primary="+primaryLoader+")");
+		}
+		libMap = new HashMap/*<String,UnixFile>*/();
+		
+		classPath = new Vector/*<UnixFile>*/();
+		classPath.add(new UnixDirectory(path+"/java"));
+		
+		rJavaPath = path;
+		rJavaLibPath = libpath;
+		
+		/* load the rJava library */
+		UnixFile so = new UnixFile(rJavaLibPath+"/rJava.so");
+		if (!so.exists())
+			so = new UnixFile(rJavaLibPath+"/rJava.dll");
+		if (so.exists())
+			libMap.put("rJava", so);
+
+		/* load the jri library */
+		UnixFile jri = new UnixFile(path+"/jri/libjri.so");
+		String rarch = System.getProperty("r.arch");
+		if (rarch != null && rarch.length()>0) {
+			UnixFile af = new UnixFile(path+"/jri"+rarch+"/libjri.so");
+			if (af.exists())
+			    jri = af;
+			else {
+			    af = new UnixFile(path+"/jri"+rarch+"/jri.dll");
+			    if (af.exists())
+				jri = af;
+			}			
+		}
+		if (!jri.exists())
+			jri = new UnixFile(path+"/jri/libjri.jnilib");
+		if (!jri.exists())
+			jri = new UnixFile(path+"/jri/jri.dll");
+		if (jri.exists()) {
+			libMap.put("jri", jri);
+			if (verbose) System.out.println(" - registered JRI: "+jri);
+		}
+
+		/* if we are the primary loader, make us the context loader so
+		   projects that rely on the context loader pick us */
+		if (primaryLoader == this)
+			Thread.currentThread().setContextClassLoader(this);
+
+		if (verbose) {
+		    System.out.println("RJavaClassLoader initialized.\n\nRegistered libraries:");
+		    for(Iterator entries = libMap.keySet().iterator(); entries.hasNext(); ) {
+			Object key = entries.next(); System.out.println("  " + key + ": '" + libMap.get(key) + "'");
+		    }
+		    System.out.println("\nRegistered class paths:");
+		    for (Enumeration e = classPath.elements() ; e.hasMoreElements() ;)
+			System.out.println("  '"+e.nextElement()+"'");
+		    System.out.println("\n-- end of class loader report --");
+		}
+	}
+	// }}}
+
+	// {{{ classNameToFile
+	/**
+	 * convert . to /
+	 */ 
+	String classNameToFile(String cls) {
+		return cls.replace('.','/');
+	}
+	// }}}
+
+	// {{{ findClass
+	protected Class findClass(String name) throws ClassNotFoundException {
+		Class cl = null;
+		if (verbose) System.out.println(""+this+".findClass("+name+")");
+		if ("RJavaClassLoader".equals(name)) return getClass();
+		
+		// {{{ use the usual method of URLClassLoader
+		if (useSystem) {
+			try {
+				cl = super.findClass(name);
+				if (cl != null) {
+					if (verbose) System.out.println("RJavaClassLoader: found class "+name+" using URL loader");
+					return cl;
+				}
+			} catch (Exception fnf) {
+			    if (verbose) System.out.println(" - URL loader did not find it: " + fnf);
+			}	    
+		}
+		if (verbose) System.out.println("RJavaClassLoader.findClass(\""+name+"\")");
+		// }}}
+
+		// {{{ iterate through the elements of the class path
+		InputStream ins = null;
+		Exception defineException = null;
+		Enumeration/*<UnixFile>*/ e = classPath.elements() ;
+		while( e.hasMoreElements() ){
+			UnixFile cp = (UnixFile) e.nextElement();
+
+			if (verbose) System.out.println(" - trying class path \""+cp+"\"");
+			try {
+				ins = null;
+				/* a file - assume it is a jar file */
+				if (cp instanceof UnixJarFile){
+					ins = ((UnixJarFile)cp).getResourceAsStream( classNameToFile(name) + ".class" ) ;
+					if (verbose) System.out.println("   JAR file, can get '" + classNameToFile(name) + "'? " + ((ins == null) ? "NO" : "YES"));
+				} else if ( cp instanceof UnixDirectory ){
+					UnixFile class_f = new UnixFile(cp.getPath()+"/"+classNameToFile(name)+".class");
+					if (class_f.isFile() ) {
+						ins = new FileInputStream(class_f);
+					}
+					if (verbose) System.out.println("   Directory, can get '" + class_f + "'? " + ((ins == null) ? "NO" : "YES"));
+				}
+				
+				/* some comments on the following :
+					
+				   we could call ZipEntry.getSize in case of a jar file to 
+				   find out the size of the byte[] directly
+				   
+				   also ByteBuffer seems more efficient, but the ByteBuffer class
+				   is java >= 1.4 and the defineClass method that uses the class
+				   is java >= 1.5
+				*/
+				
+				if (ins != null) {
+					int al = 128*1024;
+					byte fc[] = new byte[al];
+					int n = ins.read(fc);
+					int rp = n;
+					if( verbose ) System.out.println("  loading class file, initial n = "+n);
+					while (n > 0) {
+						if (rp == al) {
+							int nexa = al*2;
+							if (nexa<512*1024) nexa=512*1024;
+							byte la[] = new byte[nexa];
+							System.arraycopy(fc, 0, la, 0, al);
+							fc = la;
+							al = nexa;
+						}
+						n = ins.read(fc, rp, fc.length-rp);
+						if( verbose ) System.out.println("  next n = "+n+" (rp="+rp+", al="+al+")");
+						if (n>0) rp += n;
+					}
+					ins.close();
+					n = rp;
+					if (verbose) System.out.println("RJavaClassLoader: loaded class "+name+", "+n+" bytes");
+					try {
+					    cl = defineClass(name, fc, 0, n);
+					} catch (Exception dce) {
+					    // we want to save this one so we can pass it on
+					    defineException = dce;
+					    break;
+					}
+					if (verbose) System.out.println("  defineClass('" + name +"') returned " + cl);
+					// System.out.println(" - class = "+cl);
+					return cl;
+				}
+			} catch (Exception ex) {
+				// System.out.println(" * won't work: "+ex.getMessage());
+			}
+		}
+		// }}}
+		
+		if (defineException != null) // we bailed out on class interpretation, re-throw it
+		    throw (new ClassNotFoundException("Class not found - candidate class binary found but could not be loaded", defineException));
+
+		// giving up
+		if( verbose ) System.out.println("    >> ClassNotFoundException ");
+		if (cl == null) {
+			throw (new ClassNotFoundException());
+		}
+		return cl;
+	}
+	// }}}
+
+	// {{{ findResource 
+	public URL findResource(String name) {
+		if (verbose) System.out.println("RJavaClassLoader: findResource('"+name+"')");
+		
+		// {{{ use the standard way
+		if (useSystem) {
+			try {
+				URL u = super.findResource(name);
+				if (u != null) {
+					if (verbose) System.out.println("RJavaClassLoader: found resource in "+u+" using URL loader.");
+					return u;
+				}
+			} catch (Exception fre) {
+			}
+		}
+		// }}}
+		
+		// {{{ iterate through the classpath
+		if (verbose) System.out.println(" - resource not found with URL loader, trying alternative");
+		Enumeration/*<UnixFile>*/ e = classPath.elements() ;
+		while( e.hasMoreElements()) {
+			UnixFile cp = (UnixFile) e.nextElement();
+
+			try {
+				/* is a file - assume it is a jar file */
+				if (cp instanceof UnixJarFile ) {
+					URL u = ( (UnixJarFile)cp ).getResource( name ) ;
+					if (u != null) {
+						if (verbose) System.out.println(" - found in a JAR file, URL "+u);
+						return u;
+					}
+				} else if(cp instanceof UnixDirectory ) {
+					UnixFile res_f = new UnixFile(cp.getPath()+"/"+name);
+					if (res_f.isFile()) {
+						if (verbose) System.out.println(" - find as a file: "+res_f);
+						return res_f.toURL();
+					}
+				}
+			} catch (Exception iox) {
+			}
+		}
+		// }}}
+		return null;
+	}
+	// }}}
+
+	// {{{ addRLibrary
+	/** add a library to path mapping for a native library */
+	public void addRLibrary(String name, String path) {
+		libMap.put(name, new UnixFile(path));
+	}
+	// }}}
+
+	// {{{ addClassPath
+	/** 
+	 * adds an entry to the class path
+	 */ 
+	public void addClassPath(String cp) {
+		UnixFile f = new UnixFile(cp);
+		
+		// use the URLClassLoader
+		if (useSystem) {
+			try {
+				addURL(f.toURL());
+				if (verbose) System.out.println("RJavaClassLoader: added '" + cp + "' to the URL class path loader");
+				//return; // we need to add it anyway so it appears in .jclassPath()
+			} catch (Exception ufe) {
+			}
+		}
+		
+		UnixFile g = null ;
+		if( f.isFile() && (f.getName().endsWith(".jar") || f.getName().endsWith(".JAR"))) {
+			g = new UnixJarFile(cp) ;
+			if (verbose) System.out.println("RJavaClassLoader: adding Java archive file '"+cp+"' to the internal class path");
+		} else if( f.isDirectory() ){
+			g = new UnixDirectory(cp) ;
+			if (verbose) System.out.println("RJavaClassLoader: adding class directory '"+cp+"' to the internal class path");
+		} else if (verbose)
+		    System.err.println(f.exists() ?
+				       ("WARNING: the path '"+cp+"' is neither a directory nor a .jar file, it will NOT be added to the internal class path!") :
+				       ("WARNING: the path '"+cp+"' does NOT exist, it will NOT be added to the internal class path!"));
+		
+		if (g != null && !classPath.contains(g)) {
+			// this is the real meat - add it to our internal list
+			classPath.add(g);
+			// this is just cosmetics - it doesn't really have any meaning
+			System.setProperty("java.class.path",
+					System.getProperty("java.class.path")+File.pathSeparator+g.getPath());
+		}
+	}
+	
+	/** 
+	 * adds several entries to the class path
+	 */
+	public void addClassPath(String[] cp) {
+		int i = 0;
+		while (i < cp.length) addClassPath(cp[i++]);
+	}
+	// }}}
+
+	// {{{ getClassPath
+	/**
+	 * @return the array of class paths used by this class loader
+	 */
+	public String[] getClassPath() {
+		int j = classPath.size();
+		String[] s = new String[j];
+		int i = 0;
+		while (i < j) {
+			s[i] = ((UnixFile) classPath.elementAt(i)).getPath();
+			i++;
+		}
+		return s;
+	}
+	// }}}
+	
+	// {{{ findLibrary
+	protected String findLibrary(String name) {
+		if (verbose) System.out.println("RJavaClassLoader.findLibrary(\""+name+"\")");
+		//if (name.equals("rJava"))
+		//    return rJavaLibPath+"/"+name+".so";
+
+		UnixFile u = (UnixFile) libMap.get(name);
+		String s = null;
+		if (u!=null && u.exists()) s=u.getPath();
+		if (verbose) System.out.println(" - mapping to "+((s==null)?"<none>":s));
+
+		return s;
+	}
+	// }}}
+
+	// {{{ bootClass
+	/**
+	 * Boots the specified method of the specified class
+	 * 
+	 * @param cName class to boot
+	 * @param mName method to boot (typically main). The method must take a String[] as parameter
+	 * @param args arguments to pass to the method
+	 */
+	public void bootClass(String cName, String mName, String[] args) throws java.lang.IllegalAccessException, java.lang.reflect.InvocationTargetException, java.lang.NoSuchMethodException, java.lang.ClassNotFoundException {
+		Class c = findClass(cName);
+		resolveClass(c);
+		java.lang.reflect.Method m = c.getMethod(mName, new Class[] { String[].class });
+		m.invoke(null, new Object[] { args });
+	}
+	// }}}
+
+	// {{{ setDebug
+	/**
+	 * Set the debug level. At the moment, there is only verbose (level &gt; 0)
+	 * or quiet
+	 *
+	 * @param level debug level. verbose (&gt;0), quiet otherwise
+	 */
+	public static void setDebug(int level) {
+		verbose=(level>0);
+	}
+	// }}}
+
+	// {{{ u2w
+	/** 
+	 * Utility to convert paths for windows. Converts / to the path separator in use
+	 * 
+	 * @param fn file name
+	 */
+	public static String u2w(String fn) {
+		return (File.separatorChar != '/') ? fn.replace('/', File.separatorChar) : fn ;
+	}
+	// }}}
+
+	// {{{ main
+	/**
+	 * main method
+	 * 
+	 * <p>This uses the system properties: 
+	 * <ul>
+	 * <li><code>rjava.path</code> : path of the rJava package</li>
+	 * <li><code>rjava.lib</code>  : lib sub directory of the rJava package</li>
+	 * <li><code>main.class</code> : main class to "boot", assumes Main if not specified</li>
+	 * <li><code>rjava.class.path</code> : set of paths to populate the initiate the class path</li>
+	 * </ul>
+	 * </p>
+	 *
+	 * <p>and boots the "main" method of the specified <code>main.class</code>, 
+	 * passing the args down to the booted class</p>
+	 *
+	 * <p>This makes sure R and rJava are known by the class loader</p>
+	 */
+	public static void main(String[] args) {
+		String rJavaPath = System.getProperty("rjava.path");
+		if (rJavaPath  == null) {
+			System.err.println("ERROR: rjava.path is not set");
+			System.exit(2);
+		}
+		String rJavaLib = System.getProperty("rjava.lib");
+		if (rJavaLib == null) { // it is not really used so far, just for rJava.so, so we can guess
+			rJavaLib = rJavaPath + File.separator + "libs";
+		}
+		RJavaClassLoader cl = new RJavaClassLoader(u2w(rJavaPath), u2w(rJavaLib));
+		String mainClass = System.getProperty("main.class");
+		if (mainClass == null || mainClass.length()<1) {
+			System.err.println("WARNING: main.class not specified, assuming 'Main'");
+			mainClass = "Main";
+		}
+		String classPath = System.getProperty("rjava.class.path");
+		if (classPath != null) {
+			StringTokenizer st = new StringTokenizer(classPath, File.pathSeparator);
+			while (st.hasMoreTokens()) {
+				String dirname = u2w(st.nextToken());
+				cl.addClassPath(dirname);
+			}
+		}
+		try {
+			cl.bootClass(mainClass, "main", args);
+		} catch (Exception ex) { 
+			System.err.println("ERROR: while running main method: "+ex);
+			ex.printStackTrace();
+		}
+	}
+	// }}}
+
+	//----- tools -----
+	
+	// {{{ RJavaObjectInputStream class
+	class RJavaObjectInputStream extends ObjectInputStream {
+		public RJavaObjectInputStream(InputStream in) throws IOException {
+			super(in);
+		}
+		protected Class resolveClass(ObjectStreamClass desc) throws ClassNotFoundException {
+			return Class.forName(desc.getName(), false, RJavaClassLoader.getPrimaryLoader());
+		}
+	}
+	// }}}
+
+	// {{{ toByte
+	/** 
+	 * Serialize an object to a byte array. (code by CB)
+	 *
+	 * @param object object to serialize
+	 * @return byte array that represents the object
+	 * @throws Exception 
+	 */
+	public static byte[] toByte(Object object) throws Exception {
+		ByteArrayOutputStream os = new ByteArrayOutputStream();
+		ObjectOutputStream   oos = new ObjectOutputStream((OutputStream) os);
+		oos.writeObject(object);
+		oos.close();
+		return os.toByteArray();
+	}
+	// }}}
+
+	// {{{ toObject
+	/** 
+	 * Deserialize an object from a byte array. (code by CB)
+	 *
+	 * @param byteArray
+	 * @return the object that is represented by the byte array
+	 * @throws Exception 
+	 */
+	public Object toObject(byte[] byteArray) throws Exception {
+		InputStream        is = new ByteArrayInputStream(byteArray);
+		RJavaObjectInputStream ois = new RJavaObjectInputStream(is);
+		Object o = (Object) ois.readObject();
+		ois.close();
+		return o;
+	}
+	// }}}
+
+	// {{{ toObjectPL
+	/**
+	 * converts the byte array into an Object using the primary RJavaClassLoader
+	 */
+	public static Object toObjectPL(byte[] byteArray) throws Exception{
+		return RJavaClassLoader.getPrimaryLoader().toObject(byteArray);
+	}
+	// }}}
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaComparator.java b/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaComparator.java
new file mode 100644
index 0000000000000000000000000000000000000000..30e3f14f23ad4b6fdcb54bbc64a3487d0b4e3981
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaComparator.java
@@ -0,0 +1,52 @@
+import java.lang.Comparable ; 
+
+/**
+ * Utility class to compare two objects in the sense
+ * of the java.lang.Comparable interface
+ *
+ */
+public class RJavaComparator {
+	           
+	/**
+	 * compares a and b in the sense of the java.lang.Comparable if possible
+	 *
+	 * <p>instances of the Number interface are treated specially, in order to 
+	 * allow comparing Numbers of different classes, for example it is allowed 
+	 * to compare a Double with an Integer. if the Numbers have the same class,
+	 * they are compared normally, otherwise they are first converted to Doubles
+	 * and then compared</p>
+	 * 
+	 * @param a an object
+	 * @param b another object 
+	 * 
+	 * @return the result of <code>a.compareTo(b)</code> if this makes sense
+	 * @throws NotComparableException if the two objects are not comparable
+	 */
+	public static int compare( Object a, Object b ) throws NotComparableException{
+		int res ; 
+		if( a.equals( b ) ) return 0 ;
+		
+		// treat Number s separately
+		if( a instanceof Number && b instanceof Number && !( a.getClass() == b.getClass() ) ){
+			Double _a = new Double( ((Number)a).doubleValue() );
+			Double _b = new Double( ((Number)b).doubleValue() );
+			return _a.compareTo( _b ); 
+		}
+		
+		if( ! ( a instanceof Comparable ) ) throw new NotComparableException( a ); 
+		if( ! ( b instanceof Comparable ) ) throw new NotComparableException( b ); 
+		
+		try{
+			res = ( (Comparable)a ).compareTo( b ) ; 
+		} catch( ClassCastException e){
+			try{
+				res = - ((Comparable)b).compareTo( a ) ;
+			} catch( ClassCastException f){
+				throw new NotComparableException( a, b ); 
+			}
+		}
+		return res ;
+	}
+	
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaImport.java b/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaImport.java
new file mode 100644
index 0000000000000000000000000000000000000000..85984861dbf50981adb9db34dee858e22a9c5de7
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaImport.java
@@ -0,0 +1,172 @@
+
+import java.util.regex.Pattern ;
+import java.util.regex.Matcher ;
+
+import java.util.Vector; 
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Collection;
+import java.util.Set ;
+import java.util.Iterator ;
+
+import java.io.Serializable; 
+
+/**
+ * Utilities to manage java packages and how they are "imported" to R
+ * databases. This is the back door of the <code>javaImport</code>
+ * system in the R side
+ *
+ * @author Romain Francois &lt;francoisromain@free.fr&gt;
+ */
+public class RJavaImport implements Serializable {
+
+	/**
+	 * Debug flag. Prints some messages if it is set to TRUE
+	 */
+	public static boolean DEBUG = false ; 
+	
+	/** 
+	 * list of imported packages
+	 */
+	/* TODO: vector is not good enough, we need to control the order
+	         in which the packages appear */
+	private Vector/*<String>*/ importedPackages ;
+	
+	/**
+	 * maps a simple name to a fully qualified name
+	 */
+	/* String -> java.lang.String */
+  /* should we cache the Class instead ? */
+	private Map/*<String,String>*/ cache ;
+	
+	/**
+	 * associated class loader
+	 */
+	public ClassLoader loader ;
+	
+	/**
+	 * Constructor. Initializes the imported package vector and the cache
+	 */ 
+	public RJavaImport( ClassLoader loader ){
+	    this.loader = loader ;
+		importedPackages = new Vector/*<String>*/(); 
+		cache = new HashMap/*<String,String>*/() ;
+	}
+	
+	/**
+	 * Look for the class in the set of packages
+	 *
+	 * @param clazz the simple class name
+	 * 
+	 * @return an instance of Class representing the actual class
+	 */
+	public Class lookup( String clazz){
+		Class res = lookup_(clazz) ;
+		if( DEBUG ) System.out.println( "  [J] lookup( '" + clazz + "' ) = " + (res == null ? " " : ("'" + res.getName() + "'" ) ) ) ;
+		return res ;
+	}
+
+	private Class lookup_( String clazz ){
+		Class res = null ;
+		
+		if( cache.containsKey( clazz ) ){
+			try{
+				String fullname = (String)cache.get( clazz ) ;
+				Class cl = Class.forName( fullname ) ; 
+				return cl ;
+			} catch( Exception e ){
+				/* does not happen */
+			}
+		}
+		
+		/* first try to see if the class does not exist verbatim */
+		try{
+			res = Class.forName( clazz ) ;
+		} catch( Exception e){}
+		if( res != null ) {
+			cache.put( clazz, clazz ) ;
+			return res;
+		}
+		
+		int npacks = importedPackages.size() ;
+		if( DEBUG ) System.out.println( "    [J] " + npacks + " packages" ) ;
+		if( npacks > 0 ){
+			for( int i=0; i<npacks; i++){
+				try{
+				    String p = (String)importedPackages.get(i); 
+				    String candidate = p + "." + clazz ;
+				    if( DEBUG ) System.out.println( "    [J] trying class : " + candidate ) ;
+					res = Class.forName( candidate ) ;
+				} catch( Exception e){
+				    if( DEBUG ) System.out.println( "   [JE] " + e.getMessage() );
+				}
+				if( res != null ){
+					cache.put( clazz, res.getName() ) ;
+					return res ; 
+				}
+			}
+		}
+		return null ;
+	}
+	
+	/**
+	 * @return true if the class is known
+	 */
+	public boolean exists( String clazz){
+		boolean res = exists_(clazz) ;
+		if( DEBUG ) System.out.println( "  [J] exists( '" + clazz + "' ) = " + res ) ;
+		return res ;
+	}
+
+	public boolean exists_( String clazz ){
+		if( cache.containsKey( clazz ) ) return true ;
+		
+		return ( lookup_( clazz ) != null );
+	}
+	
+	/**
+	 * Adds a package to the list of "imported" packages
+	 *
+	 * @param packageName package path name
+	 */
+  public void importPackage( String packageName ){
+  	importedPackages.add( packageName ) ; 
+  }
+	
+  /**
+   * Adds a set of packages
+   *
+   * @param packages package path names
+   */
+  public void importPackage( String[] packages ){
+  	for( int i=0; i<packages.length; i++){
+  		importPackage( packages[i] ) ;
+  	}
+  }
+  
+  /**
+   * @return the simple names of the classes currently known
+   * by this importer
+   */
+  public String[] getKnownClasses(){
+  	Set/*<String>*/ set = cache.keySet() ; 
+  	int size = set.size() ;
+  	String[] res = new String[size];
+  	set.toArray( res );
+  	if( DEBUG ) System.out.println( "  [J] getKnownClasses().length = "  + res.length ) ;
+  	return res ;
+  }
+  
+  public static Class lookup( String clazz , Set importers ){
+  	Class res  ;
+  	Iterator iterator = importers.iterator() ;
+  	while( iterator.hasNext()){
+  		RJavaImport importer = (RJavaImport)iterator.next() ;
+  		res = importer.lookup( clazz ) ;
+  		if( res != null ) return res ;
+  	}
+  	return null ;
+  }
+  
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaTools.java b/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaTools.java
new file mode 100644
index 0000000000000000000000000000000000000000..f6f3424a858f484f2c417ccc09fe56398c28be34
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaTools.java
@@ -0,0 +1,737 @@
+// RJavaTools.java: rJava - low level R to java interface
+//
+// Copyright (C) 2009 - 2010	Simon Urbanek and Romain Francois
+//
+// This file is part of rJava.
+//
+// rJava 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.
+//
+// rJava 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 rJava.  If not, see <http://www.gnu.org/licenses/>.
+
+import java.lang.reflect.Method ;
+import java.lang.reflect.Field ;
+import java.lang.reflect.Constructor ;
+import java.lang.reflect.InvocationTargetException ;
+import java.lang.reflect.Modifier ;
+import java.lang.reflect.Member ;
+
+import java.util.Vector ;
+
+
+/** 
+ * Tools used internally by rJava.
+ * 
+ * The method lookup code is heavily based on ReflectionTools 
+ * by Romain Francois &lt;francoisromain@free.fr&gt; licensed under GPL v2 or higher.
+ */
+public class RJavaTools {
+	
+	/**
+	 * Returns an inner class of the class with the given simple name
+	 * 
+	 * @param cl class
+	 * @param name simple name of the inner class
+	 * @param staticRequired boolean, if <code>true</code> the inner class is required to be static
+	 */
+	public static Class getClass(Class cl, String name, boolean staticRequired){
+		Class[] clazzes = cl.getClasses(); 
+		for( int i=0; i<clazzes.length; i++){
+			if( getSimpleName( clazzes[i].getName() ).equals( name ) && ( !staticRequired || isStatic(clazzes[i]) ) ){
+				return clazzes[i] ;
+			}
+		}
+		return null; 
+	}
+	
+	
+	/**
+	 * Returns the static inner classes of the class
+	 * 
+	 * @param cl class
+	 * @return an array of classes or null if cl does not have static inner classes
+	 */
+	public static Class[] getStaticClasses(Class cl){
+		 Class[] clazzes = cl.getClasses(); 
+		 if( clazzes == null ) return null; 
+		 
+		 Vector vec = new Vector() ;
+		 int n = clazzes.length; 
+		 for( int i=0; i<n; i++){
+			Class clazz = clazzes[i] ;
+			if( isStatic( clazz ) ){
+				vec.add( clazz ) ; 
+			}
+		}
+		if( vec.size() == 0 ){
+			return null ;
+		}
+		Class[] out = new Class[ vec.size() ] ;
+		vec.toArray( out ) ; 
+		return out ; 
+	}
+	
+	/**
+	 * Indicates if a class is static
+	 * 
+	 * @param clazz class
+	 * @return true if the class is static
+	 */
+	public static boolean isStatic( Class clazz ){
+		return (clazz.getModifiers() & Modifier.STATIC) != 0  ;
+	}
+	
+	/**
+	 * Returns the static fields of the class
+	 *
+	 * @param cl class 
+	 * @return an array of static fields
+	 */
+	public static Field[] getStaticFields( Class cl ){
+		Field[] members = cl.getFields() ;
+		if( members.length == 0 ){
+			return null;  
+		}
+		Vector vec = new Vector() ;
+		int n = members.length ; 
+		for( int i=0; i<n; i++){
+			Field memb = members[i] ;
+			if( isStatic( memb ) ){
+				vec.add( memb ) ; 
+			}
+		}
+		if( vec.size() == 0 ){
+			return null ;
+		}
+		Field[] out = new Field[ vec.size() ] ;
+		vec.toArray( out ) ; 
+		return out ; 
+	}
+	
+	/**
+	 * Returns the static methods of the class
+	 *
+	 * @param cl class 
+	 * @return an array of static fields
+	 */
+	public static Method[] getStaticMethods( Class cl ){
+		Method[] members = cl.getMethods() ;
+		Vector vec = new Vector() ;
+		if( members.length == 0 ){
+			return null;  
+		}
+		int n = members.length ; 
+		for( int i=0; i<n; i++){
+			Method memb = members[i] ;
+			if( isStatic( memb ) ){
+				vec.add( memb ) ; 
+			}
+		}
+		if( vec.size() == 0 ){
+			return null ;
+		}
+		Method[] out = new Method[ vec.size() ] ;
+		vec.toArray( out ) ; 
+		return out ; 
+	}
+	
+	
+	/**
+	 * Returns the names of the fields of a given class
+	 *
+	 * @param cl class 
+	 * @param staticRequired if true only static fields are returned
+	 * @return the public (and maybe only static) names of the fields. 
+	 */
+	public static String[] getFieldNames( Class cl, boolean staticRequired ){
+		return getMemberNames( cl.getFields(), staticRequired ) ; 
+	}
+	
+	/**
+	 * Returns the completion names of the methods of a given class. 
+	 * See the getMethodCompletionName method below
+	 *
+	 * @param cl class 
+	 * @param staticRequired if true only static methods are returned
+	 * @return the public (and maybe only static) names of the methods. 
+	 */
+	public static String[] getMethodNames( Class cl, boolean staticRequired ){
+		return getMemberNames( cl.getMethods(), staticRequired ) ;
+	}
+	
+	private static String[] getMemberNames(Member[] members, boolean staticRequired){
+		String[] result = null ;
+		int nm = members.length ;
+		if( nm == 0 ){
+			return new String[0] ;
+		}
+		if( staticRequired ){
+			Vector names = new Vector();
+			for( int i=0; i<nm; i++ ){
+				Member member = members[i] ; 
+				if( isStatic( member ) ){
+					names.add( getCompletionName(member) ) ; 
+				}
+			}
+			if( names.size() == 0 ){
+				return new String[0] ;
+			}
+			result = new String[ names.size() ] ;
+		  names.toArray( result ) ; 
+		} else{ 
+			/* don't need the vector */
+			result = new String[nm] ;
+			for( int i=0; i<nm; i++ ){
+				result[i] = getCompletionName( members[i] ) ;
+			}
+		}
+		return  result; 
+	}
+	
+	/**
+	 * Completion name of a member. 
+	 * 
+	 * <p>For fields, it just returns the name of the fields
+	 *
+	 * <p>For methods, this returns the name of the method
+	 * plus a suffix that depends on the number of arguments of the method.
+	 * 
+	 * <p>The string "()" is added 
+	 * if the method has no arguments, and the string "(" is added
+	 * if the method has one or more arguments.
+	 */
+	public static String getCompletionName(Member m){
+		if( m instanceof Field ) return m.getName();
+		if( m instanceof Method ){
+			String suffix = ( ((Method)m).getParameterTypes().length == 0 ) ? ")" : "" ;
+			return m.getName() + "(" + suffix ;
+		}
+		return "" ;
+	}
+	 
+	/**
+	 * Indicates if a member of a Class (field, method ) is static
+	 * 
+	 * @param member class member
+	 * @return true if the member is static
+	 */
+	public static boolean isStatic( Member member ){
+		return (member.getModifiers() & Modifier.STATIC) != 0  ;
+	}
+	
+	/**
+	 * Checks if the class of the object has the given field. The 
+	 * getFields method of Class is used so only public fields are 
+	 * checked
+	 *
+	 * @param o object
+	 * @param name name of the field
+	 *
+	 * @return <code>true</code> if the class of <code>o</code> has the field <code>name</code>
+	 */
+	public static boolean hasField(Object o, String name) {
+		return classHasField(o.getClass(), name, false);
+	}
+	
+	/**
+	 * Checks if the class of the object has the given inner class. The 
+	 * getClasses method of Class is used so only public classes are 
+	 * checked
+	 *
+	 * @param o object
+	 * @param name (simple) name of the inner class
+	 *
+	 * @return <code>true</code> if the class of <code>o</code> has the class <code>name</code>
+	 */
+	public static boolean hasClass(Object o, String name) {
+		return classHasClass(o.getClass(), name, false);
+	}
+	
+	
+	/**
+	 * Checks if the specified class has the given field. The 
+	 * getFields method of Class is used so only public fields are 
+	 * checked
+	 *
+	 * @param cl class object
+	 * @param name name of the field
+	 * @param staticRequired if <code>true</code> then the field is required to be static
+	 *
+	 * @return <code>true</code> if the class <code>cl</code> has the field <code>name</code>
+	 */
+	public static boolean classHasField(Class cl, String name, boolean staticRequired) {
+		Field[] fields = cl.getFields();
+		for (int i = 0; i < fields.length; i++)
+			if(name.equals(fields[i].getName()) && (!staticRequired || ((fields[i].getModifiers() & Modifier.STATIC) != 0)))
+				return true; 
+		return false;
+	}
+	
+	
+	/**
+	 * Checks if the specified class has the given method. The 
+	 * getMethods method of Class is used so only public methods are 
+	 * checked
+	 *
+	 * @param cl class
+	 * @param name name of the method
+	 * @param staticRequired if <code>true</code> then the method is required to be static
+	 *
+	 * @return <code>true</code> if the class <code>cl</code> has the method <code>name</code>
+	 */
+	public static boolean classHasMethod(Class cl, String name, boolean staticRequired) {
+		Method[] methodz = cl.getMethods();
+		for (int i = 0; i < methodz.length; i++)
+			if (name.equals(methodz[i].getName()) && (!staticRequired || ((methodz[i].getModifiers() & Modifier.STATIC) != 0)))
+				return true;
+		return false;
+	}
+	
+	/**
+	 * Checks if the specified class has the given inner class. The 
+	 * getClasses method of Class is used so only public classes are 
+	 * checked
+	 *
+	 * @param cl class
+	 * @param name name of the inner class
+	 * @param staticRequired if <code>true</code> then the method is required to be static
+	 *
+	 * @return <code>true</code> if the class <code>cl</code> has the field <code>name</code>
+	 */
+	public static boolean classHasClass(Class cl, String name, boolean staticRequired) {
+		Class[] clazzes = cl.getClasses();
+		for (int i = 0; i < clazzes.length; i++)
+			if (name.equals( getSimpleName(clazzes[i].getName()) ) && (!staticRequired || isStatic( clazzes[i] ) ) )
+				return true;
+		return false;
+	}
+	
+	/**
+	 * Checks if the class of the object has the given method. The 
+	 * getMethods method of Class is used so only public methods are 
+	 * checked
+	 *
+	 * @param o object
+	 * @param name name of the method
+	 *
+	 * @return <code>true</code> if the class of <code>o</code> has the field <code>name</code>
+	 */
+	public static boolean hasMethod(Object o, String name) {
+		return classHasMethod(o.getClass(), name, false); 
+	}
+	
+	
+	
+	/**
+	 * Object creator. Find the best constructor based on the parameter classes
+	 * and invoke newInstance on the resolved constructor
+	 */
+	public static Object newInstance( Class o_clazz, Object[] args, Class[] clazzes ) throws Throwable {
+		
+		boolean[] is_null = new boolean[args.length];
+		for( int i=0; i<args.length; i++) {
+			is_null[i] = ( args[i] == null ) ;
+		}
+		
+		Constructor cons = getConstructor( o_clazz, clazzes, is_null );
+		
+		/* enforcing accessibility (workaround for bug 128) */
+		boolean access = cons.isAccessible(); 
+		cons.setAccessible( true ); 
+		
+		Object o; 
+		try{
+			o = cons.newInstance( args ) ; 
+		} catch( InvocationTargetException e){
+			/* the target exception is much more useful than the reflection wrapper */
+			throw e.getTargetException() ;
+		} finally{
+			cons.setAccessible( access ); 
+		}
+		return o;                                 
+	}
+	
+	static boolean[] arg_is_null(Object[] args){
+		if( args == null ) return null ;
+		boolean[] is_null = new boolean[args.length];
+		for( int i=0; i<args.length; i++) {
+			is_null[i] = ( args[i] == null ) ;
+		}
+		return is_null ;
+	}
+	
+	/**
+	 * Invoke a method of a given class
+	 * <p>First the appropriate method is resolved by getMethod and
+	 * then invokes the method
+	 */
+	public static Object invokeMethod( Class o_clazz, Object o, String name, Object[] args, Class[] clazzes) throws Throwable {
+		
+		Method m = getMethod( o_clazz, name, clazzes, arg_is_null(args) );
+		
+		/* enforcing accessibility (workaround for bug 128) */
+		boolean access = m.isAccessible(); 
+		m.setAccessible( true ); 
+		
+		Object out; 
+		try{
+			out = m.invoke( o, args ) ; 
+		} catch( InvocationTargetException e){
+			/* the target exception is much more useful than the reflection wrapper */
+			throw e.getTargetException() ;
+		} finally{
+			m.setAccessible( access ); 
+		}
+		return out ; 
+	}
+	
+	/**
+	 * Attempts to find the best-matching constructor of the class
+	 * o_clazz with the parameter types arg_clazz
+	 * 
+	 * @param o_clazz Class to look for a constructor
+	 * @param arg_clazz parameter types
+	 * @param arg_is_null indicates if each argument is null
+	 * 
+	 * @return <code>null</code> if no constructor is found, or the constructor
+	 *
+	 */
+	public static Constructor getConstructor( Class o_clazz, Class[] arg_clazz, boolean[] arg_is_null) 
+		throws SecurityException, NoSuchMethodException {
+		
+		if (o_clazz == null)
+			return null; 
+
+		Constructor cons = null ;
+		
+		/* if there is no argument, try to find a direct match */
+		if (arg_clazz == null || arg_clazz.length == 0) {
+			cons = o_clazz.getConstructor( (Class[] )null );
+			return cons ;
+		}
+
+		/* try to find an exact match */
+		try {
+			cons = o_clazz.getConstructor(arg_clazz);
+			if (cons != null)
+				return cons ;
+		} catch (NoSuchMethodException e) {
+			/* we catch this one because we want to further search */
+		}
+		
+		/* ok, no exact match was found - we have to walk through all methods */
+		cons = null;
+		Constructor[] candidates = o_clazz.getConstructors();
+		for (int k = 0; k < candidates.length; k++) {
+			Constructor c = candidates[k];
+			Class[] param_clazz = c.getParameterTypes();
+			if (arg_clazz.length != param_clazz.length) // number of parameters must match
+				continue;
+			int n = arg_clazz.length;
+			boolean ok = true; 
+			for (int i = 0; i < n; i++) {
+				if( arg_is_null[i] ){
+					/* then the class must not be a primitive type */
+					if( isPrimitive(arg_clazz[i]) ){ 
+						ok = false ;
+						break ;
+					}
+				} else{
+					if (arg_clazz[i] != null && !param_clazz[i].isAssignableFrom(arg_clazz[i])) {
+						ok = false; 
+						break;
+					}
+				}
+			}
+			// it must be the only match so far or more specific than the current match
+			if (ok && (cons == null || isMoreSpecific(c, cons)))
+				cons = c; 
+		}
+		
+		if( cons == null ){
+			throw new NoSuchMethodException( "No constructor matching the given parameters" ) ;
+		}
+		
+		return cons; 
+		
+	}
+	
+	
+	static boolean isPrimitive(Class cl){
+		return cl.equals(Boolean.TYPE) || cl.equals(Integer.TYPE) || 
+						cl.equals(Double.TYPE) || cl.equals(Float.TYPE) || 
+						cl.equals(Long.TYPE) || cl.equals(Short.TYPE) ||
+						cl.equals(Character.TYPE) ;
+	}
+	
+	/**
+	 * Attempts to find the best-matching method of the class <code>o_clazz</code> with the method name <code>name</code> and arguments types defined by <code>arg_clazz</code>.
+	 * The lookup is performed by finding the most specific methods that matches the supplied arguments (see also {@link #isMoreSpecific}).
+	 *
+	 * @param o_clazz class in which to look for the method
+	 * @param name method name
+	 * @param arg_clazz an array of classes defining the types of arguments
+	 * @param arg_is_null indicates if each argument is null
+	 *
+	 * @return <code>null</code> if no matching method could be found or the best matching method.
+	 */
+	public static Method getMethod(Class o_clazz, String name, Class[] arg_clazz, boolean[] arg_is_null) 
+		throws SecurityException, NoSuchMethodException {
+		
+		if (o_clazz == null)
+			return null; 
+
+		/* if there is no argument, try to find a direct match */
+		if (arg_clazz == null || arg_clazz.length == 0) {
+				return o_clazz.getMethod(name, (Class[])null);
+		}
+
+		/* try to find an exact match */
+		Method met;
+		try {
+			met = o_clazz.getMethod(name, arg_clazz);
+			if (met != null)
+				return met;
+		} catch (NoSuchMethodException e) {
+			/* we want to search further */
+		}
+		
+		/* ok, no exact match was found - we have to walk through all methods */
+		met = null;
+		Method[] ml = o_clazz.getMethods();
+		for (int k = 0; k < ml.length; k++) {
+			Method m = ml[k];
+			if (!m.getName().equals(name)) // the name must match
+				continue; 
+			Class[] param_clazz = m.getParameterTypes();
+			if (arg_clazz.length != param_clazz.length) // number of parameters must match
+				continue;
+			int n = arg_clazz.length;
+			boolean ok = true; 
+			for (int i = 0; i < n; i++) {
+				if( arg_is_null[i] ){
+					/* then the class must not be a primitive type */
+					if( isPrimitive(arg_clazz[i]) ){ 
+						ok = false ;
+						break ;
+					}
+				} else{
+					if (arg_clazz[i] != null && !param_clazz[i].isAssignableFrom(arg_clazz[i])) {
+						ok = false; 
+						break;
+					}
+				}
+			}
+			if (ok && (met == null || isMoreSpecific(m, met))) // it must be the only match so far or more specific than the current match
+				met = m; 
+		}
+		
+		if( met == null ){
+			throw new NoSuchMethodException( "No suitable method for the given parameters" ) ; 
+		}
+		return met; 
+	}
+
+	/** 
+	 * Returns <code>true</code> if <code>m1</code> is more specific than <code>m2</code>. 
+	 * The measure used is described in the isMoreSpecific( Class[], Class[] ) method
+	 *
+	 * @param m1 method to compare
+	 * @param m2 method to compare 
+	 *
+	 * @return <code>true</code> if <code>m1</code> is more specific (in arguments) than <code>m2</code>.
+	 */
+	private static boolean isMoreSpecific(Method m1, Method m2) {
+		Class[] m1_param_clazz = m1.getParameterTypes();
+		Class[] m2_param_clazz = m2.getParameterTypes();
+		return isMoreSpecific( m1_param_clazz, m2_param_clazz ); 
+	}
+	
+	/** 
+	 * Returns <code>true</code> if <code>cons1</code> is more specific than <code>cons2</code>. 
+	 * The measure used is described in the isMoreSpecific( Class[], Class[] ) method
+	 *
+	 * @param cons1 constructor to compare
+	 * @param cons2 constructor to compare 
+	 * 
+	 * @return <code>true</code> if <code>cons1</code> is more specific (in arguments) than <code>cons2</code>.
+	 */
+	private static boolean isMoreSpecific(Constructor cons1, Constructor cons2) {
+		Class[] cons1_param_clazz = cons1.getParameterTypes();
+		Class[] cons2_param_clazz = cons2.getParameterTypes();
+		return isMoreSpecific( cons1_param_clazz, cons2_param_clazz ); 
+	}
+	 
+	/**
+	 * Returns <code>true</code> if <code>c1</code> is more specific than <code>c2</code>. 
+	 *
+	 * The measure used is the sum of more specific arguments minus the sum of less specific arguments 
+	 * which in total must be positive to qualify as more specific. 
+	 * (More specific means the argument is a subclass of the other argument). 
+	 *
+	 * Both set of classes must have signatures fully compatible in the arguments 
+	 * (more precisely incompatible arguments are ignored in the comparison).
+	 *
+	 * @param c1 set of classes to compare
+	 * @param c2 set of classes to compare
+   */
+	private static boolean isMoreSpecific( Class[] c1, Class[] c2){
+	 	int n = c1.length ;
+		int res = 0; 
+		for (int i = 0; i < n; i++)
+			if( c1[i] != c2[i]) {
+				if( c1[i].isAssignableFrom(c2[i]))
+					res--;
+				else if( c2[i].isAssignableFrom(c2[i]) )
+					res++;
+			}
+		return res > 0;
+	}
+	
+	/**
+	 * Returns the list of classes of the object 
+	 *
+	 * @param o an Object
+	 */
+	public static Class[] getClasses(Object o){
+		Vector/*<Class<?>>*/ vec = new Vector(); 
+		Class cl = o.getClass(); 
+		while( cl != null ){
+			vec.add( cl ) ; 
+			cl = cl.getSuperclass() ;
+		}
+		Class[] res = new Class[ vec.size() ] ;
+		vec.toArray( res) ;
+		return res ;
+	}
+	
+	/**
+	 * Returns the list of class names of the object 
+	 *
+	 * @param o an Object
+	 */
+	public static String[] getClassNames(Object o){
+		Vector/*<String>*/ vec = new Vector(); 
+		Class cl = o.getClass(); 
+		while( cl != null ){
+			vec.add( cl.getName() ) ;
+			cl = cl.getSuperclass() ;
+		}
+		String[] res = new String[ vec.size() ] ;
+		vec.toArray( res) ;
+		return res ;
+	}
+	
+	/**
+	 * Returns the list of simple class names of the object
+	 *
+	 * @param o an Object
+	 */
+	public static String[] getSimpleClassNames(Object o, boolean addConditionClasses){
+		boolean hasException = false ;
+		Vector/*<String>*/ vec = new Vector(); 
+		Class cl = o.getClass();
+		String name ;
+		while( cl != null ){
+			name = getSimpleName( cl.getName() ) ;
+			if( "Exception".equals( name) ){
+				hasException = true ;
+			}
+			vec.add( name ) ;
+			cl = cl.getSuperclass() ;
+		}
+		if( addConditionClasses ){
+			if( !hasException ){
+				vec.add( "Exception" ) ;
+			}
+			vec.add( "error" ) ;
+			vec.add( "condition" ) ;
+		}
+		
+		String[] res = new String[ vec.size() ] ;
+		vec.toArray( res) ;
+		return res ;
+	}
+
+	/* because Class.getSimpleName is java 5 API */ 
+	private static String getSimpleClassName( Object o ){
+		return getSimpleName( o.getClass().getName() ) ; 
+	}
+	
+	private static String getSimpleName( String s ){
+		int lastsquare = s.lastIndexOf( '[' ) ;
+		if( lastsquare >= 0 ){
+			if( s.charAt(  s.lastIndexOf( '[' ) + 1 ) == 'L' ){
+				s = s.substring( s.lastIndexOf( '[' ) + 2, s.lastIndexOf( ';' ) ) ;
+			} else {
+				char first = s.charAt( 0 );
+				if( first == 'I' ) {
+					s = "int" ;
+				} else if( first == 'D' ){
+					s = "double" ;
+				} else if( first == 'Z' ){
+					s = "boolean" ;
+				} else if( first == 'B' ){
+					s = "byte" ;
+				} else if( first == 'J' ){
+					s = "long" ; 
+				} else if( first == 'F' ){
+					s = "float" ; 
+				} else if( first == 'S' ){
+					s = "short" ; 
+				} else if( first == 'C' ){
+					s = "char" ;
+				}
+			}
+		}
+		
+		int lastdollar = s.lastIndexOf( '$' ) ;
+		if( lastdollar >= 0 ){
+			s = s.substring( lastdollar + 1);
+		}
+		
+		int lastdot = s.lastIndexOf( '.' ) ;
+		if( lastdot >= 0 ){
+			s = s.substring( lastdot + 1);
+		}
+		
+		if( lastsquare >= 0 ){
+			StringBuffer buf = new StringBuffer( s );
+			int i ;
+			for( i=0; i<=lastsquare; i++){
+				buf.append( "[]" ); 
+			}
+			return buf.toString(); 
+		} else {
+			return s ;
+		}
+		
+	}
+	
+	/**
+	 * @param cl class 
+	 * @param field name of the field 
+	 * 
+	 * @return the class name of the field of the class (or null) 
+	 * if the class does not have the given field)
+	 */
+	public static String getFieldTypeName( Class cl, String field){
+		String res = null ; 
+		try{
+			res = cl.getField( field ).getType().getName() ;
+		} catch( NoSuchFieldException e){
+			/* just return null */
+			res = null ;
+		}
+		return res ;
+	}
+		
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaTools_Test.java b/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaTools_Test.java
new file mode 100644
index 0000000000000000000000000000000000000000..0d333842b4e20503922deaa95221423ab8582457
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/RJavaTools_Test.java
@@ -0,0 +1,800 @@
+
+// :tabSize=2:indentSize=2:noTabs=false:folding=explicit:collapseFolds=1:
+import java.lang.reflect.Constructor ;
+import java.lang.reflect.* ;
+import java.util.Map ;
+import java.util.Set ;
+import java.util.HashMap; 
+
+public class RJavaTools_Test {
+
+	private static class ExampleClass {
+		public ExampleClass( Object o1, String o2, boolean o3, boolean o4){}
+		public ExampleClass( Object o1, String o2, boolean o3){}
+		public ExampleClass(){}
+	}
+
+	/* so that we can check about access to private fields and methods */
+	private int bogus = 0 ; 
+	private int getBogus(){ return bogus ; }
+	private static int staticbogus ;
+	private static int getStaticBogus(){ return staticbogus ; } 
+	
+	public int x = 0 ; 
+	public static int static_x = 0; 
+	public int getX(){ return x ; }
+	public static int getStaticX(){ return static_x ; }
+	public void setX( Integer x ){ this.x = x.intValue();  } 
+	
+	// {{{ main 
+	public static void main( String[] args){
+		
+		try{
+			runtests() ; 
+		} catch( TestException e){
+			fails( e ) ; 
+			System.exit(1); 
+		}
+	}
+	
+	public static void runtests() throws TestException {
+		System.out.println( "Testing RJavaTools.getConstructor" ) ;
+			constructors() ;
+			success() ; 
+			
+			System.out.println( "Testing RJavaTools.classHasField" ) ;
+			classhasfield() ;
+			success(); 
+			
+			System.out.println( "Testing RJavaTools.classHasMethod" ) ;
+			classhasmethod() ;
+			success() ;
+			
+			System.out.println( "Testing RJavaTools.classHasClass" ) ;
+			classhasclass() ;
+			success(); 
+		
+			System.out.println( "Testing RJavaTools.hasField" ) ;
+			hasfield() ;
+			success(); 
+			
+			System.out.println( "Testing RJavaTools.hasClass" ) ;
+			hasclass() ;
+			success(); 
+			
+			System.out.println( "Testing RJavaTools.getClass" ) ;
+			getclass() ;
+			success() ;
+			
+			System.out.println( "Testing RJavaTools.hasMethod" ) ;
+			hasmethod() ;
+			success() ;
+		
+			System.out.println( "Testing RJavaTools.isStatic" ) ;
+			isstatic() ;
+			success() ; 
+			
+			System.out.println( "Testing RJavaTools.getCompletionName" ) ;
+			getcompletionname() ;
+			success(); 
+			
+			System.out.println( "Testing RJavaTools.getFieldNames" ) ;
+			getfieldnames() ;
+			success() ;
+			
+			System.out.println( "Testing RJavaTools.getMethodNames" ) ;
+			getmethodnames() ;
+			success() ;
+			
+			System.out.println( "Testing RJavaTools.getStaticFields" ) ;
+			getstaticfields() ;
+			success() ;
+		
+			System.out.println( "Testing RJavaTools.getStaticMethods" ) ;
+			getstaticmethods() ;
+			success() ;
+
+			System.out.println( "Testing RJavaTools.getStaticClasses" ) ;
+			getstaticclasses() ;
+			success() ;
+	
+			System.out.println( "Testing RJavaTools.invokeMethod" ) ;
+			invokemethod() ;
+			success() ;
+			
+			System.out.println( "Testing RJavaTools.getFieldTypeName" ) ;
+			getfieldtypename(); 
+			success() ;
+			
+			System.out.println( "Testing RJavaTools.getMethod" ) ;
+			System.out.println( "NOT YET AVAILABLE" ) ;
+			
+			System.out.println( "Testing RJavaTools.newInstance" ) ;
+			System.out.println( "NOT YET AVAILABLE" ) ;
+			
+	}
+	
+	// }}}
+
+	// {{{ fails 
+	private static void fails( TestException e ){
+		System.err.println( "\n" ) ;
+		e.printStackTrace() ;
+		System.err.println( "FAILED" ) ; 
+	}
+	// }}}
+	
+	// {{{ success
+	private static void success(){
+		System.out.println( "PASSED" ) ;    
+	}
+	// }}}
+	
+	// {{{ @Test getFieldNames
+	private static void getfieldnames() throws TestException{
+		String[] names; 
+		
+		// {{{ getFieldNames(DummyPoint, false) -> c('x', 'y' )
+		System.out.print( "    * getFieldNames(DummyPoint, false)" ) ;
+		names = RJavaTools.getFieldNames( DummyPoint.class, false ) ;
+		if( names.length != 2 ){
+			throw new TestException( "getFieldNames(DummyPoint, false).length != 2" ) ;
+		}
+		for( int i=0; i<2; i++){
+			if( !( "x".equals(names[i]) || "y".equals(names[i] ) ) ){
+				throw new TestException( "getFieldNames(DummyPoint, false).length != c('x','y') " ) ;
+			}
+		}
+		System.out.println( " : ok " ) ;
+		// }}}
+		
+		// {{{ getFieldNames(Point, true ) --> character(0)
+		System.out.print( "    * getFieldNames(DummyPoint, true )" ) ;
+		names = RJavaTools.getFieldNames( DummyPoint.class, true ) ;
+		if( names.length != 0 ){
+			throw new TestException( "getFieldNames(DummyPoint, true ) != character(0)" ); 
+		}
+		System.out.println( " : ok " ) ;
+		// }}}
+		
+		// {{{ getFieldNames(RJavaTools_Test, true ) --> static_x 
+		System.out.print( "    * getFieldNames(RJavaTools_Test, true )" ) ;
+		names = RJavaTools.getFieldNames( RJavaTools_Test.class, true ) ;
+		if( names.length != 1 ){
+			throw new TestException( "getFieldNames(RJavaTools_Test, true ).length != 1" ); 
+		}
+		if( ! "static_x".equals( names[0] ) ){
+			throw new TestException( "getFieldNames(RJavaTools_Test, true )[0] != 'static_x' " );
+		}
+		System.out.println( " : ok " ) ; 
+		// }}}
+		
+		// {{{ getFieldNames(RJavaTools_Test, false ) --> c('x', 'static_x') 
+		System.out.print( "    * getFieldNames(RJavaTools_Test, false )" ) ;
+		names = RJavaTools.getFieldNames( RJavaTools_Test.class, false ) ;
+		if( names.length != 2 ){
+			throw new TestException( "getFieldNames(RJavaTools_Test, false ).length != 2" ); 
+		}
+		for( int i=0; i<2; i++){
+			if( ! ( "x".equals( names[i] ) || "static_x".equals(names[i]) ) ){
+				throw new TestException( "getFieldNames(RJavaTools_Test, false ) != c('x', 'static_x') " );
+			}
+		}
+		System.out.println( " : ok " ) ;
+		// }}}
+		
+	}
+	// }}}
+	
+	// {{{ @Test getMethodNames
+	private static void getmethodnames() throws TestException{
+		String[] names ; 
+		String[] expected ;
+		int cpt = 0;
+		
+		// {{{ getMethodNames(RJavaTools_Test, true) -> c('getStaticX()', 'main(', 'runtests' )
+		System.out.print( "    * getMethodNames(RJavaTools_Test, true)" ) ;
+		names = RJavaTools.getMethodNames( RJavaTools_Test.class, true ) ;
+		if( names.length != 3 ){
+			throw new TestException( "getMethodNames(RJavaTools_Test, true).length != 3 (" + names.length + ")" ) ;
+		}
+		expected= new String[]{ "getStaticX()", "main(", "runtests()" };
+		cpt = 0; 
+		for( int i=0; i<names.length; i++){
+			for( int j=0; j<expected.length; j++ ){
+				if( names[i].equals( expected[j] ) ){
+					cpt++ ;
+					break; // j loop
+				}
+			}
+		}
+		if( cpt != expected.length ){
+			throw new TestException( "getMethodNames(RJavaTools_Test, true) != {'getStaticX()','main(', 'runtests()' }" + cpt ) ;
+		}
+		System.out.println( " : ok " ) ;
+		// }}}
+		
+		// {{{ getMethodNames(Object, true) -> character(0) )
+		System.out.print( "    * getMethodNames(Object, true)" ) ;
+		names = RJavaTools.getMethodNames( Object.class, true ) ;
+		if( names.length != 0 ){
+			throw new TestException( "getMethodNames(Object, true).length != 0 (" + names.length + ")" ) ;
+		}
+		System.out.println( " : ok " ) ;
+		// }}}
+		
+		// {{{ getMethodNames(RJavaTools_Test, false) %contains% { "getX()", "getStaticX()", "setX(", "main(" }
+		System.out.print( "    * getMethodNames(RJavaTools_Test, false)" ) ;
+		names = RJavaTools.getMethodNames( RJavaTools_Test.class, false ) ;
+		cpt = 0;
+		expected = new String[]{ "getX()", "getStaticX()", "setX(", "main(" }; 
+		for( int i=0; i<names.length; i++){
+			for( int j=0; j<expected.length; j++ ){
+				if( names[i].equals( expected[j] ) ){
+						cpt++; 
+						break ; /* the j loop */
+				}
+			}
+		}
+		if( cpt != expected.length ){
+			throw new TestException( "getMethodNames(RJavaTools_Test, false) did not contain expected methods " ) ; 
+		}
+		System.out.println( " : ok " ) ;
+		// }}}
+		
+		
+	}
+	// }}}
+	
+	// {{{ @Test getCompletionName
+	private static void getcompletionname() throws TestException{
+		
+		Field f ; 
+		Method m ; 
+		String name ; 
+		
+		// {{{ getCompletionName( RJavaTools_Test.x )
+		try{
+			System.out.print( "    * getCompletionName(RJavaTools_Test.x)" ) ;
+			f = RJavaTools_Test.class.getField("x") ;
+			if( ! "x".equals(RJavaTools.getCompletionName( f ) ) ){
+				throw new TestException( "getCompletionName(RJavaTools_Test.x) != 'x' " ) ; 
+			}
+			System.out.println( " == 'x' : ok " ) ;
+		} catch( NoSuchFieldException e){
+			throw new TestException( e.getMessage() ) ;
+		}
+		// }}}
+		
+		// {{{ getCompletionName( RJavaTools_Test.static_x )
+		try{
+			System.out.print( "    * getCompletionName(RJavaTools_Test.static_x)" ) ;
+			f = RJavaTools_Test.class.getField("static_x") ;
+			if( ! "static_x".equals(RJavaTools.getCompletionName( f ) ) ){
+				throw new TestException( "getCompletionName(RJavaTools_Test.static_x) != 'static_x' " ) ; 
+			}
+			System.out.println( " == 'static_x' : ok " ) ;
+		} catch( NoSuchFieldException e){
+			throw new TestException( e.getMessage() ) ;
+		}
+		// }}}
+		
+		// {{{ getCompletionName( RJavaTools_Test.getX() )
+		try{
+			System.out.print( "    * getCompletionName(RJavaTools_Test.getX() )" ) ;
+			m = RJavaTools_Test.class.getMethod("getX", (Class[])null ) ;
+			if( ! "getX()".equals(RJavaTools.getCompletionName( m ) ) ){
+				System.err.println( RJavaTools.getCompletionName( m ) );  
+				throw new TestException( "getCompletionName(RJavaTools_Test.getX() ) != ''getX()' " ) ; 
+			}
+			System.out.println( " == 'getX()' : ok " ) ;
+		} catch( NoSuchMethodException e){
+			throw new TestException( e.getMessage() ) ;
+		}
+		// }}}
+		
+		// {{{ getCompletionName( RJavaTools_Test.setX( Integer ) )
+		try{
+			System.out.print( "    * getCompletionName(RJavaTools_Test.setX( Integer ) )" ) ;
+			m = RJavaTools_Test.class.getMethod("setX", new Class[]{ Integer.class } ) ;
+			if( ! "setX(".equals(RJavaTools.getCompletionName( m ) ) ){
+				System.err.println( RJavaTools.getCompletionName( m ) );  
+				throw new TestException( "getCompletionName(RJavaTools_Test.setX(Integer) ) != 'setX(' " ) ; 
+			}
+			System.out.println( " == 'setX(' : ok " ) ;
+		} catch( NoSuchMethodException e){
+			throw new TestException( e.getMessage() ) ;
+		}
+		// }}}
+		
+	}
+	// }}}
+	
+	// {{{ @Test isStatic
+	private static void isstatic() throws TestException{
+		Field f ; 
+		Method m ; 
+		
+		// {{{ isStatic(RJavaTools_Test.x) -> false
+		try{
+			System.out.print( "    * isStatic(RJavaTools_Test.x)" ) ;
+			f = RJavaTools_Test.class.getField("x") ;
+			if( RJavaTools.isStatic( f) ){
+				throw new TestException( "isStatic(RJavaTools_Test.x) == true" ) ; 
+			}
+			System.out.println( " = false : ok " ) ;
+		} catch( NoSuchFieldException e){
+			throw new TestException( e.getMessage() ) ;
+		}
+		// }}}
+		
+		// {{{ isStatic(RJavaTools_Test.getX) -> true
+		try{
+			System.out.print( "    * isStatic(RJavaTools_Test.getX() )" ) ;
+			m = RJavaTools_Test.class.getMethod("getX", (Class[])null ) ;
+			if( RJavaTools.isStatic( m ) ){
+				throw new TestException( "isStatic(RJavaTools_Test.getX() ) == false" ) ; 
+			}
+			System.out.println( " = false : ok " ) ;
+		} catch( NoSuchMethodException e){
+			throw new TestException( e.getMessage() ) ;
+		}
+		// }}}
+		
+		// {{{ isStatic(RJavaTools_Test.static_x) -> true
+		try{
+			System.out.print( "    * isStatic(RJavaTools_Test.static_x)" ) ;
+			f = RJavaTools_Test.class.getField("static_x") ;
+			if( ! RJavaTools.isStatic( f) ){
+				throw new TestException( "isStatic(RJavaTools_Test.static_x) == false" ) ; 
+			}
+			System.out.println( " = true  : ok " ) ;
+		} catch( NoSuchFieldException e){
+			throw new TestException( e.getMessage() ) ;
+		}
+		// }}}
+	
+		// {{{ isStatic(RJavaTools_Test.getStaticX) -> true
+		try{
+			System.out.print( "    * isStatic(RJavaTools_Test.getStaticX() )" ) ;
+			m = RJavaTools_Test.class.getMethod("getStaticX", (Class[])null ) ;
+			if( ! RJavaTools.isStatic( m ) ){
+				throw new TestException( "isStatic(RJavaTools_Test.getStaticX() ) == false" ) ; 
+			}
+			System.out.println( " = true  : ok " ) ;
+		} catch( NoSuchMethodException e){
+			throw new TestException( e.getMessage() ) ;
+		}
+		// }}}
+
+		/* classes */
+		
+		// {{{ isStatic(RJavaTools_Test.TestException) -> true 
+		System.out.print( "    * isStatic(RJavaTools_Test.TestException )" ) ;
+		Class cl = RJavaTools_Test.TestException.class ; 
+		if( ! RJavaTools.isStatic( cl ) ){
+			throw new TestException( "isStatic(RJavaTools_Test.TestException) == false" ) ; 
+		}
+		System.out.println( " = true  : ok " ) ;
+		// }}}
+		
+		// {{{ isStatic(RJavaTools_Test.DummyNonStaticClass) -> false 
+		System.out.print( "    * isStatic(RJavaTools_Test.DummyNonStaticClass )" ) ;
+		cl = RJavaTools_Test.DummyNonStaticClass.class ; 
+		if( RJavaTools.isStatic( cl ) ){
+			throw new TestException( "isStatic(RJavaTools_Test.DummyNonStaticClass) == true" ) ; 
+		}
+		System.out.println( " = false : ok " ) ;
+		// }}}
+	}
+	// }}}
+	
+  // {{{ @Test constructors 
+	private static void constructors() throws TestException {
+		/* constructors */ 
+		Constructor cons ;
+		boolean error ; 
+		
+		// {{{ getConstructor( String, null )
+		System.out.print( "    * getConstructor( String, null )" ) ;
+		try{
+			cons = RJavaTools.getConstructor( String.class, (Class[])null, (boolean[])null ) ;
+		} catch( Exception e ){
+			throw new TestException( "getConstructor( String, null )" ) ; 
+		}
+		System.out.println( " : ok " ) ;
+		// }}}
+		
+		// {{{ getConstructor( Integer, { String.class } ) 
+		System.out.print( "    * getConstructor( Integer, { String.class } )" ) ;
+		try{
+			cons = RJavaTools.getConstructor( Integer.class, new Class[]{ String.class }, new boolean[]{false} ) ;
+		} catch( Exception e){
+			throw new TestException( "getConstructor( Integer, { String.class } )" ) ; 
+		}
+		System.out.println( " : ok " ) ;
+		// }}}
+		
+		// disabled for now
+		// // {{{ getConstructor( JButton, { String.class, ImageIcon.class } )
+		// System.out.print( "    * getConstructor( JButton, { String.class, ImageIcon.class } )" ) ;
+		// try{
+		// 	cons = RJavaTools.getConstructor( JButton.class, 
+		// 		new Class[]{ String.class, ImageIcon.class }, 
+		// 		new boolean[]{ false, false} ) ;
+		// } catch( Exception e){
+		// 	throw new TestException( "getConstructor( JButton, { String.class, ImageIcon.class } )" ) ; 
+		// }
+		// System.out.println( " : ok " ) ;
+		// // }}}
+		
+		// {{{ getConstructor( Integer, null ) -> exception 
+		error = false ; 
+		System.out.print( "    * getConstructor( Integer, null )" ) ;
+		try{
+			cons = RJavaTools.getConstructor( Integer.class, (Class[])null, (boolean[])null ) ;
+		} catch( Exception e){
+			 error = true ; 
+		}
+		if( !error ){
+			throw new TestException( "getConstructor( Integer, null ) did not generate error" ) ;
+		}
+		System.out.println( " -> exception : ok " ) ;
+		// }}}
+		
+		// disabled for now
+		// // {{{ getConstructor( JButton, { String.class, JButton.class } ) -> exception
+		// error = false ; 
+		// System.out.print( "    * getConstructor( JButton, { String.class, JButton.class } )" ) ;
+		// try{
+		// 	cons = RJavaTools.getConstructor( JButton.class, 
+		// 		new Class[]{ String.class, JButton.class }, 
+		// 		new boolean[]{ false, false } ) ;
+		// } catch( Exception e){
+		// 	 error = true ; 
+		// }
+		// if( !error ){
+		// 	throw new TestException( "getConstructor( JButton, { String.class, JButton.class } ) did not generate error" ) ;
+		// }
+		// System.out.println( " -> exception : ok " ) ;
+		// // }}}
+
+
+		Object o1 = null ;
+		Object o2 = null ;
+		ExampleClass foo = new ExampleClass(o1,(String)o2,false) ;
+		// {{{ getConstructor( ExampleClass, { null, null, false } 
+		error = false ;
+		System.out.print( "    * getConstructor( ExampleClass, {Object.class, Object.class, boolean}) : " ) ;
+		try{
+			cons = RJavaTools.getConstructor( ExampleClass.class, 
+				new Class[]{ Object.class, Object.class, Boolean.TYPE}, 
+				new boolean[]{ true, true, false} );
+		} catch(Exception e){
+			error = true ;
+			e.printStackTrace() ;
+		}
+		if( error ){
+			throw new TestException( "getConstructor( ExampleClass, {Object.class, Object.class, boolean}) : exception " ) ;
+		}
+		System.out.println( " ok" ) ;
+		// }}}
+		
+	
+	}
+	// }}}
+	
+	// {{{ @Test methods
+	private static void methods() throws TestException{
+		
+	}
+	// }}}
+	
+	// {{{ @Test hasfields
+	private static void hasfield() throws TestException{
+		
+		DummyPoint p = new DummyPoint() ; 
+		System.out.println( "    java> DummyPoint p = new DummyPoint()" ) ; 
+		System.out.print( "    * hasField( p, 'x' ) " ) ; 
+		if( !RJavaTools.hasField( p, "x" ) ){
+			throw new TestException( " hasField( DummyPoint, 'x' ) == false" ) ;
+		}
+		System.out.println( " true : ok" ) ;
+		
+		System.out.print( "    * hasField( p, 'iiiiiiiiiiiii' ) " ) ; 
+		if( RJavaTools.hasField( p, "iiiiiiiiiiiii" ) ){
+			throw new TestException( " hasField( DummyPoint, 'iiiiiiiiiiiii' ) == true" ) ;
+		}
+		System.out.println( "  false : ok" ) ;
+		
+		/* testing a private field */
+		RJavaTools_Test ob = new RJavaTools_Test(); 
+		System.out.print( "    * testing a private field " ) ; 
+		if( RJavaTools.hasField( ob, "bogus" ) ){
+			throw new TestException( " hasField returned true on private field" ) ;
+		}
+		System.out.println( "  false : ok" ) ;
+		
+		
+	}
+	// }}}
+	
+	// {{{ @Test hasmethod
+	private static void hasmethod() throws TestException{
+		
+		DummyPoint p = new DummyPoint() ; 
+		System.out.println( "    java> DummyPoint p = new DummyPoint()" ) ; 
+		System.out.print( "    * hasMethod( p, 'move' ) " ) ; 
+		if( !RJavaTools.hasMethod( p, "move" ) ){
+			throw new TestException( " hasField( DummyPoint, 'move' ) == false" ) ;
+		}
+		System.out.println( " true : ok" ) ;
+		
+		System.out.print( "    * hasMethod( p, 'iiiiiiiiiiiii' ) " ) ; 
+		if( RJavaTools.hasMethod( p, "iiiiiiiiiiiii" ) ){
+			throw new TestException( " hasMethod( Point, 'iiiiiiiiiiiii' ) == true" ) ;
+		}
+		System.out.println( "  false : ok" ) ;
+		
+		/* testing a private method */
+		RJavaTools_Test ob = new RJavaTools_Test(); 
+		System.out.print( "    * testing a private method " ) ; 
+		if( RJavaTools.hasField( ob, "getBogus" ) ){
+			throw new TestException( " hasMethod returned true on private method" ) ;
+		}
+		System.out.println( "  false : ok" ) ;
+
+	}
+	// }}}
+
+	// {{{ @Test hasclass
+	private static void hasclass() throws TestException{
+		
+		RJavaTools_Test ob = new RJavaTools_Test(); 
+		
+		System.out.print( "    * hasClass( RJavaTools_Test, 'TestException' ) " ) ; 
+		if( ! RJavaTools.hasClass( ob, "TestException" ) ){
+			throw new TestException( " hasClass( RJavaTools_Test, 'TestException' ) == false" ) ;
+		}
+		System.out.println( "  true : ok" ) ;
+
+		System.out.print( "    * hasClass( RJavaTools_Test, 'DummyNonStaticClass' ) " ) ; 
+		if( ! RJavaTools.hasClass( ob, "DummyNonStaticClass" ) ){
+			throw new TestException( " hasClass( RJavaTools_Test, 'DummyNonStaticClass' ) == false" ) ;
+		}
+		System.out.println( "  true : ok" ) ;
+
+	}
+	// }}}
+	
+	// {{{ @Test hasclass
+	private static void getclass() throws TestException{
+		Class cl ; 
+		
+		System.out.print( "    * getClass( RJavaTools_Test, 'TestException', true ) " ) ; 
+		cl = RJavaTools.getClass( RJavaTools_Test.class, "TestException", true ); 
+		if( cl != RJavaTools_Test.TestException.class ){
+			throw new TestException( " getClass( RJavaTools_Test, 'TestException', true ) != TestException" ) ;
+		}
+		System.out.println( "  : ok" ) ;
+
+		System.out.print( "    * getClass( RJavaTools_Test, 'DummyNonStaticClass', true ) " ) ; 
+		cl = RJavaTools.getClass( RJavaTools_Test.class, "DummyNonStaticClass", true ); 
+		if( cl != null ){
+			throw new TestException( " getClass( RJavaTools_Test, 'DummyNonStaticClass', true ) != null" ) ;
+		}
+		System.out.println( "  : ok" ) ;
+
+		System.out.print( "    * getClass( RJavaTools_Test, 'DummyNonStaticClass', false ) " ) ; 
+		cl = RJavaTools.getClass( RJavaTools_Test.class, "DummyNonStaticClass", false ); 
+		if( cl != RJavaTools_Test.DummyNonStaticClass.class ){
+			throw new TestException( " getClass( RJavaTools_Test, 'DummyNonStaticClass', true ) != null" ) ;
+		}
+		System.out.println( "  : ok" ) ;
+
+	}
+	// }}}
+	
+	// {{{ @Test classhasfield
+	private static void classhasfield() throws TestException{
+
+	}
+	// }}}
+	
+	// {{{ @Test classhasclass
+	private static void classhasclass() throws TestException{
+		System.out.print( "    * classHasClass( RJavaTools_Test, 'TestException', true ) " ) ; 
+		if( ! RJavaTools.classHasClass( RJavaTools_Test.class , "TestException", true ) ){
+			throw new TestException( " classHasClass( RJavaTools_Test, 'TestException', true ) == false" ) ;
+		}
+		System.out.println( "  true : ok" ) ;
+
+		System.out.print( "    * classHasClass( RJavaTools_Test, 'DummyNonStaticClass', true ) " ) ; 
+		if( RJavaTools.classHasClass( RJavaTools_Test.class , "DummyNonStaticClass", true ) ){
+			throw new TestException( " classHasClass( RJavaTools_Test, 'DummyNonStaticClass', true ) == true" ) ;
+		}
+		System.out.println( "  false : ok" ) ;
+
+		System.out.print( "    * classHasClass( RJavaTools_Test, 'DummyNonStaticClass', false ) " ) ; 
+		if( ! RJavaTools.classHasClass( RJavaTools_Test.class , "DummyNonStaticClass", false ) ){
+			throw new TestException( " classHasClass( RJavaTools_Test, 'DummyNonStaticClass', false ) == false" ) ;
+		}
+		System.out.println( "  true : ok" ) ;
+
+	}
+	// }}}
+	
+	// {{{ @Test classhasmethod
+	private static void classhasmethod() throws TestException{
+
+		System.out.print( "    * classHasMethod( RJavaTools_Test, 'getX', false ) " ) ;
+		if( ! RJavaTools.classHasMethod( RJavaTools_Test.class, "getX", false ) ){
+			throw new TestException( " classHasMethod( RJavaTools_Test, 'getX', false ) == false" ) ;
+		}
+		System.out.println( "  true : ok" ) ;
+
+		System.out.print( "    * classHasMethod( RJavaTools_Test, 'getStaticX', false ) " ) ;
+		if( ! RJavaTools.classHasMethod( RJavaTools_Test.class, "getStaticX", false ) ){
+			throw new TestException( " classHasMethod( RJavaTools_Test, 'getStaticX', false ) == false" ) ;
+		}
+		System.out.println( "  true : ok" ) ;
+
+		System.out.print( "    * classHasMethod( RJavaTools_Test, 'getX', true ) " ) ;
+		if( RJavaTools.classHasMethod( RJavaTools_Test.class, "getX", true ) ){
+			throw new TestException( " classHasMethod( RJavaTools_Test, 'getX', true ) == true (non static method)" ) ;
+		}
+		System.out.println( "  false : ok" ) ;
+
+		System.out.print( "    * classHasMethod( RJavaTools_Test, 'getStaticX', true ) " ) ;
+		if( ! RJavaTools.classHasMethod( RJavaTools_Test.class, "getStaticX", true ) ){
+			throw new TestException( " classHasMethod( RJavaTools_Test, 'getStaticX', true ) == false (static)" ) ;
+		}
+		System.out.println( "  true : ok" ) ;
+
+		System.out.print( "    * classHasMethod( RJavaTools_Test, 'getBogus', false ) " ) ;
+		if( RJavaTools.classHasMethod( RJavaTools_Test.class, "getBogus", false ) ){
+			throw new TestException( " classHasMethod( RJavaTools_Test, 'getBogus', false ) == true (private method)" ) ;
+		}
+		System.out.println( "  false : ok" ) ;
+
+		System.out.print( "    * classHasMethod( RJavaTools_Test, 'getStaticBogus', true ) " ) ;
+		if( RJavaTools.classHasMethod( RJavaTools_Test.class, "getStaticBogus", true ) ){
+			throw new TestException( " classHasMethod( RJavaTools_Test, 'getBogus', true ) == true (private method)" ) ;
+		}
+		System.out.println( "  false : ok" ) ;
+
+	}
+	// }}}
+	
+	// {{{ @Test getstaticfields
+	private static void getstaticfields() throws TestException{
+		Field[] f ;
+		
+		System.out.print( "    * getStaticFields( RJavaTools_Test ) " ) ;
+		f = RJavaTools.getStaticFields( RJavaTools_Test.class ) ;
+		if( f.length != 1 ){
+			throw new TestException( " getStaticFields( RJavaTools_Test ).length != 1" ) ;
+		}
+		if( ! "static_x".equals( f[0].getName() ) ){
+			throw new TestException( " getStaticFields( RJavaTools_Test )[0] != 'static_x'" ) ;
+		}
+		System.out.println( "  : ok" ) ;
+		
+		System.out.print( "    * getStaticFields( Object ) " ) ;
+		f = RJavaTools.getStaticFields( Object.class ) ;
+		if( f != null ){
+			throw new TestException( " getStaticFields( Object ) != null" ) ;
+		}
+		System.out.println( "  : ok" ) ;
+		
+	}
+	// }}}
+	 
+	// {{{ @Test getstaticmethods
+	private static void getstaticmethods() throws TestException{
+		Method[] m ;
+		
+		// {{{ getStaticMethods( RJavaTools_Test )
+		System.out.print( "    * getStaticMethods( RJavaTools_Test ) " ) ;
+		m = RJavaTools.getStaticMethods( RJavaTools_Test.class ) ;
+		String[] expected = new String[]{ "getStaticX" , "main", "runtests" };
+		int count = 0; 
+		if( m.length != expected.length ){
+			throw new TestException( " getStaticMethods( RJavaTools_Test ).length != 2" ) ;
+		}
+		for( int i=0; i<m.length; i++){
+			for( int j=0; j<expected.length; j++ ){
+				if( m[i].getName().equals( expected[j] ) ){
+					count++; 
+					break ; // the j loop
+				}
+			}
+		}
+		if( count != expected.length ){
+			throw new TestException( " getStaticMethods( RJavaTools_Test ) != c('main', 'getStaticX', 'runtests' ) " ) ;
+		}
+		System.out.println( "  : ok" ) ;
+		// }}}
+		
+		// {{{ getStaticMethods( Object )
+		System.out.print( "    * getStaticMethods( Object ) " ) ;
+		m = RJavaTools.getStaticMethods( Object.class ) ;
+		if( m != null ){
+			throw new TestException( " getStaticMethods( Object ) != null" ) ;
+		}
+		System.out.println( "  : ok" ) ;
+		// }}}
+		
+	}
+	// }}}
+	
+	// {{{ @Test getstaticclasses
+	private static void getstaticclasses() throws TestException{
+		Class[] clazzes ;
+		
+		// {{{ getStaticClasses( Object )
+		System.out.print( "    * getStaticClasses( Object ) " ) ;
+		clazzes = RJavaTools.getStaticClasses( Object.class ) ;
+		if( clazzes != null ){
+			throw new TestException( " getStaticClasses( Object ) != null" ) ;
+		}
+		System.out.println( "  : ok" ) ;
+		// }}}
+		
+		// {{{ getStaticClasses( RJavaTools_Test )
+		System.out.print( "    * getStaticClasses( RJavaTools_Test ) " ) ;
+		clazzes = RJavaTools.getStaticClasses( RJavaTools_Test.class ) ;
+		if( clazzes.length != 1 ){
+			throw new TestException( " getStaticClasses( RJavaTools_Test ).length != 1" ) ;
+		}
+		if( clazzes[0] != RJavaTools_Test.TestException.class ){
+			throw new TestException( " getStaticClasses( RJavaTools_Test ) != RJavaTools_Test.TestException" ) ;
+		}
+		System.out.println( "  : ok" ) ;
+		// }}}
+		
+	}
+	// }}}
+	
+	// {{{ @Test invokeMethod
+	private static void invokemethod() throws TestException{
+		
+		// {{{ enforcing accessibility
+		System.out.print( "  * testing enforcing accessibility (bug# 128)" ) ; 
+		Map map = new HashMap(); 
+		map.put( "x", "x" ) ; 
+		Set set = map.entrySet() ; 
+		try{
+			Object o = RJavaTools.invokeMethod( set.getClass(), set, "iterator", (Object[])null, (Class[])null );
+		} catch( Throwable e){
+			throw new TestException( "not able to enforce accessibility" ) ; 
+		}
+		System.out.println( " : ok " ) ;
+		// }}}
+	}
+	// }}}
+	
+	// {{{ @Test getFieldTypeName
+	private static void getfieldtypename() throws TestException{
+		System.out.print( "  * getFieldTypeName( DummyPoint, x )" ) ;
+		String s = RJavaTools.getFieldTypeName( DummyPoint.class, "x" ) ;
+		if( !s.equals("int") ){
+			throw new TestException("getFieldTypeName( DummyPoint, x ) != int") ;
+		}
+		System.out.println( ": ok" ) ;
+	}
+	// }}}
+	
+	// {{{ TestException class
+	public static class TestException extends Exception{
+		public TestException( String message ){
+			super( message ) ;
+		}
+	}
+	// }}}
+	
+	// {{{ Dummy
+	public class DummyNonStaticClass{}
+	// }}}
+	
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/RectangularArrayBuilder.java b/com.oracle.truffle.r.pkgs/rJava/src/java/RectangularArrayBuilder.java
new file mode 100644
index 0000000000000000000000000000000000000000..9bb9cb9736aa50db48390bd84598d650d5b6e10a
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/RectangularArrayBuilder.java
@@ -0,0 +1,188 @@
+// :tabSize=2:indentSize=2:noTabs=false:folding=explicit:collapseFolds=1:
+
+import java.lang.reflect.Array ; 
+
+/**
+ * Builds rectangular java arrays
+ */
+public class RectangularArrayBuilder extends RJavaArrayIterator {
+	
+	// {{{ constructors
+	/**
+	 * constructor
+	 *
+	 * @param payload one dimensional array
+	 * @param dimensions target dimensions
+	 * @throws NotAnArrayException if payload is not an array
+	 */
+	public RectangularArrayBuilder( Object payload, int[] dimensions) throws NotAnArrayException, ArrayDimensionException {
+		
+		super( dimensions ) ; 
+		if( !RJavaArrayTools.isArray(payload) ){
+			throw new NotAnArrayException( payload.getClass() ) ;
+		}
+		if( !RJavaArrayTools.isSingleDimensionArray(payload)){
+			throw new ArrayDimensionException( "not a single dimension array : " + payload.getClass() ) ;
+		}
+		
+		if( dimensions.length == 1 ){
+			array = payload ;
+		} else{
+			
+			String typeName = RJavaArrayTools.getObjectTypeName( payload ); 
+			Class clazz = null ;
+			try{
+				clazz = RJavaArrayTools.getClassForSignature( typeName, payload.getClass().getClassLoader() );  
+			} catch( ClassNotFoundException e){/* should not happen */}
+			
+			array = Array.newInstance( clazz , dimensions ) ;
+		  if( typeName.equals( "I" ) ){
+		  	fill_int( (int[])payload ) ;
+		  } else if( typeName.equals( "Z" ) ){
+		  	fill_boolean( (boolean[])payload ) ;
+		  } else if( typeName.equals( "B" ) ){
+		  	fill_byte( (byte[])payload ) ;
+		  } else if( typeName.equals( "J" ) ){
+		  	fill_long( (long[])payload ) ;
+		  } else if( typeName.equals( "S" ) ){
+		  	fill_short( (short[])payload ) ;
+		  } else if( typeName.equals( "D" ) ){
+		  	fill_double( (double[])payload ) ;
+		  } else if( typeName.equals( "C" ) ){
+		  	fill_char( (char[])payload ) ;
+		  } else if( typeName.equals( "F" ) ){
+		  	fill_float( (float[])payload ) ;
+		  } else{
+		  	fill_Object( (Object[])payload ) ;
+		  }
+			
+		}
+	}
+	public RectangularArrayBuilder( Object payload, int length ) throws NotAnArrayException, ArrayDimensionException{
+		this( payload, new int[]{ length } ) ;
+	}
+
+	// java < 1.5 kept happy
+	public RectangularArrayBuilder(int x    , int[] dim ) throws NotAnArrayException { throw new NotAnArrayException("primitive type : int     ") ; }
+	public RectangularArrayBuilder(boolean x, int[] dim ) throws NotAnArrayException { throw new NotAnArrayException("primitive type : boolean ") ; }
+	public RectangularArrayBuilder(byte x   , int[] dim ) throws NotAnArrayException { throw new NotAnArrayException("primitive type : byte    ") ; }
+	public RectangularArrayBuilder(long x   , int[] dim ) throws NotAnArrayException { throw new NotAnArrayException("primitive type : long    ") ; }
+	public RectangularArrayBuilder(short x  , int[] dim ) throws NotAnArrayException { throw new NotAnArrayException("primitive type : short   ") ; }
+	public RectangularArrayBuilder(double x , int[] dim ) throws NotAnArrayException { throw new NotAnArrayException("primitive type : double  ") ; }
+	public RectangularArrayBuilder(char x   , int[] dim ) throws NotAnArrayException { throw new NotAnArrayException("primitive type : char    ") ; }
+	public RectangularArrayBuilder(float x  , int[] dim ) throws NotAnArrayException { throw new NotAnArrayException("primitive type : float   ") ; }
+
+	public RectangularArrayBuilder(int x    , int length ) throws NotAnArrayException { throw new NotAnArrayException("primitive type : int     ") ; }
+	public RectangularArrayBuilder(boolean x, int length ) throws NotAnArrayException { throw new NotAnArrayException("primitive type : boolean ") ; }
+	public RectangularArrayBuilder(byte x   , int length ) throws NotAnArrayException { throw new NotAnArrayException("primitive type : byte    ") ; }
+	public RectangularArrayBuilder(long x   , int length ) throws NotAnArrayException { throw new NotAnArrayException("primitive type : long    ") ; }
+	public RectangularArrayBuilder(short x  , int length ) throws NotAnArrayException { throw new NotAnArrayException("primitive type : short   ") ; }
+	public RectangularArrayBuilder(double x , int length ) throws NotAnArrayException { throw new NotAnArrayException("primitive type : double  ") ; }
+	public RectangularArrayBuilder(char x   , int length ) throws NotAnArrayException { throw new NotAnArrayException("primitive type : char    ") ; }
+	public RectangularArrayBuilder(float x  , int length ) throws NotAnArrayException { throw new NotAnArrayException("primitive type : float   ") ; }
+	// }}}
+	
+	// {{{ fill_**
+	private void fill_int( int[] payload ){
+		int k; 
+		while( hasNext() ){
+			int[] current = (int[])next() ;
+			k = start ; 
+			for( int j=0; j<current.length; j++, k+=increment){
+				current[j] = payload[k];
+			}
+		}
+	}
+	
+	private void fill_boolean( boolean[] payload ){
+		int k; 
+		while( hasNext() ){
+			boolean[] current = (boolean[])next() ;
+			k = start ; 
+			for( int j=0; j<current.length; j++, k+=increment){
+				current[j] = payload[k];
+			}
+		}
+	}
+	
+	private void fill_byte( byte[] payload ){
+		int k; 
+		while( hasNext() ){
+			byte[] current = (byte[])next() ;
+			k = start ; 
+			for( int j=0; j<current.length; j++, k+=increment){
+				current[j] = payload[k];
+			}
+		}
+	}
+	
+	private void fill_long( long[] payload ){
+		int k; 
+		while( hasNext() ){
+			long[] current = (long[])next() ;
+			k = start ; 
+			for( int j=0; j<current.length; j++, k+=increment){
+				current[j] = payload[k];
+			}
+		}
+	}
+
+	private void fill_short( short[] payload ){
+		int k; 
+		while( hasNext() ){
+			short[] current = (short[])next() ;
+			k = start ; 
+			for( int j=0; j<current.length; j++, k+=increment){
+				current[j] = payload[k];
+			}
+		}
+	}
+
+	private void fill_double( double[] payload ){
+		int k; 
+		while( hasNext() ){
+			double[] current = (double[])next() ;
+			k = start ; 
+			for( int j=0; j<current.length; j++, k+=increment){
+				current[j] = payload[k];
+			}
+		}
+	}
+
+	private void fill_char( char[] payload ){
+		int k; 
+		while( hasNext() ){
+			char[] current = (char[])next() ;
+			k = start ; 
+			for( int j=0; j<current.length; j++, k+=increment){
+				current[j] = payload[k];
+			}
+		}
+	}
+
+	private void fill_float( float[] payload ){
+		int k; 
+		while( hasNext() ){
+			float[] current = (float[])next() ;
+			k = start ; 
+			for( int j=0; j<current.length; j++, k+=increment){
+				current[j] = payload[k];
+			}
+		}
+	}
+	
+	private void fill_Object( Object[] payload ){
+		int k; 
+		while( hasNext() ){
+			Object[] current = (Object[])next() ;
+			k = start ; 
+			for( int j=0; j<current.length; j++, k+=increment){
+				current[j] = payload[k];
+			}
+		}
+	}
+
+	// }}}
+
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/RectangularArrayBuilder_Test.java b/com.oracle.truffle.r.pkgs/rJava/src/java/RectangularArrayBuilder_Test.java
new file mode 100644
index 0000000000000000000000000000000000000000..08cbac4fe303580c0d04ad1695ff896b15e8c713
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/RectangularArrayBuilder_Test.java
@@ -0,0 +1,819 @@
+// :tabSize=2:indentSize=2:noTabs=false:folding=explicit:collapseFolds=1:
+
+/**
+ * Test suite for RectangularArrayBuilder 
+ */
+public class RectangularArrayBuilder_Test {
+
+	private static int[] dim1d = {10} ;
+	private static int[] dim2d = {5,2} ;
+	private static int[] dim3d = {5,3,2} ;
+	
+	// {{{ main
+	public static void main(String[] args ){
+		try{
+			runtests() ;
+		} catch( TestException e){
+			e.printStackTrace(); 
+			System.exit(1); 
+		}
+		System.out.println( "\nALL PASSED\n" ) ; 
+		System.exit( 0 ); 
+	}
+	// }}}
+	
+	// {{{ runtests
+	public static void runtests() throws TestException {
+		
+		// {{{ 1d 
+		System.out.println( " >> 1 d" );
+		System.out.print( "fill int[]" );     fill_int_1();     System.out.println( " :  ok" ); 
+		System.out.print( "fill boolean[]" ); fill_boolean_1(); System.out.println( " :  ok" );
+		System.out.print( "fill byte[]" ); fill_byte_1(); System.out.println( " :  ok" );
+		System.out.print( "fill long[]" ); fill_long_1(); System.out.println( " :  ok" );
+		System.out.print( "fill short[]" ); fill_short_1(); System.out.println( " :  ok" );
+		System.out.print( "fill double[]" ); fill_double_1(); System.out.println( " :  ok" );
+		System.out.print( "fill char[]" ); fill_char_1(); System.out.println( " :  ok" );
+		System.out.print( "fill float[]" ); fill_float_1(); System.out.println( " :  ok" );
+		System.out.print( "fill String[]" ); fill_String_1(); System.out.println( " :  ok" );
+		System.out.print( "fill Point[]" ); fill_Point_1(); System.out.println( " :  ok" );
+		// }}}
+		
+		// {{{ 2d 
+		System.out.println( " >> 2 d" );
+		System.out.print( "fill int[][]" );     fill_int_2();     System.out.println( " :  ok" ); 
+		System.out.print( "fill boolean[][]" ); fill_boolean_2(); System.out.println( " :  ok" );
+		System.out.print( "fill byte[][]" ); fill_byte_2(); System.out.println( " :  ok" );
+		System.out.print( "fill long[][]" ); fill_long_2(); System.out.println( " :  ok" );
+		System.out.print( "fill short[][]" ); fill_short_2(); System.out.println( " :  ok" );
+		System.out.print( "fill double[][]" ); fill_double_2(); System.out.println( " :  ok" );
+		System.out.print( "fill char[][]" ); fill_char_2(); System.out.println( " :  ok" );
+		System.out.print( "fill float[][]" ); fill_float_2(); System.out.println( " :  ok" );
+		System.out.print( "fill String[][]" ); fill_String_2(); System.out.println( " :  ok" );
+		System.out.print( "fill Point[][]" ); fill_Point_2(); System.out.println( " :  ok" );
+		// }}}
+		
+		// {{{ 3d 
+		System.out.println( " >> 3 d" );
+		System.out.print( "fill int[][][]" );     fill_int_3();     System.out.println( " :  ok" ); 
+		System.out.print( "fill boolean[][][]" ); fill_boolean_3(); System.out.println( " :  ok" );
+		System.out.print( "fill byte[][][]" ); fill_byte_3(); System.out.println( " :  ok" );
+		System.out.print( "fill long[][][]" ); fill_long_3(); System.out.println( " :  ok" );
+		System.out.print( "fill short[][][]" ); fill_short_3(); System.out.println( " :  ok" );
+		System.out.print( "fill double[][][]" ); fill_double_3(); System.out.println( " :  ok" );
+		System.out.print( "fill char[][][]" ); fill_char_3(); System.out.println( " :  ok" );
+		System.out.print( "fill float[][][]" ); fill_float_3(); System.out.println( " :  ok" );
+		System.out.print( "fill String[][][]" ); fill_String_3(); System.out.println( " :  ok" );
+		System.out.print( "fill Point[][][]" ); fill_Point_3(); System.out.println( " :  ok" );
+		// }}}
+		
+	}
+	//}}}
+
+	// {{{ 1d
+	private static void fill_int_1() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( ints(10), dim1d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array int[10]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		int[] data = (int[])builder.getArray();
+		int current = 0; 
+		for( int i=0; i<dim1d[0]; i++, current++){
+			if( data[i] != current ){
+				throw new TestException( "data["+i+"] != " + current ) ;
+			}
+		}
+		
+	}
+
+	private static void fill_boolean_1() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( booleans(10), dim1d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array boolean[10]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		boolean[] data = (boolean[])builder.getArray();
+		boolean current = false; 
+	
+		for( int i=0; i<dim1d[0]; i++, current=!current){
+				if( data[i] != current ){
+					throw new TestException( "data["+i+"] != " + current ) ;
+				}
+		}
+		
+	}
+	
+	private static void fill_byte_1() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( bytes(10), dim1d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array byte[10]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		byte[] data = (byte[])builder.getArray();
+		int current = 0; 
+		for( int i=0; i<dim1d[0]; i++, current++){
+			if( data[i] != current ){
+				throw new TestException( "data["+i+"] != " + current ) ;
+			}
+		}
+		
+	}
+
+	private static void fill_long_1() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( longs(10), dim1d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array long[10]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		long[] data = (long[])builder.getArray();
+		int current = 0; 
+		for( int i=0; i<dim1d[0]; i++, current++){
+			if( data[i] != current ){
+				throw new TestException( "data["+i+"] != " + current ) ;
+			}
+		}
+		
+	}
+
+	private static void fill_short_1() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( shorts(10), dim1d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array short[10]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		short[] data = (short[])builder.getArray();
+		int current = 0; 
+		for( int i=0; i<dim1d[0]; i++, current++){
+			if( data[i] != current ){
+				throw new TestException( "data["+i+"] != " + current ) ;
+			}
+		}
+		
+	}
+
+	private static void fill_double_1() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( doubles(10), dim1d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array double[10]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		double[] data = (double[])builder.getArray();
+		int current = 0; 
+		for( int i=0; i<dim1d[0]; i++, current++){
+			if( data[i] != current ){
+				throw new TestException( "data["+i+"] != " + current ) ;
+			}
+		}
+		
+	}
+
+	private static void fill_char_1() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( chars(10), dim1d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array char[10]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		char[] data = (char[])builder.getArray();
+		int current = 0; 
+		for( int i=0; i<dim1d[0]; i++, current++){
+			if( data[i] != current ){
+				throw new TestException( "data["+i+"] != " + current ) ;
+			}
+		}
+		
+	}
+
+	private static void fill_float_1() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( floats(10), dim1d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array float[10]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		float[] data = (float[])builder.getArray();
+		int current = 0; 
+		for( int i=0; i<dim1d[0]; i++, current++){
+			if( data[i] != current ){
+				throw new TestException( "data["+i+"] != " + current ) ;
+			}
+		}
+		
+	}
+	
+	private static void fill_String_1() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( strings(10), dim1d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array String[10]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		String[] data = (String[])builder.getArray();
+		int current = 0; 
+		for( int i=0; i<dim1d[0]; i++, current++){
+			if( !data[i].equals(current+"") ){
+				throw new TestException( "data["+i+"] != " + current ) ;
+			}
+		}
+		
+	}
+
+	private static void fill_Point_1() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( points(10), dim1d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array DummyPoint[10]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		DummyPoint[] data = (DummyPoint[])builder.getArray();
+		int current = 0; 
+		for( int i=0; i<dim1d[0]; i++, current++){
+			DummyPoint p = data[i] ;
+			if( p.x != current || p.y != current ){
+				throw new TestException( "data["+i+"].x != " + current ) ;
+			}
+		}
+		
+	}
+	
+	// }}}
+	
+	// {{{ 2d 
+	private static void fill_int_2() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( ints(10), dim2d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array int[10]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		int[][] data = (int[][])builder.getArray();
+		int current = 0; 
+		for( int j=0; j<dim2d[1]; j++){
+			for( int i=0; i<dim2d[0]; i++, current++){
+				if( data[i][j] != current ){
+					throw new TestException( "data["+i+"]["+j+"] != " + current ) ;
+				}
+			}
+		}
+		
+	}
+
+	private static void fill_boolean_2() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( booleans(10), dim2d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array boolean[10]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		boolean[][] data = (boolean[][])builder.getArray();
+		boolean current = false; 
+		for( int j=0; j<dim2d[1]; j++){
+			for( int i=0; i<dim2d[0]; i++, current=!current){
+				if( data[i][j] != current ){
+					throw new TestException( "data["+i+"]["+j+"] != " + current ) ;
+				}
+			}
+		}
+		
+	}
+	
+	private static void fill_byte_2() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( bytes(10), dim2d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array byte[10]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		byte[][] data = (byte[][])builder.getArray();
+		int current = 0; 
+		for( int j=0; j<dim2d[1]; j++){
+			for( int i=0; i<dim2d[0]; i++, current++){
+				if( data[i][j] != current ){
+					throw new TestException( "data["+i+"]["+j+"] != " + current ) ;
+				}
+			}
+		}
+		
+	}
+
+	private static void fill_long_2() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( longs(10), dim2d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array long[10]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		long[][] data = (long[][])builder.getArray();
+		int current = 0; 
+		for( int j=0; j<dim2d[1]; j++){
+			for( int i=0; i<dim2d[0]; i++, current++){
+				if( data[i][j] != current ){
+					throw new TestException( "data["+i+"]["+j+"] != " + current ) ;
+				}
+			}
+		}
+		
+	}
+
+	private static void fill_short_2() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( shorts(10), dim2d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array short[10]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		short[][] data = (short[][])builder.getArray();
+		int current = 0; 
+		for( int j=0; j<dim2d[1]; j++){
+			for( int i=0; i<dim2d[0]; i++, current++){
+				if( data[i][j] != current ){
+					throw new TestException( "data["+i+"]["+j+"] != " + current ) ;
+				}
+			}
+		}
+		
+	}
+
+	private static void fill_double_2() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( doubles(10), dim2d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array double[10]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		double[][] data = (double[][])builder.getArray();
+		int current = 0; 
+		for( int j=0; j<dim2d[1]; j++){
+			for( int i=0; i<dim2d[0]; i++, current++){
+				if( data[i][j] != current ){
+					throw new TestException( "data["+i+"]["+j+"] != " + current ) ;
+				}
+			}
+		}
+		
+	}
+
+	private static void fill_char_2() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( chars(10), dim2d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array char[10]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		char[][] data = (char[][])builder.getArray();
+		int current = 0; 
+		for( int j=0; j<dim2d[1]; j++){
+			for( int i=0; i<dim2d[0]; i++, current++){
+				if( data[i][j] != current ){
+					throw new TestException( "data["+i+"]["+j+"] != " + current ) ;
+				}
+			}
+		}
+		
+	}
+
+	private static void fill_float_2() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( floats(10), dim2d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array float[10]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		float[][] data = (float[][])builder.getArray();
+		int current = 0; 
+		for( int j=0; j<dim2d[1]; j++){
+			for( int i=0; i<dim2d[0]; i++, current++){
+				if( data[i][j] != current ){
+					throw new TestException( "data["+i+"]["+j+"] != " + current ) ;
+				}
+			}
+		}
+		
+	}
+	
+	private static void fill_String_2() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( strings(10), dim2d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array String[10]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		String[][] data = (String[][])builder.getArray();
+		int current = 0; 
+		for( int j=0; j<dim2d[1]; j++){
+			for( int i=0; i<dim2d[0]; i++, current++){
+				if( !data[i][j].equals(current+"") ){
+					throw new TestException( "data["+i+"]["+j+"] != " + current ) ;
+				}
+			}
+		}
+		
+	}
+
+		private static void fill_Point_2() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( points(10), dim2d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array Point[10]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		DummyPoint[][] data = (DummyPoint[][])builder.getArray();
+		int current = 0; 
+		for( int j=0; j<dim2d[1]; j++){
+			for( int i=0; i<dim2d[0]; i++, current++){
+				DummyPoint p = data[i][j] ;
+				if( p.x != current || p.y != current ){
+					throw new TestException( "data["+i+"]["+j+"].x != " + current ) ;
+				}
+			}
+		}
+		
+	}
+
+	// }}}
+
+	// {{{ 3d
+	private static void fill_int_3() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( ints(30), dim3d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array int[30]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		int[][][] data = (int[][][])builder.getArray();
+		int current = 0;
+		for( int k=0; k<dim3d[2] ; k++ ){
+			for( int j=0; j<dim3d[1]; j++){
+				for( int i=0; i<dim3d[0]; i++, current++){
+					if( data[i][j][k] != current ){
+						throw new TestException( "data["+i+"]["+j+"]["+k+"]  != " + current ) ;
+					}
+				}
+			}
+		}
+		
+	}
+
+	private static void fill_boolean_3() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( booleans(30), dim3d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array boolean[30]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		boolean[][][] data = (boolean[][][])builder.getArray();
+		boolean current = false; 
+		for( int k=0; k<dim3d[2] ; k++ ){
+			for( int j=0; j<dim3d[1]; j++){
+				for( int i=0; i<dim3d[0]; i++, current=!current){
+					if( data[i][j][k] != current ){
+						throw new TestException( "data["+i+"]["+j+"]["+k+"]  != " + current ) ;
+					}
+				}
+			}
+		}
+	}
+	
+	private static void fill_byte_3() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( bytes(30), dim3d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array byte[30]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		byte[][][] data = (byte[][][])builder.getArray();
+		int current = 0; 
+		for( int k=0; k<dim3d[2] ; k++ ){
+			for( int j=0; j<dim3d[1]; j++){
+				for( int i=0; i<dim3d[0]; i++, current++){
+					if( data[i][j][k] != current ){
+						throw new TestException( "data["+i+"]["+j+"]["+k+"]  != " + current ) ;
+					}
+				}
+			}
+		}
+	}
+
+	private static void fill_long_3() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( longs(30), dim3d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array long[30]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		long[][][] data = (long[][][])builder.getArray();
+		int current = 0; 
+		for( int k=0; k<dim3d[2] ; k++ ){
+			for( int j=0; j<dim3d[1]; j++){
+				for( int i=0; i<dim3d[0]; i++, current++){
+					if( data[i][j][k] != current ){
+						throw new TestException( "data["+i+"]["+j+"]["+k+"]  != " + current ) ;
+					}
+				}
+			}
+		}
+	}
+
+	private static void fill_short_3() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( shorts(30), dim3d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array short[30]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		short[][][] data = (short[][][])builder.getArray();
+		int current = 0; 
+		for( int k=0; k<dim3d[2] ; k++ ){
+			for( int j=0; j<dim3d[1]; j++){
+				for( int i=0; i<dim3d[0]; i++, current++){
+					if( data[i][j][k] != current ){
+						throw new TestException( "data["+i+"]["+j+"]["+k+"]  != " + current ) ;
+					}
+				}
+			}
+		}
+	}
+
+	private static void fill_double_3() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( doubles(30), dim3d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array double[30]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		double[][][] data = (double[][][])builder.getArray();
+		int current = 0; 
+		for( int k=0; k<dim3d[2] ; k++ ){
+			for( int j=0; j<dim3d[1]; j++){
+				for( int i=0; i<dim3d[0]; i++, current++){
+					if( data[i][j][k] != current ){
+						throw new TestException( "data["+i+"]["+j+"]["+k+"]  != " + current ) ;
+					}
+				}
+			}
+		}
+	}
+
+	private static void fill_char_3() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( chars(30), dim3d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array char[30]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		char[][][] data = (char[][][])builder.getArray();
+		int current = 0; 
+		for( int k=0; k<dim3d[2] ; k++ ){
+			for( int j=0; j<dim3d[1]; j++){
+				for( int i=0; i<dim3d[0]; i++, current++){
+					if( data[i][j][k] != current ){
+						throw new TestException( "data["+i+"]["+j+"]["+k+"]  != " + current ) ;
+					}
+				}
+			}
+		}
+	}
+
+	private static void fill_float_3() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( floats(30), dim3d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array float[30]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		float[][][] data = (float[][][])builder.getArray();
+		int current = 0; 
+		for( int k=0; k<dim3d[2] ; k++ ){
+			for( int j=0; j<dim3d[1]; j++){
+				for( int i=0; i<dim3d[0]; i++, current++){
+					if( data[i][j][k] != current ){
+						throw new TestException( "data["+i+"]["+j+"]["+k+"]  != " + current ) ;
+					}
+				}
+			}
+		}
+	}
+	
+	private static void fill_String_3() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( strings(30), dim3d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array String[30]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		String[][][] data = (String[][][])builder.getArray();
+		int current = 0; 
+		for( int k=0; k<dim3d[2] ; k++ ){
+			for( int j=0; j<dim3d[1]; j++){
+				for( int i=0; i<dim3d[0]; i++, current++){
+					if( !data[i][j][k].equals(current+"") ){
+						throw new TestException( "data["+i+"]["+j+"]["+k+"]  != " + current ) ;
+					}
+				}
+			}
+		}
+	}
+
+	private static void fill_Point_3() throws TestException{
+		RectangularArrayBuilder builder = null; 
+		try{
+			builder = new RectangularArrayBuilder( points(30), dim3d );
+		} catch( NotAnArrayException e){
+			throw new TestException( "not an array Point[30]" ) ;
+		} catch( ArrayDimensionException e){
+			throw new TestException( "array dimensionexception" ) ;
+		}
+		
+		DummyPoint[][][] data = (DummyPoint[][][])builder.getArray();
+		int current = 0; 
+		for( int k=0; k<dim3d[2] ; k++ ){
+			for( int j=0; j<dim3d[1]; j++){
+				for( int i=0; i<dim3d[0]; i++, current++){
+					DummyPoint p = data[i][j][k] ;
+					if( p.x != current || p.y != current ){
+						throw new TestException( "data["+i+"]["+j+"]["+k+"].x != " + current ) ;
+					}
+				}
+			}
+		}
+	}
+	// }}}
+	
+	// {{{ 1d array generators 
+	private static int[] ints(int n){
+		int[] x = new int[n];
+		for( int i=0; i<n; i++){
+			x[i] = i ;
+		}
+		return x; 
+	}
+	
+	private static boolean[] booleans(int n){
+		boolean[] x = new boolean[n];
+		boolean current = false; 
+		for( int i=0; i<n; i++, current = !current){
+			x[i] = current ;
+		}
+		return x; 
+	}
+	
+	private static byte[] bytes(int n){
+		byte[] x = new byte[n];
+		for( int i=0; i<n; i++){
+			x[i] = (byte)i ;
+		}
+		return x; 
+	}
+	
+	private static long[] longs(int n){
+		long[] x = new long[n];
+		for( int i=0; i<n; i++){
+			x[i] = (long)i ;
+		}
+		return x; 
+	}
+	
+	private static short[] shorts(int n){
+		short[] x = new short[n];
+		for( int i=0; i<n; i++){
+			x[i] = (short)i ;
+		}
+		return x; 
+	}
+	
+	private static double[] doubles(int n){
+		double[] x = new double[n];
+		for( int i=0; i<n; i++){
+			x[i] = 0.0 + i ;
+		}
+		return x; 
+	}
+	
+	private static char[] chars(int n){
+		char[] x = new char[n];
+		for( int i=0; i<n; i++){
+			x[i] = (char)i ;
+		}
+		return x; 
+	}
+	
+	private static float[] floats(int n){
+		float[] x = new float[n];
+		for( int i=0; i<n; i++){
+			x[i] = 0.0f + i ;
+		}
+		return x; 
+	}
+	
+	private static String[] strings(int n){
+		String[] x = new String[n];
+		for( int i=0; i<n; i++){
+			x[i] = ""+i ;
+		}
+		return x; 
+	}
+	
+	private static DummyPoint[] points(int n){
+		DummyPoint[] x = new DummyPoint[n];
+		for( int i=0; i<n; i++){
+			x[i] = new DummyPoint( i, i ) ;
+		}
+		return x; 
+	}
+	// }}}
+	
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/RectangularArrayExamples.java b/com.oracle.truffle.r.pkgs/rJava/src/java/RectangularArrayExamples.java
new file mode 100644
index 0000000000000000000000000000000000000000..8a09f9c3971bd0cf1fe282ac3b977eb086b9b4cb
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/RectangularArrayExamples.java
@@ -0,0 +1,254 @@
+// :tabSize=2:indentSize=2:noTabs=false:folding=explicit:collapseFolds=1:
+
+/**
+ * Utility class that makes example rectangular java arrays of 2 and 3 dimensions
+ * for all primitive types, String and Point (as an example of array of non primitive object)
+ */
+public class RectangularArrayExamples {
+
+	// {{{ Example 2d rect arrays 
+	public static int[][] getIntDoubleRectangularArrayExample(){
+		int[][] x = new int[5][2]; 
+		int k= 0; 
+		for( int j=0; j<2; j++){
+			for( int i=0; i<5; i++, k++){
+				x[i][j] = k ;
+			}
+		}
+		return x; 
+	}
+	
+	public static boolean[][] getBooleanDoubleRectangularArrayExample(){
+		boolean[][] x = new boolean[5][2]; 
+		boolean current = false;  
+		for( int j=0; j<2; j++){
+			for( int i=0; i<5; i++, current = !current){
+				x[i][j] = current ;
+			}
+		}
+		return x ;
+	}
+	
+	public static byte[][] getByteDoubleRectangularArrayExample(){
+		byte[][] x = new byte[5][2]; 
+		int k= 0; 
+		for( int j=0; j<2; j++){
+			for( int i=0; i<5; i++, k++){
+				x[i][j] = (byte)k ;
+			}
+		}
+		return x; 
+	}
+	
+	public static long[][] getLongDoubleRectangularArrayExample(){
+		long[][] x = new long[5][2]; 
+		int k= 0; 
+		for( int j=0; j<2; j++){
+			for( int i=0; i<5; i++, k++){
+				x[i][j] = (long)k ;
+			}
+		}
+		return x; 
+	}
+	
+	public static short[][] getShortDoubleRectangularArrayExample(){
+		short[][] x = new short[5][2]; 
+		int k= 0; 
+		for( int j=0; j<2; j++){
+			for( int i=0; i<5; i++, k++){
+				x[i][j] = (short)k ;
+			}
+		}
+		return x; 
+	}
+	
+	public static double[][] getDoubleDoubleRectangularArrayExample(){
+		double[][] x = new double[5][2]; 
+		int k= 0; 
+		for( int j=0; j<2; j++){
+			for( int i=0; i<5; i++, k++){
+				x[i][j] = k + 0.0 ;
+			}
+		}
+		return x; 
+	}
+	
+	public static char[][] getCharDoubleRectangularArrayExample(){
+		char[][] x = new char[5][2]; 
+		int k= 0; 
+		for( int j=0; j<2; j++){
+			for( int i=0; i<5; i++, k++){
+				x[i][j] = (char)k ;
+			}
+		}
+		return x; 
+	}
+	
+	public static float[][] getFloatDoubleRectangularArrayExample(){
+		float[][] x = new float[5][2]; 
+		int k= 0; 
+		for( int j=0; j<2; j++){
+			for( int i=0; i<5; i++, k++){
+				x[i][j] = k + 0.0f ;
+			}
+		}
+		return x; 
+	}
+	
+	public static String[][] getStringDoubleRectangularArrayExample(){
+		String[][] x = new String[5][2]; 
+		int k= 0; 
+		for( int j=0; j<2; j++){
+			for( int i=0; i<5; i++, k++){
+				x[i][j] = "" + k ;
+			}
+		}
+		return x; 
+	}
+	
+	public static DummyPoint[][] getDummyPointDoubleRectangularArrayExample(){
+		DummyPoint[][] x = new DummyPoint[5][2]; 
+		int k= 0; 
+		for( int j=0; j<2; j++){
+			for( int i=0; i<5; i++, k++){
+				x[i][j] = new DummyPoint(k,k) ;
+			}
+		}
+		return x; 
+	}
+	// }}}
+	
+	// {{{ Example 3d rect arrays 
+	public static int[][][] getIntTripleRectangularArrayExample(){
+		int[][][] x = new int[5][3][2]; 
+		int current = 0 ;
+		for( int k=0; k<2; k++){
+			for( int j=0; j<3; j++){
+				for( int i=0; i<5; i++, current++){
+					x[i][j][k] = current ;
+				}
+			}
+		}
+		return x; 
+	}
+	
+	public static boolean[][][] getBooleanTripleRectangularArrayExample(){
+		boolean[][][] x = new boolean[5][3][2]; 
+		boolean current = false ;
+		for( int k=0; k<2; k++){
+			for( int j=0; j<3; j++){
+				for( int i=0; i<5; i++, current= !current){
+					x[i][j][k] = current ;
+				}
+			}
+		}
+		return x; 
+	}
+	
+	public static byte[][][] getByteTripleRectangularArrayExample(){
+		byte[][][] x = new byte[5][3][2]; 
+		int current = 0 ;
+		for( int k=0; k<2; k++){
+			for( int j=0; j<3; j++){
+				for( int i=0; i<5; i++, current++){
+					x[i][j][k] = (byte)current ;
+				}
+			}
+		}
+		return x; 
+	}
+	
+	public static long[][][] getLongTripleRectangularArrayExample(){
+		long[][][] x = new long[5][3][2]; 
+		int current = 0 ;
+		for( int k=0; k<2; k++){
+			for( int j=0; j<3; j++){
+				for( int i=0; i<5; i++, current++){
+					x[i][j][k] = (long)current ;
+				}
+			}
+		}
+		return x; 
+	}
+	
+	public static short[][][] getShortTripleRectangularArrayExample(){
+		short[][][] x = new short[5][3][2]; 
+		int current = 0 ;
+		for( int k=0; k<2; k++){
+			for( int j=0; j<3; j++){
+				for( int i=0; i<5; i++, current++){
+					x[i][j][k] = (short)current ;
+				}
+			}
+		}
+		return x; 
+	}
+	
+	public static double[][][] getDoubleTripleRectangularArrayExample(){
+		double[][][] x = new double[5][3][2]; 
+		int current = 0 ;
+		for( int k=0; k<2; k++){
+			for( int j=0; j<3; j++){
+				for( int i=0; i<5; i++, current++){
+					x[i][j][k] = 0.0 + current ;
+				}
+			}
+		}
+		return x; 
+	}
+	
+	public static char[][][] getCharTripleRectangularArrayExample(){
+		char[][][] x = new char[5][3][2]; 
+		int current = 0 ;
+		for( int k=0; k<2; k++){
+			for( int j=0; j<3; j++){
+				for( int i=0; i<5; i++, current++){
+					x[i][j][k] = (char)current ;
+				}
+			}
+		}
+		return x; 
+	}
+	
+	public static float[][][] getFloatTripleRectangularArrayExample(){
+		float[][][] x = new float[5][3][2]; 
+		int current = 0 ;
+		for( int k=0; k<2; k++){
+			for( int j=0; j<3; j++){
+				for( int i=0; i<5; i++, current++){
+					x[i][j][k] = 0.0f + current ;
+				}
+			}
+		}
+		return x; 
+	}
+	
+	public static String[][][] getStringTripleRectangularArrayExample(){
+		String[][][] x = new String[5][3][2]; 
+		int current = 0 ;
+		for( int k=0; k<2; k++){
+			for( int j=0; j<3; j++){
+				for( int i=0; i<5; i++, current++){
+					x[i][j][k] = ""+current ;
+				}
+			}
+		}
+		return x; 
+	}
+	
+	public static DummyPoint[][][] getDummyPointTripleRectangularArrayExample(){
+		DummyPoint[][][] x = new DummyPoint[5][3][2]; 
+		int current = 0 ;
+		for( int k=0; k<2; k++){
+			for( int j=0; j<3; j++){
+				for( int i=0; i<5; i++, current++){
+					x[i][j][k] = new DummyPoint( current, current ) ;
+				}
+			}
+		}
+		return x; 
+	}
+	
+	// }}}
+	
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/RectangularArraySummary.java b/com.oracle.truffle.r.pkgs/rJava/src/java/RectangularArraySummary.java
new file mode 100644
index 0000000000000000000000000000000000000000..754b5106c67ea579f0591995677edfe7504de058
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/RectangularArraySummary.java
@@ -0,0 +1,269 @@
+// :tabSize=2:indentSize=2:noTabs=false:folding=explicit:collapseFolds=1:
+
+import java.lang.reflect.Array ; 
+
+/** 
+ * Utility class to extract something from a rectangular array
+ */
+public class RectangularArraySummary extends RJavaArrayIterator {
+	
+	private int length ; 
+	
+	private String typeName ;
+	
+	private boolean isprimitive ;
+	
+	private Class componentType ;
+	
+	/**
+	 * Constructor
+	 *
+	 * @param array the array to check
+	 * @throws NotAnArrayException if array is not an array
+	 */
+	public RectangularArraySummary(Object array, int[] dimensions) throws NotAnArrayException, NotComparableException {
+		super( dimensions );
+		this.array = array ;
+		typeName = RJavaArrayTools.getObjectTypeName(array );
+		isprimitive = RJavaArrayTools.isPrimitiveTypeName( typeName ) ;
+		try{
+			componentType = RJavaArrayTools.getClassForSignature( typeName , array.getClass().getClassLoader() ) ;
+		} catch( ClassNotFoundException e){}
+		checkComparableObjects() ;
+	}
+	
+	public RectangularArraySummary(Object array, int length ) throws NotAnArrayException, NotComparableException{
+		this( array, new int[]{ length } ); 
+	}
+	
+	/** 
+	 * Iterates over the array to find the minimum value
+	 * (in the sense of the Comparable interface)
+	 */
+	public Object min( boolean narm ) {
+		if( isprimitive ){
+			return null ; // TODO :implement
+		}
+		Object smallest = null ;
+		Object current ;
+		boolean found = false ;
+		
+		if( dimensions.length == 1 ){
+			return( min( (Object[])array, narm ) ) ;
+		} else{
+			
+			/* need to iterate */
+			while( hasNext() ){
+				current = min( (Object[])next(), narm ) ;
+				if( current == null ){
+					if( !narm ) return null ;
+				} else{
+					if( !found ){
+						smallest = current ;
+						found = true ;
+					} else if( smaller( current, smallest ) ) {
+						smallest = current ;
+					}					
+				}
+			}
+			return smallest ;
+		}
+		
+	}
+	
+	/** 
+	 * Iterates over the array to find the maximum value
+	 * (in the sense of the Comparable interface)
+	 */
+	public Object max( boolean narm )  {
+		if( isprimitive ){
+			return null ; // TODO :implement
+		}
+		
+		Object biggest = null ;
+		Object current ;
+		boolean found = false ;
+		
+		if( dimensions.length == 1 ){
+			return( max( (Object[])array, narm ) ) ;
+		} else{
+			
+			/* need to iterate */
+			while( hasNext() ){
+				current = max( (Object[])next(), narm ) ;
+				if( current == null ){
+					if( !narm ) return null ;
+				} else{
+					if( !found ){
+						biggest = current ;
+						found = true ;
+					} else if( bigger( current, biggest) ){ 
+						biggest = current ;
+					}					
+				}
+			}
+			return biggest ;
+		}
+		
+	}
+
+	/** 
+	 * Iterates over the array to find the range of the java array
+	 * (in the sense of the Comparable interface)
+	 */
+	public Object[] range( boolean narm )  {
+		if( isprimitive ){
+			return null ; // TODO :implement
+		}
+		
+		if( dimensions.length == 1 ){
+			return( range( (Object[])array, narm ) ) ;
+		} else{
+			
+			Object[] range = null ;
+			Object[] current ;
+			boolean found = false ;
+		
+			/* need to iterate */
+			while( hasNext() ){
+				current = range( (Object[])next(), narm ) ;
+				if( current == null ){
+					if( !narm ) return null ;
+				} else{
+					if( !found ){
+						range = current ;
+						found = true ;
+					} else {
+						if( bigger( current[1], range[1] ) ){
+							range[1] = current[1] ;
+						}
+						if( smaller( current[0], range[0] ) ){
+							range[0] = current[0] ;
+						}	
+						
+					}
+				}
+			}
+			return range ;
+		}
+		
+	}
+
+	
+	
+	
+	/**
+	 * returns the minimum (in the sense of Comparable) of the 
+	 * objects in the one dimensioned array
+	 */ 
+	private static Object min( Object[] x, boolean narm ){
+		
+		int n = x.length ;
+		Object smallest = null ; 
+		Object current ;
+		boolean found_min = false; 
+		
+		// find somewhere to start from ()
+		for( int i=0; i<n; i++){
+			current = x[i] ;
+			if( current == null ){
+				if( !narm ) return null ;
+			} else{
+				if( !found_min ){
+					smallest = current ;
+					found_min = true ;
+				} else if( ((Comparable)smallest).compareTo(current) > 0 ) {
+					smallest = current ;
+				}
+			}
+		}
+		return smallest ; 
+		
+	}
+	
+	/**
+	 * returns the minimum (in the sense of Comparable) of the 
+	 * objects in the one dimensioned array
+	 */ 
+	private static Object max( Object[] x, boolean narm ){
+		
+		int n = x.length ;
+		Object biggest = null ; 
+		Object current ;
+		boolean found_min = false; 
+		
+		// find somewhere to start from ()
+		for( int i=0; i<n; i++){
+			current = x[i] ;
+			if( current == null ){
+				if( !narm ) return null ;
+			} else{
+				if( !found_min ){
+					biggest = current ;
+					found_min = true ;
+				} else if( ((Comparable)biggest).compareTo(current) < 0 ) {
+					biggest = current ;
+				}
+			}
+		}
+		return biggest ; 
+		
+	}
+
+	/**
+	 * returns the range (in the sense of Comparable) of the 
+	 * objects in the one dimensioned array
+	 */ 
+	private static Object[] range( Object[] x, boolean narm ){
+		
+		int n = x.length ;
+		Object[] range = (Object[])Array.newInstance( x.getClass().getComponentType(), 2) ; 
+		Object current ;
+		boolean found = false; 
+		
+		// find somewhere to start from ()
+		for( int i=0; i<n; i++){
+			current = x[i] ;
+			if( current == null ){
+				if( !narm ) return null ;
+			} else{
+				if( !found ){
+					range[0] = current ;
+					range[1] = current ;
+					found = true ;
+				} else {
+					// max
+					if( ((Comparable)range[1]).compareTo(current) < 0 ) {
+						range[1] = current ;
+					}
+					// min
+					if( ((Comparable)range[0]).compareTo(current) > 0 ) {
+						range[0] = current ;
+					}
+					
+				}
+			}
+		}
+		return range ; 
+		
+	}
+	
+	public void checkComparableObjects() throws NotComparableException {
+		if( ! containsComparableObjects() ) throw new NotComparableException( typeName ) ;
+	}
+	
+	public boolean containsComparableObjects(){
+		return Comparable.class.isAssignableFrom( componentType ) ;
+	}
+	
+	// TODO : use these
+	private static boolean smaller( Object x, Object y){
+		return ( (Comparable)x ).compareTo(y) < 0 ;
+	}
+	private static boolean bigger( Object x, Object y){
+		return ( (Comparable)x ).compareTo(y) > 0 ;
+	}
+	
+	
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/java/TestException.java b/com.oracle.truffle.r.pkgs/rJava/src/java/TestException.java
new file mode 100644
index 0000000000000000000000000000000000000000..0293d1fc660aa8d6e1ec78c96170811885e07a1d
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/java/TestException.java
@@ -0,0 +1,7 @@
+/**
+ * Generated as part of testing rjava internal java tools
+ */
+public class TestException extends Exception{
+	public TestException(String message){super(message);}
+}
+	
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/jri_glue.c b/com.oracle.truffle.r.pkgs/rJava/src/jri_glue.c
new file mode 100644
index 0000000000000000000000000000000000000000..c3e74d4c793eeccec8a265e6200465991bae71ba
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/jri_glue.c
@@ -0,0 +1,60 @@
+#include <R.h>
+#include <Rinternals.h>
+#include "rJava.h"
+
+/* creates a reference to an R object on the Java side 
+   1) lock down the object in R
+   2) call new Rengine(eng,robj) {or any other class such as REXPReference for REngine API}
+ */
+REPC SEXP PushToREXP(SEXP clname, SEXP eng, SEXP engCl, SEXP robj, SEXP doConv) {
+  char sig[128];
+  jvalue jpar[4];
+  jobject o;
+  int convert = (doConv == R_NilValue) ? -1 : asInteger(doConv);
+  JNIEnv *env=getJNIEnv();
+  const char *cName;
+  
+  if (!isString(clname) || LENGTH(clname)!=1) error("invalid class name");
+  if (!isString(engCl) || LENGTH(engCl)!=1) error("invalid engine class name");
+  if (TYPEOF(eng)!=EXTPTRSXP) error("invalid engine object");
+  R_PreserveObject(robj);
+  sig[127]=0;
+  cName = CHAR(STRING_ELT(clname,0));
+  jpar[0].l = (jobject)EXTPTR_PTR(eng);
+  jpar[1].j = (jlong) robj;
+  if (convert == -1)
+    snprintf(sig,127,"(L%s;J)V",CHAR(STRING_ELT(engCl,0)));
+  else {
+    snprintf(sig,127,"(L%s;JZ)V",CHAR(STRING_ELT(engCl,0)));
+    jpar[2].z = (jboolean) convert;
+  }
+  o = createObject(env, cName, sig, jpar, 1, 0);
+  if (!o) error("Unable to create Java object");
+  return j2SEXP(env, o, 1);
+  /* ok, some thoughts on mem mgmt - j2SEXP registers a finalizer. But I believe that is ok, because the pushed reference is useless until it is passed as an argument to some Java method. And then, it will have another reference which will prevent the Java side from being collected. The R-side reference may be gone, but that's ok, because it's the Java finalizer that needs to clean up the pushed R object and for that it doesn't need the proxy object at all. This is the reason why RReleaseREXP uses EXTPTR - all the Java finalizaer has to do is to call RReleaseREXP(self). For that it can create a fresh proxy object containing the REXP. But here comes he crux - this proxy cannot again create a reference - it must be plain pass-through, so this part needs to be verified.
+
+Note: as of REngine API the references assume protected objects and use rniRelease to clean up, so RReleaseREXP won't be called and is not needed. That is good, because RReleaseREXP assumes JRI objects whereas REngine will create REXPReference (no xp there). However, if we ever change that REXPReference assumption we will be in trouble.
+ */
+}
+
+/* this is pretty much hard-coded for now - it's picking "xp" attribute */
+REPC SEXP RReleaseREXP(SEXP ptr) {
+  jobject o;
+  if (TYPEOF(ptr)==EXTPTRSXP) error("invalid object");
+  o = (jobject)EXTPTR_PTR(ptr);
+  {
+    JNIEnv *env = getJNIEnv();
+    jclass cls = (*env)->GetObjectClass(env, o);
+    if (cls) {
+      jfieldID fid=(*env)->GetFieldID(env,cls,"xp","J");
+      if (fid) {
+	jlong r = (*env)->GetLongField(env, o, fid);
+	SEXP x = (SEXP) r;
+	if (x) R_ReleaseObject(x);
+      }
+    }
+  }
+  return R_NilValue;
+}
+
+    
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/jvm-w32/Makefile b/com.oracle.truffle.r.pkgs/rJava/src/jvm-w32/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..e4d895d0fd7e5eb0026e1ab2b122f0ae7740236a
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/jvm-w32/Makefile
@@ -0,0 +1,33 @@
+# helper tools and libs for building and running rJava for Windows
+# Author: Simon Urbanek
+#         with contributions from Brian Ripley
+
+include $(R_HOME)/etc$(R_ARCH)/Makeconf
+
+TARGETS=libjvm.dll.a findjava.exe
+
+# libjvm.dll.a    - wrapper lib for jvm.dll from Java
+# findjava.exe    - helper tool to find the current JDK from the registry
+
+all: $(TARGETS)
+
+# detect 64-bit Windows
+ifeq ($(strip $(shell $(R_HOME)/bin/R --slave -e 'cat(.Machine$$sizeof.pointer)')),8)
+JVM64DEF=64
+endif
+
+libjvm.dll.a: jvm$(JVM64DEF).def
+	$(DLLTOOL) --input-def $^ --kill-at --dllname jvm.dll --output-lib $@
+
+# compile findjava.exe from source - no magic here, no special libs necessary
+findjava.o: findjava.c
+	$(CC) -O2 -c -o $@ $^
+
+findjava.exe: findjava.o
+	$(CC) -s -o $@ $^
+
+# just cleanup everything
+clean:
+	rm -f *.o *~ $(TARGETS)
+
+.PHONY: all clean
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/jvm-w32/WinRegistry.c b/com.oracle.truffle.r.pkgs/rJava/src/jvm-w32/WinRegistry.c
new file mode 100644
index 0000000000000000000000000000000000000000..0b3bc7f1ecccde415dcfc0f0a188257373775836
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/jvm-w32/WinRegistry.c
@@ -0,0 +1,34 @@
+#include <Rinternals.h>
+
+#ifdef WIN32
+#include <windows.h>
+#include <winreg.h>
+
+char RegStrBuf[32768];
+
+SEXP RegGetStrValue(SEXP par) {
+  SEXP res=R_NilValue;
+  DWORD t,s=32767;
+  HKEY k;
+  char *key=CHAR(STRING_ELT(par, 0));
+  char *val=CHAR(STRING_ELT(par, 1));
+
+  RegStrBuf[32767]=*RegStrBuf=0;
+  /* printf("RegGetStrValue(\"%s\",\"%s\")\n",key,val); */
+
+  if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,key,0,KEY_QUERY_VALUE,&k)!=ERROR_SUCCESS ||
+      RegQueryValueEx(k,val,0,&t,RegStrBuf,&s)!=ERROR_SUCCESS)
+    return res;
+  
+  PROTECT(res = allocVector(STRSXP, 1));
+  SET_STRING_ELT(res, 0, mkChar(RegStrBuf));
+  UNPROTECT(1);
+
+  return res;
+};
+
+#else
+/* all functions return NULL since they are not supported on non-Win32 platforms */
+SEXP RegGetStrValue(SEXP par) { return R_NilValue; };
+
+#endif
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/jvm-w32/config.h b/com.oracle.truffle.r.pkgs/rJava/src/jvm-w32/config.h
new file mode 100644
index 0000000000000000000000000000000000000000..5ad5eae63d006573b3d83863c7dcf9a655df6a7d
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/jvm-w32/config.h
@@ -0,0 +1,4 @@
+/* fall-back setting on Widnows */
+
+/* assume Sun/Oracle JVM which supports -Xrs */
+#define HAVE_XRS 1
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/jvm-w32/findjava.c b/com.oracle.truffle.r.pkgs/rJava/src/jvm-w32/findjava.c
new file mode 100644
index 0000000000000000000000000000000000000000..8335411059edef088b7b37c37256e4928bc18327
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/jvm-w32/findjava.c
@@ -0,0 +1,82 @@
+#include <windows.h>
+#include <winreg.h>
+#include <stdio.h>
+
+static char RegStrBuf[32768], dbuf[32768];
+
+int main(int argc, char **argv) {
+  int i=0, doit=0;
+  DWORD t,s=32767;
+  HKEY k;
+  HKEY root=HKEY_LOCAL_MACHINE;
+  char *javakey="Software\\JavaSoft\\Java Runtime Environment";
+
+  /* JAVA_HOME can override our detection - but we still post-process it */
+  if (getenv("JAVA_HOME")) {
+    strcpy(RegStrBuf,getenv("JAVA_HOME"));
+  } else {
+
+#ifdef FINDJRE
+    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,javakey,0,KEY_QUERY_VALUE,&k)!=ERROR_SUCCESS ||
+	RegQueryValueEx(k,"CurrentVersion",0,&t,RegStrBuf,&s)!=ERROR_SUCCESS) {
+#endif
+      javakey="Software\\JavaSoft\\Java Development Kit"; s=32767;
+      if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,javakey,0,KEY_QUERY_VALUE,&k)!=ERROR_SUCCESS ||
+	  RegQueryValueEx(k,"CurrentVersion",0,&t,RegStrBuf,&s)!=ERROR_SUCCESS) {
+	fprintf(stderr, "ERROR*> JavaSoft\\{JRE|JDK} can't open registry keys.\n");
+	/* MessageBox(wh, "Can't find Sun's Java runtime.\nPlease install Sun's J2SE JRE or JDK 1.4.2 or later (see http://java.sun.com/).","Can't find Sun's Java",MB_OK|MB_ICONERROR); */
+	return -1;
+      }
+#ifdef FINDJRE
+    }
+#endif
+    RegCloseKey(k); s=32767;
+
+    strcpy(dbuf,javakey);
+    strcat(dbuf,"\\");
+    strcat(dbuf,RegStrBuf);
+    javakey=(char*) malloc(strlen(dbuf)+1);
+    strcpy(javakey, dbuf);
+    
+    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,javakey,0,KEY_QUERY_VALUE,&k)!=ERROR_SUCCESS ||
+	RegQueryValueEx(k,"JavaHome",0,&t,RegStrBuf,&s)!=ERROR_SUCCESS) {
+      fprintf(stderr, "There's no JavaHome value in the JDK/JRE registry key.\n");
+      /* MessageBox(wh, "Can't find Java home path. Maybe your JRE is too old.\nPlease install Sun's J2SE JRE or SDK 1.4.2 (see http://java.sun.com/).","Can't find Sun's Java",MB_OK|MB_ICONERROR); */
+      return -1;
+    }
+    RegCloseKey(k);
+  }
+  
+  /*--- post-processing according to supplied flags --*/
+
+  /* -a = automagic, i.e. use short name only if the name contains spaces */
+  i=1;
+  while (i<argc) if (!strcmp(argv[i++],"-a")) { doit=1; break; };
+  if (doit) {
+    int hasws=0;
+    char *c=dbuf;
+    while (*c) { if (*c==' '||*c=='\t') { hasws=1; break; } c++; };
+    if (!hasws) doit=0;
+  }
+
+  /* -s = short name */
+  if (!doit) {
+    i=1;
+    while (i<argc) if (!strcmp(argv[i++],"-s")) { doit=1; break; };
+  }
+  strcpy(dbuf, RegStrBuf);
+  if (doit)
+    GetShortPathName(RegStrBuf, dbuf, 32768);
+
+  /* -f = forward slashes */
+  doit=0; i=1;
+  while (i<argc) if (!strcmp(argv[i++],"-f")) { doit=1; break; };
+  if (doit) {
+    char *c=dbuf;
+    while (*c) { if (*c=='\\') *c='/'; c++; };
+  }
+
+  puts(dbuf);
+  return 0;
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/jvm-w32/jvm.def b/com.oracle.truffle.r.pkgs/rJava/src/jvm-w32/jvm.def
new file mode 100644
index 0000000000000000000000000000000000000000..b27b1bc8b44cc5b931161ba2c5f6ed0a0224b84b
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/jvm-w32/jvm.def
@@ -0,0 +1,6 @@
+LIBRARY     JVM.DLL
+
+EXPORTS
+    JNI_CreateJavaVM@12
+    JNI_GetCreatedJavaVMs@12
+    JNI_GetDefaultJavaVMInitArgs@4
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/jvm-w32/jvm64.def b/com.oracle.truffle.r.pkgs/rJava/src/jvm-w32/jvm64.def
new file mode 100644
index 0000000000000000000000000000000000000000..343b82fe4d3557169aae994d8101a2086de44b20
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/jvm-w32/jvm64.def
@@ -0,0 +1,6 @@
+LIBRARY     JVM.DLL
+
+EXPORTS
+    JNI_CreateJavaVM
+    JNI_GetCreatedJavaVMs
+    JNI_GetDefaultJavaVMInitArgs
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/loader.c b/com.oracle.truffle.r.pkgs/rJava/src/loader.c
new file mode 100644
index 0000000000000000000000000000000000000000..f1c08ebafd31674096ace2a71fbe8fe80d51b994
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/loader.c
@@ -0,0 +1,91 @@
+/* functions dealing with the rJava class loader
+ *
+ * rJava R/Java interface  (C)Copyright 2003-2007 Simon Urbanek
+ * (see rJava project root for licensing details)
+ */
+
+#include "rJava.h"
+
+jclass   clClassLoader = (jclass) 0;
+jobject  oClassLoader = (jobject) 0;
+
+HIDE int initClassLoader(JNIEnv *env, jobject cl) {
+  clClassLoader = (*env)->NewGlobalRef(env, (*env)->GetObjectClass(env, cl));
+  /* oClassLoader = (*env)->NewGlobalRef(env, cl); */ 
+  oClassLoader = cl;
+#ifdef DEBUG_CL
+  printf("initClassLoader: cl=%x, clCl=%x, jcl=%x\n", oClassLoader, clClassLoader, javaClassClass);
+#endif
+  return 0;
+}
+
+REPC SEXP RJava_set_class_loader(SEXP ldr) {
+  JNIEnv *env=getJNIEnv();
+  if (TYPEOF(ldr) != EXTPTRSXP)
+    error("invalid type");
+  if (!env)
+    error("VM not initialized");
+  
+  jverify(ldr);
+  initClassLoader(env, (jobject)EXTPTR_PTR(ldr));
+  return R_NilValue;
+}
+
+REPC SEXP RJava_primary_class_loader() {
+  JNIEnv *env=getJNIEnv();
+  jclass cl = (*env)->FindClass(env, "RJavaClassLoader");
+  _dbg(Rprintf("RJava_primary_class_loader, cl = %x\n", (int) cl));
+  if (cl) {
+    jmethodID mid = (*env)->GetStaticMethodID(env, cl, "getPrimaryLoader", "()LRJavaClassLoader;");
+    _dbg(Rprintf(" - mid = %d\n", (int) mid));
+    if (mid) {
+      jobject o = (*env)->CallStaticObjectMethod(env, cl, mid);
+      _dbg(Rprintf(" - call result = %x\n", (int) o));
+      if (o) {
+	return j2SEXP(env, o, 1);
+      }
+    }
+  }
+  checkExceptionsX(env, 1);
+
+#ifdef NEW123
+  jclass cl = (*env)->FindClass(env, "JRIBootstrap");
+  Rprintf("RJava_primary_class_loader, cl = %x\n", (int) cl);
+  if (cl) {
+    jmethodID mid = (*env)->GetStaticMethodID(env, cl, "getBootRJavaLoader", "()Ljava/lang/Object;");
+    Rprintf(" - mid = %d\n", (int) mid);
+    if (mid) {
+      jobject o = (*env)->CallStaticObjectMethod(env, cl, mid);
+      Rprintf(" - call result = %x\n", (int) o);
+      if (o) {
+	return j2SEXP(env, o, 1);
+      }
+    }
+  }
+  checkExceptionsX(env, 1);
+#endif
+  return R_NilValue; 
+}
+
+REPC SEXP RJava_new_class_loader(SEXP p1, SEXP p2) {
+  JNIEnv *env=getJNIEnv();
+  
+  const char *c1 = CHAR(STRING_ELT(p1, 0));
+  const char *c2 = CHAR(STRING_ELT(p2, 0));
+  jstring s1 = newString(env, c1);
+  jstring s2 = newString(env, c2);
+
+  jclass cl = (*env)->FindClass(env, "RJavaClassLoader");
+  _dbg(Rprintf("find rJavaClassLoader: %x\n", (int) cl));
+  jmethodID mid = (*env)->GetMethodID(env, cl, "<init>", "(Ljava/lang/String;Ljava/lang/String;)V");
+  _dbg(Rprintf("constructor mid: %x\n", mid));
+  jobject o = (*env)->NewObject(env, cl, mid, s1, s2);
+  _dbg(Rprintf("new object: %x\n", o));
+  o = makeGlobal(env, o);
+  _dbg(Rprintf("calling initClassLoader\n"));
+  initClassLoader(env, o);
+  releaseObject(env, s1);
+  releaseObject(env, s2);
+  releaseObject(env, cl);
+  return R_NilValue;
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/otables.c b/com.oracle.truffle.r.pkgs/rJava/src/otables.c
new file mode 100644
index 0000000000000000000000000000000000000000..216db9572a62b4ad3ae273738cf8ed644b11e96e
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/otables.c
@@ -0,0 +1,241 @@
+#include "rJava.h"
+
+#define RJAVA_LOOKUP 23
+
+/* This uses the mechanism of the RObjectTables package
+   see: http://www.omegahat.org/RObjectTables/ */
+
+/**
+ * Returns the R_UnboundValue
+ */
+HIDE SEXP R_getUnboundValue() {
+    return(R_UnboundValue);
+}
+
+/**
+ * @param name name of a java class
+ * @param canCache Can R cache this object
+ * @param tb 
+ * @return TRUE if the a class called name exists in on of the packages
+ */
+/* not actually used by R */
+HIDE Rboolean rJavaLookupTable_exists(const char * const name, Rboolean *canCache, R_ObjectTable *tb){
+
+#ifdef LOOKUP_DEBUG
+ Rprintf( "  >> rJavaLookupTable_exists\n" ); 
+#endif
+	
+ if(tb->active == FALSE)
+    return(FALSE);
+
+ tb->active = FALSE;
+ Rboolean val = classNameLookupExists( tb, name );
+ tb->active = TRUE;
+ 
+ return( val );
+}
+
+/**
+ * Returns a new jclassName object if the class exists or the 
+ * unbound value if it does not
+ *
+ * @param name class name
+ * @param canCache ?? 
+ * @param tb lookup table
+ */
+SEXP rJavaLookupTable_get(const char * const name, Rboolean *canCache, R_ObjectTable *tb){
+
+#ifdef LOOKUP_DEBUG
+ Rprintf( "  >> rJavaLookupTable_get\n" ); 
+#endif
+
+ SEXP val;
+ if(tb->active == FALSE)
+    return(R_UnboundValue);
+
+ tb->active = FALSE;
+ val = PROTECT( classNameLookup( tb, name ) );
+ tb->active = TRUE;
+
+ UNPROTECT(1); /* val */ 
+ return(val);
+}
+
+/**
+ * Does nothing. Not applicable to java packages
+ */
+int rJavaLookupTable_remove(const char * const name,  R_ObjectTable *tb){
+#ifdef LOOKUP_DEBUG
+ Rprintf( "  >> rJavaLookupTable_remove( %s) \n", name ); 
+#endif
+	error( "cannot remove from java package" ) ;
+	return 0;
+}
+
+/**
+ * Indicates if R can cahe the variable name. 
+ * Currently allways return FALSE
+ *
+ * @param name name of the class
+ * @param tb lookup table
+ * @return allways FALSE (for now)
+ */ 
+HIDE Rboolean rJavaLookupTable_canCache(const char * const name, R_ObjectTable *tb){
+#ifdef LOOKUP_DEBUG
+ Rprintf( "  >> rJavaLookupTable_canCache\n" ); 
+#endif
+	return( FALSE );
+}
+
+/**
+ * Generates an error. assign is not possible on our lookup table
+ */
+HIDE SEXP rJavaLookupTable_assign(const char * const name, SEXP value, R_ObjectTable *tb){
+#ifdef LOOKUP_DEBUG
+ Rprintf( "  >> rJavaLookupTable_assign( %s ) \n", name ); 
+#endif
+    error("can't assign to java package lookup");
+    return R_NilValue;
+}
+
+/**
+ * Returns the list of classes known to be included in the 
+ * packages. Currently returns NULL
+ *
+ * @param tb lookup table
+ */ 
+HIDE SEXP rJavaLookupTable_objects(R_ObjectTable *tb) {
+#ifdef LOOKUP_DEBUG
+ Rprintf( "  >> rJavaLookupTable_objects\n" ); 
+#endif
+	
+	tb->active = FALSE;
+	SEXP res = PROTECT( getKnownClasses( tb ) ) ; 
+	tb->active = TRUE;
+	UNPROTECT(1); /* res */
+	return( res ); 
+}
+
+
+REPC SEXP newRJavaLookupTable(SEXP importer){
+#ifdef LOOKUP_DEBUG
+ Rprintf( "<newRJavaLookupTable>\n" ); 
+#endif
+
+ R_ObjectTable *tb;
+ SEXP val, klass;
+
+  tb = (R_ObjectTable *) malloc(sizeof(R_ObjectTable));
+  if(!tb)
+      error( "cannot allocate space for an internal R object table" );
+  
+  tb->type = RJAVA_LOOKUP ; /* FIXME: not sure what this should be */
+  tb->cachedNames = NULL;
+  
+  R_PreserveObject(importer); 
+  tb->privateData = importer; 
+
+  tb->exists = rJavaLookupTable_exists;
+  tb->get = rJavaLookupTable_get;
+  tb->remove = rJavaLookupTable_remove;
+  tb->assign = rJavaLookupTable_assign;
+  tb->objects = rJavaLookupTable_objects;
+  tb->canCache = rJavaLookupTable_canCache;
+
+  tb->onAttach = NULL;
+  tb->onDetach = NULL;
+
+  PROTECT(val = R_MakeExternalPtr(tb, install("UserDefinedDatabase"), R_NilValue));
+  PROTECT(klass = NEW_CHARACTER(1));
+   SET_STRING_ELT(klass, 0, COPY_TO_USER_STRING("UserDefinedDatabase"));
+   SET_CLASS(val, klass);
+  UNPROTECT(2);
+
+#ifdef LOOKUP_DEBUG
+ Rprintf( "</newRJavaLookupTable>\n" ); 
+#endif
+  return(val);
+}
+
+
+HIDE jobject getImporterReference(R_ObjectTable *tb ){
+	jobject res = (jobject)EXTPTR_PTR( GET_SLOT( (SEXP)(tb->privateData), install( "jobj" ) ) );
+	
+#ifdef LOOKUP_DEBUG
+	Rprintf( "  >> getImporterReference : [%d]\n", res ); 
+#endif
+	return res ;
+}
+
+HIDE SEXP getKnownClasses( R_ObjectTable *tb ){
+#ifdef LOOKUP_DEBUG
+ Rprintf( "  >> getKnownClasses\n" ); 
+#endif
+	jobject importer = getImporterReference(tb); 
+	
+	JNIEnv *env=getJNIEnv();
+	jarray a = (jarray) (*env)->CallObjectMethod(env, importer, mid_RJavaImport_getKnownClasses ) ;
+	SEXP res = PROTECT( getStringArrayCont( a ) ) ;
+	
+#ifdef LOOKUP_DEBUG
+ Rprintf( "    %d known classes\n", LENGTH(res) ); 
+#endif
+	
+	UNPROTECT(1); 
+	return res ;
+}
+
+HIDE SEXP classNameLookup( R_ObjectTable *tb, const char * const name ){
+#ifdef LOOKUP_DEBUG
+ Rprintf( " >> classNameLookup\n" ); 
+#endif
+	JNIEnv *env=getJNIEnv();
+	
+	jobject importer = getImporterReference(tb); 
+
+	jobject clazz = newString(env, name ) ;
+	jstring s ; /* Class */
+	s = (jstring) (*env)->CallObjectMethod(env, importer, mid_RJavaImport_lookup, clazz ) ;
+	SEXP res ;
+	int np ;
+	if( !s ){
+		res = R_getUnboundValue() ;
+		np = 0; 
+	} else{
+		PROTECT( res = new_jclassName( env, s ) );
+		np = 1; 
+	}
+
+	releaseObject(env, clazz);
+	releaseObject(env, s);
+    
+	if( np ) UNPROTECT(1); 
+#ifdef LOOKUP_DEBUG
+ Rprintf( "</classNameLookup>\n" ); 
+#endif
+	return res ; 
+}
+
+HIDE Rboolean classNameLookupExists(R_ObjectTable *tb, const char * const name ){
+#ifdef LOOKUP_DEBUG
+ Rprintf( " classNameLookupExists\n" ); 
+#endif
+	
+	JNIEnv *env=getJNIEnv();
+	
+	jobject importer = getImporterReference(tb); 
+	jobject clazz = newString(env, name ) ;
+	
+	jboolean s ; /* Class */
+	s = (jboolean) (*env)->CallBooleanMethod(env, importer, 
+		mid_RJavaImport_exists , clazz ) ;
+	Rboolean res = (s) ? TRUE : FALSE; 
+
+#ifdef LOOKUP_DEBUG
+ Rprintf( "    exists( %s ) = %d \n", name, res ); 
+#endif
+	
+	releaseObject(env, clazz);
+    return res ;
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/rJava.c b/com.oracle.truffle.r.pkgs/rJava/src/rJava.c
new file mode 100644
index 0000000000000000000000000000000000000000..9843a21d40928917f429f193a5d11ade1faa2791
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/rJava.c
@@ -0,0 +1,222 @@
+#include <R.h>
+#include <Rversion.h>
+#include <Rdefines.h>
+#include "rJava.h"
+#include <stdlib.h>
+#include <string.h>
+
+/* determine whether eenv chache should be used (has no effect if JNI_CACHE is not set) */
+int use_eenv = 1;
+
+/* cached environment. Do NOT use directly! Always use getJNIEnv()! */
+JNIEnv *eenv;
+
+/* -- hack to get at the current call from C code using contexts */
+#if ( R_VERSION >= R_Version(1, 7, 0) )
+#include <setjmp.h>
+
+/* stuff we need to pull for Windows... */
+#ifdef WIN32
+/* this is from gnuwin32/fixed/h/psignal.h */
+#ifndef _SIGSET_T_
+#define _SIGSET_T_
+typedef int sigset_t;
+#endif  /* Not _SIGSET_T_ */
+typedef struct
+{    
+  jmp_buf jmpbuf;     /* Calling environment.  */  
+  int mask_was_saved;       /* Saved the signal mask?  */                   
+  sigset_t saved_mask;      /* Saved signal mask.  */                       
+} sigjmp_buf[1];
+/* we need to set HAVE_POSIX_SETJMP since we don't have config.h on Win */
+#ifndef HAVE_POSIX_SETJMP
+#define HAVE_POSIX_SETJMP
+#endif
+#endif
+
+#ifdef HAVE_POSIX_SETJMP
+#define JMP_BUF sigjmp_buf
+#else
+#define JMP_BUF jmp_buf
+#endif
+
+#ifndef CTXT_BUILTIN
+#define CTXT_BUILTIN 64
+#endif
+
+typedef struct RCNTXT { /* this RCNTXT structure is only partial since we need to get at "call" - it is safe form R 1.7.0 on */
+	struct RCNTXT *nextcontext; /* The next context up the chain <<-- we use this one to skip the .Call/.External call frame */
+	int callflag;               /* The context "type" <<<-- we use this one to skip the .Call/.External call frame */
+	JMP_BUF cjmpbuf;            /* C stack and register information */
+	int cstacktop;              /* Top of the pointer protection stack */
+	int evaldepth;              /* evaluation depth at inception */
+	SEXP promargs;              /* Promises supplied to closure */
+	SEXP callfun;               /* The closure called */
+	SEXP sysparent;             /* environment the closure was called from */
+	SEXP call;                  /* The call that effected this context <<<--- we pass this one to the condition */
+	SEXP cloenv;                /* The environment */
+} RCNTXT;
+
+#ifndef LibExtern
+#define LibExtern extern
+#endif
+
+LibExtern RCNTXT* R_GlobalContext;
+
+static SEXP getCurrentCall() {
+	RCNTXT *ctx = R_GlobalContext;
+	/* skip the .External/.Call context to get at the underlying call */
+	if (ctx->nextcontext && (ctx->callflag & CTXT_BUILTIN))
+		ctx = ctx->nextcontext;
+	/* skip .jcheck */
+	if (TYPEOF(ctx->call) == LANGSXP && CAR(ctx->call) == install(".jcheck") && ctx->nextcontext)
+		ctx = ctx->nextcontext;		
+	return ctx->call;
+}
+#else
+static SEXP getCurrentCall() {
+	return R_NilValue;
+}
+#endif
+/* -- end of hack */
+
+/** throw an exception using R condition code.
+ *  @param msg - message string
+ *  @param jobj - jobjRef object of the exception 
+ *  @param clazzes - simple name of all the classes in the inheritance tree of the exception plus "error" and "condition"
+ */
+HIDE void throwR(SEXP msg, SEXP jobj, SEXP clazzes) {
+	SEXP cond = PROTECT(allocVector(VECSXP, 3));
+	SEXP names = PROTECT(allocVector(STRSXP, 3));
+	SET_VECTOR_ELT(cond, 0, msg);
+	SET_VECTOR_ELT(cond, 1, getCurrentCall());
+	SET_VECTOR_ELT(cond, 2, jobj);
+	SET_STRING_ELT(names, 0, mkChar("message"));
+	SET_STRING_ELT(names, 1, mkChar("call"));
+	SET_STRING_ELT(names, 2, mkChar("jobj"));
+	
+	setAttrib(cond, R_NamesSymbol, names);
+	setAttrib(cond, R_ClassSymbol, clazzes);
+	UNPROTECT(2); /* clazzes, names */
+	eval(LCONS(install("stop"), CONS(cond, R_NilValue)), R_GlobalEnv);
+	UNPROTECT(1); /* cond */
+}
+
+/* check for exceptions and throw them to R level */
+HIDE void ckx(JNIEnv *env) {
+	SEXP xr, xobj, msg = 0, xclass = 0; /* note: we don't bother counting protections becasue we never return */
+	jthrowable x = 0;
+	if (env && !(x = (*env)->ExceptionOccurred(env))) return;
+	if (!env) {
+		env = getJNIEnv();
+		if (!env)
+			error("Unable to retrieve JVM environment.");
+		ckx(env);
+		return;
+	}
+	/* env is valid and an exception occurred */
+	/* we create the jobj first, because the exception may in theory disappear after being cleared, 
+	   yet this can be (also in theory) risky as it uses further JNI calls ... */
+	xobj = j2SEXP(env, x, 0);
+	(*env)->ExceptionClear(env);
+	
+	/* grab the list of class names (without package path) */
+	SEXP clazzes = PROTECT( getSimpleClassNames_asSEXP( (jobject)x, (jboolean)1 ) ) ;
+	
+	/* ok, now this is a critical part that we do manually to avoid recursion */
+	{
+		jclass cls = (*env)->GetObjectClass(env, x);
+		if (cls) {
+			jstring cname;
+			jmethodID mid = (*env)->GetMethodID(env, cls, "toString", "()Ljava/lang/String;");
+			if (mid) {
+				jstring s = (jstring)(*env)->CallObjectMethod(env, x, mid);
+				if (s) {
+					const char *c = (*env)->GetStringUTFChars(env, s, 0);
+					if (c) {
+						msg = PROTECT(mkString(c));
+						(*env)->ReleaseStringUTFChars(env, s, c);
+					}
+				}
+			}
+			/* beside toString() we also need to call getName() on cls to get the subclass */
+			cname = (jstring) (*env)->CallObjectMethod(env, cls, mid_getName);
+			if (cname) {
+				const char *c = (*env)->GetStringUTFChars(env, cname, 0);
+				if (c) {                          
+					/* convert full class name to JNI notation */
+					char *cn = strdup(c), *d = cn;
+					while (*d) { if (*d == '.') *d = '/'; d++; }
+					xclass = mkString(cn);
+					free(cn);
+					(*env)->ReleaseStringUTFChars(env, cname, c);
+				}		
+				(*env)->DeleteLocalRef(env, cname);
+			}
+			if ((*env)->ExceptionOccurred(env))
+				(*env)->ExceptionClear(env);
+			(*env)->DeleteLocalRef(env, cls);
+		} else (*env)->ExceptionClear(env);
+		if (!msg)
+			msg = PROTECT(mkString("Java Exception <no description because toString() failed>"));
+	}
+	/* delete the local reference to the exception (jobjRef has a global copy) */
+	(*env)->DeleteLocalRef(env, x);
+
+	/* construct the jobjRef */
+	xr = PROTECT(NEW_OBJECT(MAKE_CLASS("jobjRef")));
+	if (inherits(xr, "jobjRef")) {
+		SET_SLOT(xr, install("jclass"), xclass ? xclass : mkString("java/lang/Throwable"));
+		SET_SLOT(xr, install("jobj"), xobj);
+	}
+	
+	/* and off to R .. (we're keeping xr and clazzes protected) */
+	throwR(msg, xr, clazzes);
+	/* throwR never returns so don't even bother ... */
+}
+
+/* clear any pending exceptions */
+HIDE void clx(JNIEnv *env) {
+	if (env && (*env)->ExceptionOccurred(env))
+		(*env)->ExceptionClear(env);
+}
+
+#ifdef JNI_CACHE
+HIDE JNIEnv *getJNIEnvSafe();
+HIDE JNIEnv *getJNIEnv() {
+  return (use_eenv)?eenv:getJNIEnvSafe();
+}
+
+HIDE JNIEnv *getJNIEnvSafe()
+#else
+HIDE JNIEnv *getJNIEnv()
+#endif
+  {
+    JNIEnv *env;
+    jsize l;
+    jint res;
+
+    if (!jvm) { /* we're hoping that the JVM pointer won't change :P we fetch it just once */
+        res = JNI_GetCreatedJavaVMs(&jvm, 1, &l);
+        if (res != 0) {
+            error("JNI_GetCreatedJavaVMs failed! (result:%d)",(int)res); return 0;
+        }
+        if (l < 1)
+	    error("No running JVM detected. Maybe .jinit() would help.");
+	if (!rJava_initialized)
+	    error("rJava was called from a running JVM without .jinit().");
+    }
+    res = (*jvm)->AttachCurrentThread(jvm, (void**) &env, 0);
+    if (res!=0) {
+      error("AttachCurrentThread failed! (result:%d)", (int)res); return 0;
+    }
+    if (env && !eenv) eenv=env;
+    
+    /* if (eenv!=env)
+        fprintf(stderr, "Warning! eenv=%x, but env=%x - different environments encountered!\n", eenv, env); */
+    return env;
+}
+
+REP void RuseJNICache(int *flag) {
+  if (flag) use_eenv=*flag;
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/rJava.h b/com.oracle.truffle.r.pkgs/rJava/src/rJava.h
new file mode 100644
index 0000000000000000000000000000000000000000..1c8d7c4c0b247b336300e124636035a97a965ee9
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/rJava.h
@@ -0,0 +1,231 @@
+#ifndef __RJAVA_H__
+#define __RJAVA_H__
+
+#define RJAVA_VER 0x000909 /* rJava v0.9-9 */
+
+/* important changes between versions:
+   3.0  - adds compiler
+   2.0
+   1.0
+   0.9  - rectangular arrays, flattening, import
+          (really introduced in later 0.8 versions but they broke
+	   the API compatibility so 0.9 attempts to fix that)
+   0.8  - new exception handling using Exception condition
+   0.7  - new reflection code, new REngine API (JRI)
+   0.6  - adds serialization, (auto-)deserialization and cache
+   0.5  - integrates JRI, adds callbacks and class-loader
+   0.4  - includes JRI
+   0.3  - uses EXTPTR in jobj slot, adds finalizers
+   0.2  - uses S4 classes
+   0.1  - first public release */
+
+#include <jni.h>
+#include <R.h>
+#include <Rinternals.h>
+#include <Rversion.h>
+
+#include <Rdefines.h>
+#include <R_ext/Callbacks.h>
+
+/* flags used in function declarations:
+   HIDE - hidden (used internally in rJava only)
+
+   REP  - R Entry Point - .C convention
+   REPE - R Entry Point - .External convention
+   REPC - R Entry Point - .Call convention
+
+   - inline and/or hide functions that are not externally visible
+   - automatically generate symbol registration table
+ */
+#ifdef ONEFILE
+#ifdef HAVE_STATIC_INLINE
+#define HIDE static inline
+#else
+#define HIDE static
+#endif
+#else
+#define HIDE
+#endif
+#define REP
+#define REPE
+#define REPC
+
+#if defined WIN32 && ! defined Win32
+#define Win32
+#endif
+#if defined Win32 && ! defined WIN32
+#define WIN32
+#endif
+
+#include "config.h"
+
+#ifdef MEMPROF
+#include <stdio.h>
+#include <time.h>
+extern FILE* memprof_f;
+#define _mp(X) X
+#define MEM_PROF_OUT(X ...) { if (memprof_f) { long t = time(0); fprintf(memprof_f, "<%08x> %x:%02d ", (int) env, t/60, t%60); fprintf(memprof_f, X); }; }
+#else
+#define _mp(X) 
+#endif
+
+/* debugging output (enable with -DRJ_DEBUG) */
+#ifdef RJ_DEBUG
+void rjprintf(char *fmt, ...); /* in Rglue.c */
+/* we can't assume ISO C99 (variadic macros), so we have to use one more level of wrappers */
+#define _dbg(X) X
+#else
+#define _dbg(X)
+#endif
+
+/* profiling */
+#ifdef RJ_PROFILE
+#define profStart() profilerTime=time_ms()
+#define _prof(X) X
+long time_ms(); /* those are acutally in Rglue.c */
+void profReport(char *fmt, ...);
+#else
+#define profStart()
+#define _prof(X)
+#endif
+
+#ifdef ENABLE_JRICB
+#define BEGIN_RJAVA_CALL { int save_in_RJava = RJava_has_control; RJava_has_control=1; {
+#define END_RJAVA_CALL }; RJava_has_control = save_in_RJava; }
+#else
+#define BEGIN_RJAVA_CALL {
+#define END_RJAVA_CALL };
+#endif
+
+/* define mkCharUTF8 in a compatible fashion */
+#if R_VERSION < R_Version(2,7,0)
+#define mkCharUTF8(X) mkChar(X)
+#define CHAR_UTF8(X) CHAR(X)
+#else
+#define mkCharUTF8(X) mkCharCE(X, CE_UTF8)
+#define CHAR_UTF8(X) rj_char_utf8(X)
+extern const char *rj_char_utf8(SEXP);
+#endif
+
+/* signatures are stored in a local buffer if they fit. Only if they don't fit a heap buffer is allocated and used. */
+typedef struct sig_buffer {
+	char *sig; /* if sig doesn't point to sigbuf then it's allocated from heap */
+	int maxsig, len;
+	char sigbuf[256]; /* default size of the local buffer (on the stack) */
+} sig_buffer_t;
+
+/* in callbacks.c */
+extern int RJava_has_control;
+
+/* in rJava.c */
+extern JNIEnv *eenv; /* should NOT be used since not thread-safe; use getJNIEnv instead */
+
+HIDE JNIEnv* getJNIEnv();
+HIDE void ckx(JNIEnv *env);
+HIDE void clx(JNIEnv *env);
+
+HIDE SEXP getStringArrayCont(jarray) ;
+HIDE jarray getSimpleClassNames( jobject, jboolean  ) ;
+HIDE SEXP getSimpleClassNames_asSEXP( jobject, jboolean ) ;
+REPC SEXP RgetSimpleClassNames( SEXP, SEXP ); 
+
+/* in init.c */
+extern JavaVM *jvm;
+extern int rJava_initialized;
+
+extern int java_is_dead;
+
+extern jclass javaStringClass;
+extern jclass javaObjectClass;
+extern jclass javaClassClass;
+extern jclass javaFieldClass;
+extern jclass rj_RJavaTools_Class ;
+
+extern jmethodID mid_forName;
+extern jmethodID mid_getName;
+extern jmethodID mid_getSuperclass;
+extern jmethodID mid_getType;
+extern jmethodID mid_getField;
+extern jmethodID mid_rj_getSimpleClassNames;
+
+extern jmethodID mid_RJavaTools_getFieldTypeName;
+
+/* RJavaImport */
+extern jclass rj_RJavaImport_Class ;
+extern jmethodID mid_RJavaImport_getKnownClasses ;
+extern jmethodID mid_RJavaImport_lookup ;
+extern jmethodID mid_RJavaImport_exists ;
+
+HIDE void init_rJava(void);
+
+/* in otables.c */
+// turn this for debugging in otables.c
+// #define LOOKUP_DEBUG
+
+REPC SEXP newRJavaLookupTable(SEXP) ;
+
+HIDE SEXP R_getUnboundValue() ;
+HIDE SEXP rJavaLookupTable_objects(R_ObjectTable *) ;
+HIDE SEXP rJavaLookupTable_assign(const char * const, SEXP, R_ObjectTable * ) ;
+HIDE Rboolean rJavaLookupTable_canCache(const char * const, R_ObjectTable *) ;
+HIDE int rJavaLookupTable_remove(const char * const,  R_ObjectTable *) ;
+HIDE SEXP rJavaLookupTable_get(const char * const, Rboolean *, R_ObjectTable *) ;
+HIDE Rboolean rJavaLookupTable_exists(const char * const, Rboolean *, R_ObjectTable *) ;
+HIDE jobject getImporterReference(R_ObjectTable *) ;
+HIDE SEXP getKnownClasses( R_ObjectTable * ); 
+HIDE SEXP classNameLookup( R_ObjectTable *, const char * const ) ;
+HIDE Rboolean classNameLookupExists(R_ObjectTable *, const char * const ) ;
+
+/* in loader.c */
+extern jclass   clClassLoader;
+extern jobject  oClassLoader;
+
+/* in Rglue */
+HIDE SEXP j2SEXP(JNIEnv *env, jobject o, int releaseLocal);
+HIDE SEXP new_jobjRef(JNIEnv *env, jobject o, const char *klass);
+HIDE jvalue R1par2jvalue(JNIEnv *env, SEXP par, sig_buffer_t *sig, jobject *otr);
+HIDE void init_sigbuf(sig_buffer_t *sb);
+HIDE void done_sigbuf(sig_buffer_t *sb);
+HIDE SEXP getName( JNIEnv *, jobject/*Class*/ ); 
+HIDE SEXP new_jclassName(JNIEnv *, jobject/*Class*/ ) ;
+
+/* in tools.c */
+HIDE jstring callToString(JNIEnv *env, jobject o);
+
+/* in callJNI */
+HIDE jobject createObject(JNIEnv *env, const char *class, const char *sig, jvalue *par, int silent, jobject loader);
+HIDE jclass findClass(JNIEnv *env, const char *class, jobject loader);
+HIDE jclass objectClass(JNIEnv *env, jobject o);
+
+HIDE jdoubleArray newDoubleArray(JNIEnv *env, double *cont, int len);
+HIDE jintArray newIntArray(JNIEnv *env, int *cont, int len);
+HIDE jbooleanArray newBooleanArrayI(JNIEnv *env, int *cont, int len);
+HIDE jstring newString(JNIEnv *env, const char *cont);
+HIDE jcharArray newCharArrayI(JNIEnv *env, int *cont, int len);
+HIDE jshortArray newShortArrayI(JNIEnv *env, int *cont, int len);
+HIDE jfloatArray newFloatArrayD(JNIEnv *env, double *cont, int len);
+HIDE jlongArray newLongArrayD(JNIEnv *env, double *cont, int len);
+HIDE jintArray newByteArray(JNIEnv *env, void *cont, int len);
+HIDE jbyteArray newByteArrayI(JNIEnv *env, int *cont, int len);
+
+HIDE jobject makeGlobal(JNIEnv *env, jobject o);
+HIDE void releaseObject(JNIEnv *env, jobject o);
+HIDE void releaseGlobal(JNIEnv *env, jobject o);
+
+HIDE void printObject(JNIEnv *env, jobject o);
+
+HIDE int checkExceptionsX(JNIEnv *env, int silent);
+
+HIDE int initClassLoader(JNIEnv *env, jobject cl);
+
+HIDE void deserializeSEXP(SEXP o);
+
+/* this is a hook for de-serialization */
+#define jverify(X) if (EXTPTR_PROT(X) != R_NilValue) deserializeSEXP(X)
+
+#define IS_JOBJREF(obj) ( inherits(obj, "jobjRef") || inherits(obj, "jarrayRef") || inherits(obj,"jrectRef") )
+#define IS_JARRAYREF(obj) ( inherits(obj, "jobjRef") || inherits(obj, "jarrayRef") || inherits(obj, "jrectRef") )
+#define IS_JRECTREF(obj) ( inherits(obj,"jrectRef") )
+
+#endif
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/src/tools.c b/com.oracle.truffle.r.pkgs/rJava/src/tools.c
new file mode 100644
index 0000000000000000000000000000000000000000..3b27c1154dc32d31af2e7feaadbc55a6978613f6
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/src/tools.c
@@ -0,0 +1,165 @@
+/* misc. utility functions, mostly callable from R
+ *
+ * rJava R/Java interface  (C)Copyright 2003-2007 Simon Urbanek
+ * (see rJava project root for licensing details)
+ */
+
+#include "rJava.h"
+
+/** jobjRefInt object : string */
+REPE SEXP RgetStringValue(SEXP par) {
+  SEXP p,e,r;
+  jstring s;
+  const char *c;
+  JNIEnv *env=getJNIEnv();
+  
+  profStart();
+  p=CDR(par); e=CAR(p); p=CDR(p);
+  if (e==R_NilValue) return R_NilValue;
+  if (TYPEOF(e)==EXTPTRSXP) {
+    jverify(e);
+    s = (jstring)EXTPTR_PTR(e);
+  } else {
+    error("invalid object parameter");
+    s = 0;
+  }
+  if (!s) return R_NilValue;
+  c=(*env)->GetStringUTFChars(env, s, 0);
+  if (!c)
+    error("cannot retrieve string content");
+  r = mkString(c);
+  (*env)->ReleaseStringUTFChars(env, s, c);
+  _prof(profReport("RgetStringValue:"));
+  return r;
+}
+
+/** calls .toString() of the object and returns the corresponding string java object */
+HIDE jstring callToString(JNIEnv *env, jobject o) {
+  jclass cls;
+  jmethodID mid;
+  jstring s;
+
+  if (!o) { _dbg(rjprintf("callToString: invoked on a NULL object\n")); return 0; }
+  cls=objectClass(env,o);
+  if (!cls) {
+    _dbg(rjprintf("callToString: can't determine class of the object\n"));
+    releaseObject(env, cls);
+    checkExceptionsX(env, 1);
+    return 0;
+  }
+  mid=(*env)->GetMethodID(env, cls, "toString", "()Ljava/lang/String;");
+  if (!mid) {
+    _dbg(rjprintf("callToString: toString not found for the object\n"));
+    releaseObject(env, cls);
+    checkExceptionsX(env, 1);
+    return 0;
+  }
+  BEGIN_RJAVA_CALL;
+  s = (jstring)(*env)->CallObjectMethod(env, o, mid);
+  END_RJAVA_CALL;
+  _mp(MEM_PROF_OUT("  %08x LNEW object method toString result\n", (int) s))
+  releaseObject(env, cls);
+  return s;
+}
+
+/** calls .toString() on the passed object (int/extptr) and returns the string 
+    value or NULL if there is no toString method */
+REPE SEXP RtoString(SEXP par) {
+  SEXP p,e,r;
+  jstring s;
+  jobject o;
+  const char *c;
+  JNIEnv *env=getJNIEnv();
+
+  p=CDR(par); e=CAR(p); p=CDR(p);
+  if (e==R_NilValue) return R_NilValue;
+  if (TYPEOF(e)==EXTPTRSXP) {
+    jverify(e);
+    o=(jobject)EXTPTR_PTR(e);
+  } else
+    error_return("RtoString: invalid object parameter");
+  if (!o) return R_NilValue;
+  s=callToString(env, o);
+  if (!s) {
+    return R_NilValue;
+  }
+  c=(*env)->GetStringUTFChars(env, s, 0);
+  PROTECT(r=allocVector(STRSXP,1));
+  SET_STRING_ELT(r, 0, mkCharUTF8(c));
+  UNPROTECT(1);
+  (*env)->ReleaseStringUTFChars(env, s, c);
+  releaseObject(env, s);
+  return r;
+}
+
+/* compares two references */
+REPC SEXP RidenticalRef(SEXP ref1, SEXP ref2) {
+  SEXP r;
+  if (TYPEOF(ref1)!=EXTPTRSXP || TYPEOF(ref2)!=EXTPTRSXP) return R_NilValue;
+  jverify(ref1);
+  jverify(ref2);
+  r=allocVector(LGLSXP,1);
+  LOGICAL(r)[0]=(R_ExternalPtrAddr(ref1)==R_ExternalPtrAddr(ref2));
+  return r;
+}
+
+/** create a NULL external reference */
+REPC SEXP RgetNullReference() {
+  return R_MakeExternalPtr(0, R_NilValue, R_NilValue);
+}
+
+/** TRUE if cl1 x; cl2 y = (cl2) x ... is valid */
+REPC SEXP RisAssignableFrom(SEXP cl1, SEXP cl2) {
+  SEXP r;
+  JNIEnv *env=getJNIEnv();
+
+  if (TYPEOF(cl1)!=EXTPTRSXP || TYPEOF(cl2)!=EXTPTRSXP)
+    error("invalid type");
+  if (!env)
+    error("VM not initialized");
+  jverify(cl1);
+  jverify(cl2);
+  r=allocVector(LGLSXP,1);
+  LOGICAL(r)[0]=((*env)->IsAssignableFrom(env,
+					  (jclass)EXTPTR_PTR(cl1),
+					  (jclass)EXTPTR_PTR(cl2)));
+  return r;
+}
+
+REPC SEXP RJava_checkJVM() {
+  SEXP r = allocVector(LGLSXP, 1);
+  LOGICAL(r)[0] = 0;
+  if (!jvm || !getJNIEnv()) return r;
+  LOGICAL(r)[0] = 1;
+  return r;
+}
+
+extern int rJava_initialized; /* in callJNI.c */
+
+REPC SEXP RJava_needs_init() {
+  SEXP r = allocVector(LGLSXP, 1);
+  LOGICAL(r)[0] = rJava_initialized?0:1;
+  return r;
+}
+
+REPC SEXP RJava_set_memprof(SEXP fn) {
+#ifdef MEMPROF
+  const char *cFn = CHAR(STRING_ELT(fn, 0));
+  int env = 0; /* we're just faking it so we can call MEM_PROF_OUT */
+  
+  if (memprof_f) fclose(memprof_f);
+  if (cFn && !cFn[0]) {
+    memprof_f = 0; return R_NilValue;
+  }
+  if (!cFn || (cFn[0]=='-' && !cFn[1]))
+    memprof_f = stdout;
+  else
+    memprof_f = fopen(cFn, "a");
+  if (!memprof_f) error("Cannot create memory profile file.");
+  MEM_PROF_OUT("  00000000 REST -- profiling file set --\n");
+  return R_NilValue;
+#else
+  error("Memory profiling support was not enabled in rJava.");
+#endif
+  return R_NilValue;
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/tests/Leaks.java b/com.oracle.truffle.r.pkgs/rJava/tests/Leaks.java
new file mode 100644
index 0000000000000000000000000000000000000000..f64c33e7bfadf3e6a0e16abc249ca5f3229d323e
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/tests/Leaks.java
@@ -0,0 +1,41 @@
+public class Leaks {
+    public int[] i;
+    public String[] s;
+
+    public Leaks(int[] i, String[] s) {
+	this.i = i;
+	this.s = s;
+    }
+
+    public String[] getS() { return s; }
+    public int[] getI() { return i; }
+    
+    public String[] replaceS(String[] s) {
+	String[] a = this.s;
+	this.s = s;
+	return a;
+    }
+
+    public int[] replaceI(int[] i) {
+	int[] a = this.i;
+	this.i = i;
+	return a;
+    }
+
+    public static String[] passS(String[] s) { return s; }
+    public static Object[] passSO(String[] s) { return (Object[])s; }
+    public static int[] passI(int[] i) { return i; }
+
+
+    public static void runGC() {
+	Runtime r = Runtime.getRuntime();
+	r.runFinalization();
+	r.gc();
+    }
+
+    public static String reportMem() {
+	Runtime r = Runtime.getRuntime();
+	r.gc();
+	return "used: "+((r.totalMemory()-r.freeMemory())/1024L)+"kB (free: "+r.freeMemory()+" of "+r.totalMemory()+")";
+    }
+}
diff --git a/com.oracle.truffle.r.pkgs/rJava/tests/Makefile b/com.oracle.truffle.r.pkgs/rJava/tests/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..d55ef797dc410effc78e988ffb9e2cd69f5abd5b
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/tests/Makefile
@@ -0,0 +1,30 @@
+RBIN=R
+RARGS=--vanilla --slave
+JAVAC=javac
+JFLAGS=-source 1.2 -target 1.2
+
+TESTS=types.R leaks.R
+SOURCES=Types.java Leaks.java
+
+TEST_RES=$(TESTS:%.R=%.test)
+CLASSES=$(SOURCES:%.java=%.class)
+
+retest: clean-tests test
+
+test: $(CLASSES) $(TEST_RES)
+
+.R.test:
+	$(RBIN) $(RARGS) < $^ > $@
+
+.java.class:
+	$(JAVAC) $(JFLAGS) $^
+
+clean: clean-tests
+	rm -f *~ $(CLASSES)
+
+clean-tests:
+	rm -f $(TEST_RES)
+
+.PHONY: clean test clean-tests retest
+
+.SUFFIXES: .R .test .java .class
diff --git a/com.oracle.truffle.r.pkgs/rJava/tests/README b/com.oracle.truffle.r.pkgs/rJava/tests/README
new file mode 100644
index 0000000000000000000000000000000000000000..ef8ae7e78973ebfddc393ca8991e0140a103a6ff
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/tests/README
@@ -0,0 +1,6 @@
+This directory contains off-line tests, i.e. they are not included
+in the package, but can be used to test the rJava functionality.
+At some point we will create a proper test suite that is included
+in the package, but we're not there yet ...
+
+Run via make (default is retest which does clean-tests + test)
diff --git a/com.oracle.truffle.r.pkgs/rJava/tests/Types.java b/com.oracle.truffle.r.pkgs/rJava/tests/Types.java
new file mode 100644
index 0000000000000000000000000000000000000000..74003f0b2133521fd7ed0c76a58cf5472a85e152
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/tests/Types.java
@@ -0,0 +1,55 @@
+public class Types {
+    public static int sri() { return si; }
+    public int ri() { return i; }
+    public static byte srb() { return sb; }
+    public byte rb() { return b; }
+    public static boolean srz() { return sz; }
+    public boolean rz() { return z; }
+    public static char src() { return sc; }
+    public char rc() { return c; }
+    public static short srs() { return ss; }
+    public short rs() { return s; }
+    public static long srj() { return sj; }
+    public long rj() { return j; }
+    public static float srf() { return sf; }
+    public float rf() { return f; }
+    public static double srd() { return sd; }
+    public double rd() { return d; }
+    public static String srS() { return sS; }
+    public String rS() { return S; }
+    
+    public void zbcsijfdS(boolean _z, byte _b, char _c,
+			 short _s, int _i, long _j,
+			 float _f, double _d, String _S) {
+	z = _z; b = _b; c = _c;
+	s = _s; i = _i; j = _j;
+	f = _f; d = _d; S = _S;
+    }
+    public static void szbcsijfdS(boolean z, byte b, char c,
+				 short s, int i, long j,
+				 float f, double d, String S) {
+	sz = z; sb = b; sc = c;
+	ss = s; si = i; sj = j;
+	sf = f; sd = d; sS = S;
+    }
+
+    public boolean z = true;
+    public byte b = 123;
+    public char c = 'c';
+    public short s = 1234;
+    public int i = 1234;
+    public long j = 1234567890;
+    public double d = 1234.567;
+    public float f = 1234.567f;
+    public String S = "ok";
+    public static boolean sz = true;
+    public static byte sb = 123;
+    public static char sc = 'c';
+    public static short ss = 1234;
+    public static int si = 1234;
+    public static long sj = 1234567890;
+    public static double sd = 1234.567;
+    public static float sf = 1234.567f;
+    public static String sS = "ok";
+}
+
diff --git a/com.oracle.truffle.r.pkgs/rJava/tests/leaks.R b/com.oracle.truffle.r.pkgs/rJava/tests/leaks.R
new file mode 100644
index 0000000000000000000000000000000000000000..cae4bb4e93bd80f06b2750200233bc19eb20f674
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/tests/leaks.R
@@ -0,0 +1,51 @@
+library(rJava)
+# restrict memory so we run out of it earlier
+.jinit(".","-Xmx128m")
+gc()
+.s <- as.character(1:10000)
+.i <- 1:10000
+..s <- .s
+..i <- .i
+cat(.jcall("Leaks","S","reportMem"),"\n")
+cat(" - create unassigned objects\n")
+for (i in 1:400) .jnew("Leaks", .i, .s)
+cat(.jcall("Leaks","S","reportMem"),"\n")
+cat(" running R gc\n")
+gc()
+cat(" running java GC\n")
+cat(.jcall("Leaks","S","reportMem"),"\n")
+cat(" - static pass thorugh parameters\n")
+for (i in 1:800) {
+  if (i==400) { cat('   (forcing R gc)\n'); gc() }
+  .i <- .jcall("Leaks", "[I", "passI", .i)
+  .s <- .jcall("Leaks", "[S", "passS", .s)
+}
+cat(.jcall("Leaks","S","reportMem"),"\n")
+cat(" running R gc\n")
+gc()
+cat(" running java GC\n")
+.jcall("Leaks","V","runGC")
+cat(.jcall("Leaks","S","reportMem"),"\n")
+if (!isTRUE(all.equal(.s, ..s)))
+  stop("FAILED - string array was modified")
+if (!isTRUE(all.equal(.i, ..i)))
+  stop("FAILED - integer array was modified")
+cat(" - dynamic storage\n")
+l <- .jnew("Leaks", .i, .s)
+for (i in 1:800) {
+  .i <- .jcall("Leaks", "[I", "passI", .i)
+  .s <- .jcall("Leaks", "[S", "passS", .s)
+}
+cat(.jcall("Leaks","S","reportMem"),"\n")
+cat(" running R gc\n")
+gc()
+cat(.jcall("Leaks","S","reportMem"),"\n")
+cat(" running java GC\n")
+.jcall("Leaks","V","runGC")
+cat(.jcall("Leaks","S","reportMem"),"\n")
+if (!isTRUE(all.equal(.s, ..s)))
+  stop("FAILED - string array was modified")
+if (!isTRUE(all.equal(.i, ..i)))
+  stop("FAILED - integer array was modified")
+
+cat("OK\n")
diff --git a/com.oracle.truffle.r.pkgs/rJava/tests/testthat.R b/com.oracle.truffle.r.pkgs/rJava/tests/testthat.R
deleted file mode 100644
index 46b38886ec61b333475eda982a77f68ac0bdd59a..0000000000000000000000000000000000000000
--- a/com.oracle.truffle.r.pkgs/rJava/tests/testthat.R
+++ /dev/null
@@ -1,5 +0,0 @@
-library(testthat)
-library(rjava)
-
-test_check("rjava")
-typeName
\ No newline at end of file
diff --git a/com.oracle.truffle.r.pkgs/rJava/tests/testthat/testArrays.R b/com.oracle.truffle.r.pkgs/rJava/tests/testthat/testArrays.R
deleted file mode 100644
index 1fb95666c0d118d0b40b88a009f4a5f3f1051f61..0000000000000000000000000000000000000000
--- a/com.oracle.truffle.r.pkgs/rJava/tests/testthat/testArrays.R
+++ /dev/null
@@ -1,104 +0,0 @@
-# prerequisites:
-# - 'testthat' package has to be installed: install.packages("testthat")
-# - FastR`s rJava package has to be installed: bin/r CMD INSTALL com.oracle.truffle.r.pkgs/rjava
-
-library(testthat)
-library(rJava)
-
-.jaddClassPath(paste0(Sys.getenv("R_HOME"), "/mxbuild/dists/fastr-unit-tests.jar"))
-
-testName <- "test .jarray"
-test_that(testName, {
-    cat(paste0(testName, "\n"))
-	    
-    a <- .jarray(c(1.1, 2.1, 3.1))
-    expect_true(is.external.array(a))
-    expect_equal(length(a), 3)
-    expect_equal(a[1], c(1.1))
-    expect_equal(a[2], c(2.1))
-    expect_equal(a[3], c(3.1))
-
-    a <- .jarray(c(1L, 2L, 3L))
-    expect_true(is.external.array(a))
-    expect_equal(length(a), 3)
-    expect_equal(a[1], c(1))
-    expect_equal(a[2], c(2))
-    expect_equal(a[3], c(3))
-
-    a <- .jarray(c(TRUE, FALSE))
-    expect_true(is.external.array(a))
-    expect_equal(length(a), 2)
-    expect_equal(a[1], TRUE)
-    expect_equal(a[2], FALSE)
-
-    a <- .jarray(c(.jbyte(1), .jchar("a"), .jfloat(1.1), .jlong(2), .jshort(123)))
-    expect_true(is.external.array(a))
-    expect_equal(length(a), 5)
-    expect_equal(a[1], 1)
-    expect_equal(a[2], "a")
-    expect_true((a[3] - 1.1)^2 < 1e-8)
-    expect_equal(a[4], 2)
-    expect_equal(a[5], 123)
-
-    to <- .jnew('java.util.ArrayList')
-    a <- .jarray(to)
-    expect_true(is.external.array(a))
-    expect_equal(length(a), 1)
-    # fails at the moment  
-    # testthat passes 'to' into .Call("find_label_", quote(to), environment()) 
-    # expect_equal(a[1], to)
-  
-    to <- .jnew('java.util.ArrayList')
-    a <- .jarray(c(to, to))
-    expect_true(is.external.array(a))
-    # fails at the moment    
-    # expect_equal(length(a), 2)
-    # expect_equal(a[1], to)
-    # expect_equal(a[2], to)
-
-    a <- .jarray(list(1, 2, 3))
-    expect_true(is.external.array(a))
-    expect_equal(length(a), 3)
-    expect_equal(a[1], 1)
-    expect_equal(a[2], 2)
-    expect_equal(a[3], 3)
-})
-
-testName <- "test .jevalArray"
-test_that(testName, {
-    cat(paste0(testName, "\n"))
-
-    expectedValues <- list(
-        Boolean=list("logical", TRUE, FALSE, TRUE), 
-        Byte=list("integer", 1,2,3), 
-        Char=list("character", "a", "b", "c"), 
-        Double=list("double",1.1, 2.1, 3.1), 
-        Float=list("double", 1.1, 2.1, 3.1), 
-        Integer=list("integer",1,2,3), 
-        Long=list("double", 1,2,3), 
-        Short=list("integer",1,2,3), 
-        String=list("character", "a", "b", "c"))
-    testClassName <- "com.oracle.truffle.r.test.library.fastr.TestJavaInterop$TestClass"
-    t<-.jnew(class=testClassName)
-
-    for(expectedName in names(expectedValues)) {                
-        fieldName <- paste0("fieldStatic", expectedName, "Array")
-        ev<-expectedValues[expectedName][[1]]
-        arrayType <- ev[[1]]
-        arrayLength <- length(ev) - 1
-        a<-t[fieldName]
-        expect_true(is.external.array(a), info=paste0("the array was returned for ", fieldName), label="is.external.array")
-        ae<-.jevalArray(a)
-        expect_true(is.vector(ae), info=paste0("the array was returned for ", fieldName), label="is.vector")
-        expect_equal(typeof(ae), arrayType, info=paste0("the array was returned for ", fieldName), label="typeof")
-        expect_equal(length(ae), arrayLength, info=paste0("the array was returned for ", fieldName), label="array length")
-        for(i in 1:arrayLength) {
-            if(expectedName != "Float") {
-                expect_equal(a[i], ev[[i+1]], info=paste0("the array was returned for ", fieldName), label=paste0("value at", i))
-            } else {
-                expect_true((ev[[i+1]] - a[i])^2 < 1e-8, info=paste0("the array was returned for ", fieldName), label=paste0("value at", i))
-            }
-        }
-    }
-
-})
diff --git a/com.oracle.truffle.r.pkgs/rJava/tests/testthat/testBasic.R b/com.oracle.truffle.r.pkgs/rJava/tests/testthat/testBasic.R
deleted file mode 100644
index 1062c93039bbe8c78bbe2bb8bb816a81bf4bce15..0000000000000000000000000000000000000000
--- a/com.oracle.truffle.r.pkgs/rJava/tests/testthat/testBasic.R
+++ /dev/null
@@ -1,135 +0,0 @@
-# prerequisites:
-# - 'testthat' package has to be installed: install.packages("testthat")
-# - FastR`s rJava package has to be installed: bin/r CMD INSTALL com.oracle.truffle.r.pkgs/rjava
-
-library(testthat)
-library(rJava)
-.jaddClassPath(paste0(Sys.getenv("R_HOME"), "/mxbuild/dists/fastr-unit-tests.jar"))
-
-bo <- TRUE
-bt <- 123
-ch <- 'a'
-d  <- 1.123456
-f  <- 1.123
-i  <- 12345L
-l  <- 123456
-sh <- 1234
-st <- "a test string"
-
-jbt <- .jbyte(bt)
-jch <- .jchar(ch)
-jf  <- .jfloat(f)
-jl  <- .jlong(l)
-jsh <- .jshort(sh)
-
-primitiveTypeNames <- c("Boolean", "Byte", "Char", "Double", "Float", "Integer", "Long", "Short")
-expectedValues <- list(bo, bt, ch, d, f, i, l, sh, st)
-
-testClassName <- "com.oracle.truffle.r.test.library.fastr.TestJavaInterop$TestClass"
-t<-.jnew(class=testClassName, bo, jbt, jch, d, jf, i, jl, jsh, st)
-
-testForMember <- function(valueProvider, memberNameProvider, typeNames) {
-	for(idx in 1:length(typeNames)) {	
-		typeName <- typeNames[idx]
-		member <- memberNameProvider(typeName)
-		expectedValue <- expectedValues[[idx]]
-		value <- valueProvider(t, member)
-		testValue(member, typeName, expectedValue, value)
-	}
-}
-
-testValue <- function(memberName, typeName, expectedValue, value) {
-	cat(paste0("  ", memberName, " returned value [", value, "] and is expected to be [", expectedValue, "]"), "\n")
-	if(typeName != "Float") {
-		expect_that(expectedValue, equals(value), info=memberName, label=memberName)
-	} else {
-		expect_true((expectedValue - value)^2 < 1e-8, info=memberName, label=memberName)
-	}
-}
-
-testName <- "test if primitive field access works"
-test_that(testName, {
-	cat(paste0(testName, "\n"))
-	testForMember( valueProvider = function(t, member) { .jfield(t, , member) },
-                   memberNameProvider = function(typeName) { paste0("field", typeName) },
-                   primitiveTypeNames )
-})
-
-testName <- "test if primitive static field access works"
-test_that(testName, {
-	cat(paste0(testName, "\n"))
-	testForMember( valueProvider = function(t, member) { .jfield(t, , member) },
-                   memberNameProvider = function(typeName) { paste0("fieldStatic", typeName) },
-                   primitiveTypeNames )
-})
-
-testName <- "test if static field access works"
-test_that("test if static field access works", {
-	testForMember( valueProvider = function(t, member) { .jfield(t, , member) },
-                   memberNameProvider = function(typeName) { paste0("fieldStatic", typeName, "Object") },
-                   c(primitiveTypeNames, "String") )
-})
-
-testName <- "test if field access works"
-test_that(testName, {
-	cat(paste0(testName, "\n"))
-	testForMember( valueProvider = function(t, member) { .jfield(t, , member) },
-                   memberNameProvider = function(typeName) { paste0("field", typeName, "Object")},
-                   c(primitiveTypeNames, "String") )
-})
-
-testName <- "test if calling static method returning primitive values works"
-test_that(testName, {
-	cat(paste0(testName, "\n"))
-	testForMember( valueProvider = function(t, member) { .jcall(t, , member) },
-                   memberNameProvider = function(typeName) { paste0("methodStatic", typeName) },
-                   primitiveTypeNames )
-})
-
-testName <- "test if calling method returning primitive values works"
-test_that(testName, {
-	cat(paste0(testName, "\n"))
-	testForMember( valueProvider = function(t, member) { .jcall(t, , member) },
-                   memberNameProvider = function(typeName) { paste0("method", typeName) },
-                   primitiveTypeNames )
-})
-
-testName <- "test if calling static method returning object values works"
-test_that(testName, {
-	cat(paste0(testName, "\n"))
-	testForMember( valueProvider = function(t, member) { .jcall(t, , member) },
-                   memberNameProvider = function(typeName) { paste0("methodStatic", typeName, "Object") },
-                   c(primitiveTypeNames, "String") )
-})
-
-testName <- "test if calling method returning object values works"
-test_that(testName, {
-	cat(paste0(testName, "\n"))
-	testForMember( valueProvider = function(t, member) { .jcall(t, , member) },
-                   memberNameProvider = function(typeName) { paste0("method", typeName, "Object") },
-                   c(primitiveTypeNames, "String") )
-})
-
-testName <- "test if static access via class name works"
-test_that(testName, {
-	cat(paste0(testName, "\n"))
-	value <- .jfield(testClassName, , "fieldStaticInteger")
-	testValue("fieldStaticInteger", "Integer", i, value)
-
-	value <- .jcall(testClassName, , "methodStaticInteger")
-	testValue("methodStaticInteger", "Integer", i, value)
-})
-
-testName <- "test if calling method with all primitive type parameters + string works"
-test_that(testName, {
-	cat(paste0(testName, "\n"))
-	value <- .jcall(t, , "allTypesMethod", bo, jbt, jch, d, jf, i, jl, jsh, st)
-	expect_false(is.null(value))
-})
-
-testName <- "test if calling method with all primitive type parameters + string works"
-test_that(testName, {
-	cat(paste0(testName, "\n"))
-	value <- .jcall(t, , "allTypesStaticMethod", bo, jbt, jch, d, jf, i, jl, jsh, st)
-	expect_false(is.null(value))
-})
\ No newline at end of file
diff --git a/com.oracle.truffle.r.pkgs/rJava/tests/testthat/testJ.R b/com.oracle.truffle.r.pkgs/rJava/tests/testthat/testJ.R
deleted file mode 100644
index a406765bfd11c9486d53507445846d5dfbfda577..0000000000000000000000000000000000000000
--- a/com.oracle.truffle.r.pkgs/rJava/tests/testthat/testJ.R
+++ /dev/null
@@ -1,21 +0,0 @@
-# prerequisites:
-# - 'testthat' package has to be installed: install.packages("testthat")
-# - FastR`s rJava package has to be installed: bin/r CMD INSTALL com.oracle.truffle.r.pkgs/rjava
-
-library(testthat)
-library(rJava)
-
-.jaddClassPath(paste0(Sys.getenv("R_HOME"), "/mxbuild/dists/fastr-unit-tests.jar"))
-
-testName <- "test J function"
-test_that(testName, {
-    cat(paste0(testName, "\n"))
-    tc <- J("com.oracle.truffle.r.test.library.fastr.TestJavaInterop$TestClass")
-    expect_equal(2147483647L, tc$fieldStaticInteger)
-
-    tc <- J("com/oracle/truffle/r/test/library/fastr/TestJavaInterop$TestClass")
-    expect_equal(2147483647L, tc$fieldStaticInteger)
-
-    expect_equal(2147483647L, J("com.oracle.truffle.r.test.library.fastr.TestJavaInterop$TestClass", "methodStaticInteger"))
-    expect_equal(2147483647L, J("com/oracle/truffle/r/test/library/fastr/TestJavaInterop$TestClass", "methodStaticInteger"))
-})
diff --git a/com.oracle.truffle.r.pkgs/rJava/tests/types.R b/com.oracle.truffle.r.pkgs/rJava/tests/types.R
new file mode 100644
index 0000000000000000000000000000000000000000..a4b5935ab6413b692df9d1ec8ef662ad5efe8334
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/tests/types.R
@@ -0,0 +1,46 @@
+library(rJava)
+.jinit(".")
+cat(" - instantiate Types class\n")
+t=.jnew("Types")
+ts=c("Z","B","C","T","I","J","D","F","Ljava/lang/String;")
+tn=c("z","b","c","s","i","j","d","f","S")
+ty=c("boolean","byte","char","short","int","long","double","float","string")
+ev=list(TRUE, 123L, 99L, 1234L, 1234L, 1234567890, 1234.567, 1234.567, "ok")
+for (i in 1:length(ts)) {
+  cat(" -",ty[i],"\n")
+#  cat("    static call\n");
+  sr=.jcall("Types",ts[i],paste('sr',tn[i],sep=''))
+#  cat("    call\n");
+  r=.jcall(t,ts[i],paste('r',tn[i],sep=''))
+#  cat("    static+sig\n");
+  sfr=.jfield("Types",ts[i],paste('s',tn[i],sep=''))
+#  cat("    sig\n");
+  fr=.jfield(t,ts[i],tn[i])
+#  cat("    static\n");
+  .sfr=.jfield("Types",,paste('s',tn[i],sep=''))
+  if (.sfr != sfr) stop("static field test failed: different results with and without a signature")
+#  cat("    no sig\n");
+  .fr=.jfield(t,,tn[i])
+  if (.fr != fr) stop("field test failed: different results with and without a signature")
+  ..sfr=.jfield(t,,paste('s',tn[i],sep=''))
+  if (..sfr != .sfr) stop("field test failed: different results fetching a static field from an instance and the class")
+  if (tn[i] == 'f') {
+    if ((sr-ev[[i]])^2>1e-8) stop("failed static return test for ",ts[i])
+    if ((r-ev[[i]])^2>1e-8) stop("failed return test for ",ts[i])
+    if ((sfr-ev[[i]])^2>1e-8) stop("failed static field test for ",ts[i])
+    if ((fr-ev[[i]])^2>1e-8) stop("failed field test for ",ts[i])
+  } else {
+    if (sr != ev[[i]]) stop("failed static return test for ",ts[i])
+    if (r != ev[[i]]) stop("failed return test for ",ts[i])
+    if (sfr != ev[[i]]) stop("failed static field test for ",ts[i])
+    if (fr != ev[[i]]) stop("failed field test for ",ts[i])
+  }
+}
+cat(" - calling a static method with all types\n")
+.jcall("Types", "V", "szbcsijfdS",
+       TRUE, .jbyte(-123), .jchar(66), .jshort(4321), 4321L,
+       .jlong(9876543210), .jfloat(4321.12), 4321.1234, "foo")
+cat(" - calling a method with all types\n")
+.jcall(t, "V", "zbcsijfdS",
+       TRUE, .jbyte(-123), .jchar(66), .jshort(4321), 4321L,
+       .jlong(9876543210), .jfloat(4321.12), 4321.1234, "foo")
diff --git a/com.oracle.truffle.r.pkgs/rJava/version b/com.oracle.truffle.r.pkgs/rJava/version
new file mode 100755
index 0000000000000000000000000000000000000000..0233f131effa234c3bd0d60bd07b14943022d32f
--- /dev/null
+++ b/com.oracle.truffle.r.pkgs/rJava/version
@@ -0,0 +1,8 @@
+#!/bin/sh
+
+VER=`awk -v ORS= '/rJava v/ { print substr($6,2) }' src/rJava.h`
+if test "$1" == "-f"; then 
+    echo "rJava_${VER}.tar.gz"
+else
+    echo "${VER}"
+fi