changeset 15625:acf0addfc610

include Octave Forge java package in core Octave * scripts/java: New directory tree. * scripts/Makefile.am: Include java/module.mk. (JAR_FILES): New variable. (nobase_fcnfile_DATA): Include $(JAR_FILES) in the list. (all-local): Depend on $(JAR_FILES). (java/PKG_ADD, java_GEN_FCN_FILES, java/$(octave_dirstamp)): New rules. * libinterp/link-deps (LIBOCTINTERP_LINK_DEP): Include $(JAVA_LIBS) in the list. * dldfcn/__java__.h, dldfcn/__java__.cc: New files. * dldfcn/module-files (__java__.cc): New file description. * doc/interpreter/java.txi: New file. * doc/interpreter/octave.texi: Include java.texi. * doc/interpreter/java-images: New directory. * doc/interpreter/Makefile.am (JAVA_IMAGES): New variable. (IMAGES): Include $(JAVA_IMAGSES) in the list. (MUNGED_TEXI_SRC): Include java.texi in the list. * configure.ac: Check for Java libraries and tools. Include Java info in the summary message. * build-aux/common.mk (JAVA_CPPFLAGS, JAVA_LIBS): New variables. * NEWS: Update. * contributors.in: Include Martin Hepperle in the list.
author John W. Eaton <jwe@octave.org>
date Fri, 23 Nov 2012 15:29:13 -0500
parents 550147454137
children 1cc10ce368ea
files NEWS build-aux/common.mk configure.ac doc/interpreter/Makefile.am doc/interpreter/contributors.in doc/interpreter/java-images/image001.png doc/interpreter/java-images/image002.png doc/interpreter/java-images/image003.png doc/interpreter/java-images/image004.png doc/interpreter/java-images/image005.png doc/interpreter/java-images/image006.png doc/interpreter/java-images/image007.png doc/interpreter/java-images/image008.png doc/interpreter/java-images/image009.png doc/interpreter/java.txi doc/interpreter/octave.texi libinterp/dldfcn/__java__.cc libinterp/dldfcn/__java__.h libinterp/dldfcn/module-files libinterp/link-deps.mk scripts/Makefile.am scripts/java/dlgtest.m scripts/java/errordlg.m scripts/java/helpdlg.m scripts/java/inputdlg.m scripts/java/java.m scripts/java/javaArray.m scripts/java/javaaddpath.m scripts/java/javaclasspath.m scripts/java/javafields.m scripts/java/javamem.m scripts/java/javamethods.m scripts/java/javarmpath.m scripts/java/listdlg.m scripts/java/module.mk scripts/java/msgbox.m scripts/java/org/octave/ClassHelper.java scripts/java/org/octave/DlgListener.java scripts/java/org/octave/JDialogBox.java scripts/java/org/octave/Matrix.java scripts/java/org/octave/OctClassLoader.java scripts/java/org/octave/Octave.java scripts/java/org/octave/OctaveReference.java scripts/java/org/octave/TeXcode.java scripts/java/org/octave/TeXtranslator.java scripts/java/org/octave/images/error.png scripts/java/org/octave/images/information.png scripts/java/org/octave/images/octave.png scripts/java/org/octave/images/question.png scripts/java/org/octave/images/warning.png scripts/java/questdlg.m scripts/java/warndlg.m
diffstat 52 files changed, 8527 insertions(+), 5 deletions(-) [+]
line wrap: on
line diff
--- a/NEWS	Fri Nov 23 11:43:49 2012 -0500
+++ b/NEWS	Fri Nov 23 15:29:13 2012 -0500
@@ -97,7 +97,29 @@
 
  ** The default name of the Octave crash dump file is now called
     octave-workspace instead of octave-core.
-      
+
+ ** The java package from Octave Forge is now part of Octave.  The
+    following new functions are available for interacting with Java
+    directly from Octave:
+
+      java                  java_invoke
+      java2mat              java_new
+      javaArray             java_set
+      javaMethod            java_unsigned_conversion
+      javaObject            javaaddpath
+      java_convert_matrix   javaclasspath
+      java_debug            javafields
+      java_exit             javamem
+      java_get              javamethods
+      java_init             javarmpath
+
+    In addition, the following functions that use the Java interface
+    are now available (provided that Octave is compiled with support for
+    Java enabled):
+
+      helpdlg    listdlg   questdlg
+      inputdlg   msgbox    warndlg
+
  ** Other new functions added in 3.8.0:
 
       betaincinv   erfcinv      lines      rgbplot
--- a/build-aux/common.mk	Fri Nov 23 11:43:49 2012 -0500
+++ b/build-aux/common.mk	Fri Nov 23 15:29:13 2012 -0500
@@ -224,6 +224,9 @@
 HDF5_LDFLAGS = @HDF5_LDFLAGS@
 HDF5_LIBS = @HDF5_LIBS@
 
+JAVA_CPPFLAGS = @JAVA_CPPFLAGS@
+JAVA_LIBS = @JAVA_LIBS@
+
 LAPACK_LIBS = @LAPACK_LIBS@
 
 LLVM_CPPFLAGS = @LLVM_CPPFLAGS@
--- a/configure.ac	Fri Nov 23 11:43:49 2012 -0500
+++ b/configure.ac	Fri Nov 23 15:29:13 2012 -0500
@@ -738,6 +738,105 @@
 AC_SUBST(LLVM_LDFLAGS)
 AC_SUBST(LLVM_LIBS)
 
+### Check for Java.
+
+warn_java=
+
+if test -z "$JAVA_HOME"; then
+  AC_CHECK_PROG(JAVA, java, java)
+  AC_CHECK_PROG(JAVAC, javac, javac)
+  AC_CHECK_PROG(JAR, jar, jar)
+else
+  AC_PATH_PROG(JAVA, java, [], [$JAVA_HOME/bin$PATH_SEPARATOR$PATH])
+  AC_PATH_PROG(JAVAC, javac, [], [$JAVA_HOME/bin$PATH_SEPARATOR$PATH])
+  AC_PATH_PROG(JAR, jar, [], [$JAVA_HOME/bin$PATH_SEPARATOR$PATH])
+fi
+HAVE_JAVA=no
+if test -n "$JAVAC" -a -n "$JAR"; then
+  AC_MSG_CHECKING([for Java version])
+  java_version=[`$JAVA -version 2>&1 | sed -n -e 's/^java version[^0-9"]*"\([^"]*\)"/\1/p'`]
+  AC_MSG_RESULT($java_version)
+  java_major=[`echo -n $java_version | sed -e 's/^\([0-9][0-9]*\)\.\([0-9][0-9]*\)\..*$/\1/'`]
+  java_minor=[`echo -n $java_version | sed -e 's/^\([0-9][0-9]*\)\.\([0-9][0-9]*\)\..*$/\2/'`]
+  if test $java_major -ge 1 -a $java_minor -ge 5; then
+    case "$canonical_host_type" in
+      *-msdosmsvc*)
+        HAVE_JAVA=yes
+        JAVA_LIBS=-ladvapi32
+      ;;
+      *)
+        if test -z "$JAVA_HOME"; then
+          # This is the location of Java on an OS X box. In this
+          # directory we can find the various versions of a
+          # JavaVMs. Check for the newest version set the JAVA_HOME
+          # variable.
+          if test -d "/System/Library/Frameworks/JavaVM.framework"; then
+            # Sneak the -framework flag into mkoctfile via LFLAGS
+            LFLAGS="$LFLAGS -framework JavaVM"
+            JAVA_TEMP="/System/Library/Frameworks/JavaVM.framework"
+            JAVA_HOME="${JAVA_TEMP}/Home"
+            JAVA_ARCH="${JAVA_TEMP}/Libraries/libjvm_compat.dylib"
+            # According to:
+            #   http://developer.apple.com/unix/crossplatform.html
+            # you need to explicitely set the include path
+            JAVA_CPPFLAGS="-I${JAVA_HOME}/include"
+            HAVE_JAVA=yes
+          # This is the Debian default path
+          elif test -d "/usr/lib/jvm/default-java"; then
+            JAVA_HOME=/usr/lib/jvm/default-java
+          # This is the path of java 6 on debian
+          elif test -d "/usr/lib/jvm/java-6-sun"; then
+            JAVA_HOME=//usr/lib/jvm/java-6-sun
+          else
+            JAVA_HOME=/usr/lib/jvm
+          fi
+        fi
+        JAVA_HOME=[`echo -n $JAVA_HOME | sed -e 's|/$||'`]
+        if test -z "$JAVA_ARCH"; then
+          if test -d "${JAVA_HOME}/jre/lib/i386"; then
+            JAVA_ARCH="i386";
+          elif test -d "${JAVA_HOME}/jre/lib/amd64"; then
+            JAVA_ARCH="amd64"
+          elif test -d "${JAVA_HOME}/jre/lib/mac"; then
+            JAVA_ARCH="mac"
+          elif test -d "${JAVA_HOME}/jre/lib/maci"; then
+            JAVA_ARCH="maci"
+          elif test -d "${JAVA_HOME}/jre/lib/solaris"; then
+            JAVA_ARCH="solaris"
+          elif test -d "${JAVA_HOME}/jre/lib/solarisv9"; then
+            JAVA_ARCH="solarisv9"
+          fi
+        fi
+        if test -n "$JAVA_ARCH"; then
+          HAVE_JAVA=yes
+          case "$canonical_host_type" in
+            *-mingw* | *-cygwin*)
+              JAVA_LIBS=-ladvapi32
+              JAVA_CPPFLAGS="-I${JAVA_HOME}/include -I${JAVA_HOME}/include/win32"
+            ;;
+            *)
+              JAVA_CPPFLAGS="-I${JAVA_HOME}/include -I${JAVA_HOME}/include/linux"
+            ;;
+          esac
+        fi
+      ;;
+    esac
+    if test "$HAVE_JAVA" = "yes"; then
+      AC_DEFINE(HAVE_JAVA, 1,
+        [Define to 1 if Java is available and is at least version 1.5])
+    fi
+  else
+    warn_java="Java 1.5 or later not found.  Octave will not be able to call Java methods."
+  fi
+fi
+
+AC_SUBST(JAVAC)
+AC_SUBST(JAR)
+AC_SUBST(JAVA_CPPFLAGS)
+AC_SUBST(JAVA_LIBS)
+AC_DEFINE_UNQUOTED([JAVA_HOME], ["$JAVA_HOME"], [Java home.])
+AC_DEFINE_UNQUOTED([JAVA_ARCH], ["$JAVA_ARCH"], [Java arch.])
+
 ### Check for HDF5 library.
 
 save_CPPFLAGS="$CPPFLAGS"
@@ -2535,6 +2634,10 @@
   HDF5 CPPFLAGS:               $HDF5_CPPFLAGS
   HDF5 LDFLAGS:                $HDF5_LDFLAGS
   HDF5 libraries:              $HDF5_LIBS
+  Java arch:                   $JAVA_ARCH
+  Java home:                   $JAVA_HOME
+  Java CPPFLAGS:               $JAVA_CPPFLAGS
+  Java libraries:              $JAVA_LIBS
   LAPACK libraries:            $LAPACK_LIBS
   LLVM CPPFLAGS:               $LLVM_CPPFLAGS
   LLVM LDFLAGS:                $LLVM_LDFLAGS
--- a/doc/interpreter/Makefile.am	Fri Nov 23 11:43:49 2012 -0500
+++ b/doc/interpreter/Makefile.am	Fri Nov 23 15:29:13 2012 -0500
@@ -83,11 +83,23 @@
 $(srcdir)/images.mk: $(srcdir)/config-images.sh $(srcdir)/images.awk $(srcdir)/images
 	$(srcdir)/config-images.sh $(top_srcdir)
 
+JAVA_IMAGES = \
+  java-images/image001.png \
+  java-images/image002.png \
+  java-images/image003.png \
+  java-images/image004.png \
+  java-images/image005.png \
+  java-images/image006.png \
+  java-images/image007.png \
+  java-images/image008.png \
+  java-images/image009.png
+
 IMAGES = \
   $(IMAGES_EPS) \
   $(IMAGES_PDF) \
   $(IMAGES_PNG) \
-  $(IMAGES_TXT)
+  $(IMAGES_TXT) \
+  $(JAVA_IMAGES)
 
 HTMLDIR_IMAGES = $(addprefix octave.html/, $(IMAGES_PNG))
 
@@ -123,6 +135,7 @@
   interp.texi \
   intro.texi \
   io.texi \
+  java.texi \
   linalg.texi \
   matrix.texi \
   nonlin.texi \
--- a/doc/interpreter/contributors.in	Fri Nov 23 11:43:49 2012 -0500
+++ b/doc/interpreter/contributors.in	Fri Nov 23 15:29:13 2012 -0500
@@ -93,6 +93,7 @@
 Daniel Heiserer
 Martin Helm
 Stefan Hepp
+Martin Hepperle
 Jordi GutiƩrrez Hermoso
 Yozo Hida
 Ryan Hinton
Binary file doc/interpreter/java-images/image001.png has changed
Binary file doc/interpreter/java-images/image002.png has changed
Binary file doc/interpreter/java-images/image003.png has changed
Binary file doc/interpreter/java-images/image004.png has changed
Binary file doc/interpreter/java-images/image005.png has changed
Binary file doc/interpreter/java-images/image006.png has changed
Binary file doc/interpreter/java-images/image007.png has changed
Binary file doc/interpreter/java-images/image008.png has changed
Binary file doc/interpreter/java-images/image009.png has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/doc/interpreter/java.txi	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,1705 @@
+@c Copyright (C) 2010-2012 Martin Hepperle
+@c
+@c This file is part of Octave.
+@c
+@c Octave is free software; you can redistribute it and/or modify it
+@c under the terms of the GNU General Public License as published by the
+@c Free Software Foundation; either version 3 of the License, or (at
+@c your option) any later version.
+@c 
+@c Octave is distributed in the hope that it will be useful, but WITHOUT
+@c ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+@c FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+@c for more details.
+@c 
+@c You should have received a copy of the GNU General Public License
+@c along with Octave; see the file COPYING.  If not, see
+@c <http://www.gnu.org/licenses/>.
+
+@node Java Interface
+@chapter Java Interface
+
+@cindex using Octave with Java
+@cindex Java, using with Octave
+@cindex calling Java from Octave
+@cindex Java, calling from Octave
+@cindex calling Octave from Java
+@cindex  Octave, calling from Java
+
+The @code{java} package is designed for calling Java from Octave.
+If you want to call Octave from Java, you might want to use a library like 
+@code{javaOctave} (@url{http://kenai.com/projects/javaOctave}) or
+@code{joPas} (@url{http://jopas.sourceforge.net}). 
+
+@menu
+* Available Functions::         
+* FAQ - Frequently asked Questions::  
+@end menu
+
+@node Available Functions
+@section Available Functions
+
+@menu
+* javaclasspath::               
+* javaaddpath::                 
+* javarmpath::                  
+* javamem::                     
+* javaArray::                   
+* javaObject::                  
+* java_new::                    
+* javaMethod::                  
+* java_invoke::                 
+* java_get::                    
+* java_set::                    
+* javamethods::                 
+* javafields::                  
+* msgbox::                      
+* errordlg::                    
+* helpdlg::                     
+* inputdlg::                    
+* listdlg::                     
+* questdlg::                    
+* warndlg::                     
+@end menu
+
+@node javaclasspath
+@subsection javaclasspath
+@findex javaclasspath
+@anchor{doc-javaclasspath}
+@c - index -
+@cindex classpath, displaying
+@cindex classpath, dynamic
+@cindex dynamic classpath
+@cindex classpath, static
+@cindex static classpath
+@c - index -
+
+@deftypefn {Function file}  {} javaclasspath
+@deftypefnx {Function file} {@var{STATIC} =} javaclasspath
+@deftypefnx {Function file} {[@var{STATIC}, @var{DYNAMIC}] =} javaclasspath
+@deftypefnx {Function file} {@var{PATH} =} javaclasspath (@var{WHAT})
+
+Return the class path of the Java virtual machine as a cell array of strings. 
+
+If called without an input parameter:
+@itemize
+@item If no output variable is given, the result is simply printed 
+to the standard output.
+@item If one output variable @var{STATIC} is given, the result is
+the static classpath.
+@item If two output variables @var{STATIC} and @var{DYNAMIC} are 
+given, the first variable will contain the static classpath,
+the second will be filled with the dynamic claspath.
+@end itemize
+
+If called with a single input parameter @var{WHAT}:
+@itemize
+If no output parameter is given:
+@item The result is printed to the standard output similar to the call without input parameter.@*
+If the output parameter @var{PATH} is used:
+@item If @var{WHAT} is '-static' the static classpath is returned.
+@item If @var{WHAT} is '-dynamic' the dynamic  classpath is returned.
+@item If @var{WHAT} is '-all' the static and the dynamic classpath 
+are returned in a single cell array.
+@end itemize
+
+For the example two entries have been added to the static classpath using the file @code{classpath.txt}.
+
+Example: 
+@example
+Octave > javaclasspath('-all')
+   STATIC JAVA PATH
+
+      z:/someclasses.jar
+      z:/classdir/classfiles
+      
+   DYNAMIC JAVA PATH
+      - empty -
+
+Octave > javaaddpath('z:/dynamic');
+Octave > ps = javaclasspath('-all')
+ps =
+@{
+  [1,1] = z:/someclasses.jar
+  [1,2] = z:/classdir/classfiles
+  [1,3] = z:/dynamic
+@}
+@end example
+
+@seealso{@ref{doc-javaaddpath,,javaaddpath},
+         @ref{doc-javarmpath,,javarmpath},
+         @ref{doc-FAQ,,How to make Java classes available to Octave?}}
+@end deftypefn
+
+@c ------------------------------------------------------------------------
+@node javaaddpath
+@subsection javaaddpath
+@anchor{doc-javaaddpath}
+@c - index -
+@findex javaaddpath
+@cindex classpath, adding new path
+@cindex path, adding to classpath
+@cindex classpath, dynamic
+@cindex dynamic classpath, adding new path
+@c - index -
+
+@deftypefn {Function File} {} javaaddpath (@var{PATH})
+
+Add @var{PATH} to the dynamic class path of the Java virtual machine. @var{PATH} can be either a directory where .class files can be found, or a .jar file containing Java classes. In both cases the directory or file must exist. 
+
+Example: 
+
+This example adds a Java archive and a directory containing @var{.class} files to the @var{classpath} and displays the current @var{classpath} list. 
+
+@example
+Octave > javaaddpath('C:/java/myclasses.jar'); 
+Octave > javaaddpath('C:/java/classes'); 
+Octave > javaclasspath; 
+ans = 
+@{ 
+  [1,1] = C:\java\myclasses.jar 
+  [1,2] = C:\java\classes 
+@} 
+@end example
+@seealso{@ref{doc-javaclasspath,,javaclasspath}, @ref{doc-javarmpath,,javarmpath},
+         @ref{doc-FAQ,,How to make Java classes available to Octave?}}
+@end deftypefn
+
+@c ------------------------------------------------------------------------
+@node javarmpath
+@subsection javarmpath
+@anchor{doc-javarmpath}
+@c - index -
+@cindex classpath, removing path
+@cindex path, removing from classpath
+@c - index -
+
+@deftypefn {Function File} {} javarmpath (@var{PATH})
+Remove @var{PATH} from the dynamic class path of the Java virtual machine. @var{PATH} can be either a directory where .class files can be found, or a .jar file containing Java classes. 
+
+Example: This example removes one of the directories added in the example for the @code{javaaddpath} function. 
+
+@example
+Octave > javarmpath('C:/java/classes'); 
+Octave > javaclasspath 
+@{ 
+  [1,1] = C:\java\myclasses.jar 
+@} 
+@end example
+
+@seealso{@ref{doc-javaaddpath,,javaaddpath}, @ref{doc-javaclasspath,,javaclasspath},
+         @ref{doc-FAQ,,How to make Java classes available to Octave?}}
+@end deftypefn
+
+@c ------------------------------------------------------------------------
+@node javamem
+@subsection javamem
+@anchor{doc-javamem}
+@c - index -
+@cindex memory, displaying Java memory status
+@c - index -
+
+@deftypefn  {Function File} {} javamem
+@deftypefnx {Function File} {[@var{JMEM}] =} javamem
+
+Show current memory status of the java virtual machine (JVM)
+& run garbage collector.
+
+When no return argument is given the info is echoed to the screen.
+Otherwise, cell array @var{JMEM} contains @var{Maximum}, @var{Total}, and
+@var{Free} memory (in bytes).
+
+All java-based routines are run in the JVM's shared memory pool,
+a dedicated and separate part of memory claimed by the JVM from
+your computer's total memory (which comprises physical RAM and
+virtual memory / swap space on hard disk).
+
+The maximum available memory can be set using the file @code{java.opts}
+(in the same subdirectory where @code{javaaddpath.m} lives, see 
+@samp{which javaaddpath}. Usually that is: @*
+[/usr]/share/Octave/packages/java-1.2.8.
+
+@code{java.opts} is a plain text file. It can contain memory related 
+options, starting with @code{-X}.
+In the following exmaple, the first line specifies the initial 
+memory size in megabytes, the second line specifies the requested 
+maximum size:
+@example
+-Xms64m
+-Xmx512m
+@end example
+You can adapt these values if your system has limited available
+physical memory. When no @code{java.opts} file is present, the default
+assignments are depending on system hardware and Java version. 
+Typically these are an initial memory size of @math{RAM/64} and 
+a maximum memory size of @math{min(RAM/4, 1GB)}, where @var{RAM}
+is the amount of installed memory.
+
+In the output of javamem @var{Total memory} is what the operating
+system has currently assigned to the JVM and depends on actual 
+and active memory usage.
+@var{Free memory} is self-explanatory. During operation of java-based
+Octave functions the amounts of Total and Free memory will vary,
+due to java's own cleaning up and your operating system's memory
+management.
+
+Example:
+@example
+Octave > javamem
+Java virtual machine (JVM) memory info:
+Maximum available memory:          247 MB;
+   (...running garbage collector...)
+OK, current status:
+Total memory in virtual machine:    15 MB;
+Free memory in virtual machine:     15 MB;
+2 CPUs available.
+
+Octave > [MEM] = javamem()
+MEM =
+@{
+  [1,1] =  259522560
+  [2,1] =  16318464
+  [3,1] =  16085576
+@}
+@end example
+
+@seealso{@ref{doc-FAQ,,How can I handle memory limitations?}}
+@end deftypefn
+
+@c ------------------------------------------------------------------------
+@node javaArray
+@subsection javaArray
+@anchor{doc-javaArray}
+@c - index -
+@cindex array, creating a Java array
+@c - index -
+
+@deftypefn  {Function File} {ARRAY =} javaArray (@var{CLASS}, [@var{M}, @var{N}, ...])
+@deftypefnx {Function File} {ARRAY =} javaArray (@var{CLASS}, @var{M}, @var{N}, ...)
+
+Create a Java array of size @code{[M, N, ...]} with elements of class @var{CLASS}. @var{CLASS} can be a Java object representing a class or a string containing the fully qualified class name. 
+The generated array is uninitialized, all elements are set to null if @var{CLASS} is a reference type, or to a default value (usually 0) if @var{CLASS} is a primitive type. 
+
+Example: This example creates a (2 x 2) array of Java @var{String} objects and assigns a value to one of the elements. Finally it displays the type of @var{a}.
+@example
+Octave > a = javaArray('java.lang.String', 2, 2); 
+Octave > a(1,1) = 'Hello'; 
+Octave > a
+a =
+<Java object: java.lang.String[][]>
+@end example
+@end deftypefn
+
+@c ------------------------------------------------------------------------
+@node javaObject
+@subsection javaObject
+@anchor{doc-javaObject}
+@c - index -
+@cindex object, creating a Java object
+@c - index -
+
+@deftypefn  {Function File} {OBJECT =} javaObject (@var{CLASS}, [@var{ARG1}, ...,  @var{ARGN}])
+
+Create a Java object of class @var{CLASS}, by calling the class constructor with the given arguments @var{ARG1}, ..., @var{ARGN}. The @var{CLASS} name should be given in fully qualified string form (including any package prefix). In Matlab you should avoid to use the import statement and the short form of object creation. 
+
+Example: This example demonstrates two ways to create a Java @code{StringBuffer} object. The first variant creates an uninitialized @var{StringBuffer} object, while the second variant calls a constructor with the given initial @code{String}. Then it displays the type of @code{o}, and finally the content of the @code{StringBuffer} object is displayed by using its @code{toString} method.
+
+@example
+Octave > o = javaObject('java.lang.StringBuffer'); 
+Octave > o = javaObject('java.lang.StringBuffer', 'Initial'); 
+Octave > o 
+o =
+<Java object: java.lang.StringBuffer>
+Octave > o.toString 
+ans = Initial
+@end example
+
+Equivalent to the @code{java_new} function.
+For compatibility with Matlab it is recommended to use the @code{javaObject} function. 
+
+@seealso{@ref{doc-java_new,,java_new}}
+@end deftypefn
+
+@c ------------------------------------------------------------------------
+@node java_new
+@subsection java_new
+@anchor{doc-java_new}
+@c - index -
+@cindex object, creating a Java object
+@c - index -
+
+@deftypefn  {Function File} {OBJECT =} java_new (@var{CLASS}, [@var{ARG1}, ...,  @var{ARGN}])
+
+Create a Java object of class @var{CLASS}, by calling the class constructor with the given arguments @var{ARG1}, ..., @var{ARGN}. 
+Equivalent to the @code{javaObject} function. 
+For compatibility with Matlab it is recommended to use the @code{javaObject} function. 
+
+Example: 
+@example
+Octave > o = java_new('java.lang.StringBuffer', 'Initial'); 
+Octave > o 
+o =
+<Java object: java.lang.StringBuffer>
+Octave > o.toString 
+ans = Initial
+@end example
+
+@seealso{@ref{doc-javaObject,,javaObject}}
+@end deftypefn
+
+@c ------------------------------------------------------------------------
+@node javaMethod
+@subsection javaMethod
+@anchor{doc-javaMethod}
+@c - index -
+@cindex method, invoking a method of a Java object
+@c - index -
+
+@deftypefn  {Function File} {RET =} javaMethod (@var{NAME}, @var{OBJECT}[, @var{ARG1}, ...,  @var{ARGN}])
+
+Invoke the method @var{NAME} on the Java object @var{OBJECT} with the arguments @var{ARG1}, ... For static methods, @var{OBJECT} can be a string representing the fully qualified name of the corresponding class. The function returns the result of the method invocation. 
+When @var{OBJECT} is a regular Java object, the structure-like indexing can be used as a shortcut syntax. For instance, the two statements in the example are equivalent. 
+
+Example: 
+@example
+Octave > ret = javaMethod("method1", x, 1.0, "a string")
+Octave > ret = x.method1(1.0, "a string") 
+@end example
+
+@seealso{@ref{doc-javamethods,,javamethods}}
+@end deftypefn
+
+@c ------------------------------------------------------------------------
+@node java_invoke
+@subsection java_invoke
+@anchor{doc-java_invoke}
+@c - index -
+@cindex method, invoking a method of a Java object
+@c - index -
+
+@deftypefn  {Function File} {RET =} java_invoke (@var{OBJECT}, @var{NAME}[, @var{ARG1}, ...,  @var{ARGN}])
+
+Invoke the method @var{NAME} on the Java object @var{OBJECT} with the arguments @var{ARG1}, ... For static methods, @var{OBJECT} can be a string representing the fully qualified name of the corresponding class. The function returns the result of the method invocation. Equivalent to the @code{javaMethod} function. When @var{OBJECT} is a regular Java object, the structure-like indexing can be used as a shortcut syntax. For instance, the two statements in the example are equivalent. 
+
+Example: 
+@example
+Octave > ret = java_invoke(x, "method1", 1.0, "a string") 
+Octave > ret = x.method1(1.0, "a string") 
+@end example
+
+@seealso{@ref{doc-javamethods,,javamethods}}
+@end deftypefn
+
+@c ------------------------------------------------------------------------
+@node java_get
+@subsection java_get
+@anchor{doc-java_get}
+@c - index -
+@cindex field, returning value of Java object field
+@c - index -
+
+@deftypefn  {Function File} {VAL =} java_get (@var{OBJECT}, @var{NAME})
+
+Get the value of the field @var{NAME} of the Java object @var{OBJECT}. For static fields, @var{OBJECT} can be a string representing the fully qualified name of the corresponding class. 
+
+When @var{OBJECT} is a regular Java object, the structure-like indexing can be used as a shortcut syntax. For instance, the two statements in the example are equivalent 
+
+Example: 
+@example
+Octave > java_get(x, "field1") 
+Octave > x.field1 
+@end example
+
+@seealso{@ref{doc-javafields,,javafields},
+         @ref{doc-java_set,,java_set}}
+@end deftypefn
+
+@c ------------------------------------------------------------------------
+@node java_set
+@subsection java_set
+@anchor{doc-java_set}
+@c - index -
+@cindex field, setting value of Java object field
+@c - index -
+
+@deftypefn  {Function File} {OBJECT =} java_set (@var{OBJECT}, @var{NAME}, @var{VALUE})
+
+Set the value of the field @var{NAME} of the Java object @var{OBJECT} to @var{VALUE}. For static fields, @var{OBJECT} can be a string representing the fully qualified named of the corresponding Java class. 
+When @var{OBJECT} is a regular Java object, the structure-like indexing can be used as a shortcut syntax. For instance, the two statements in the example are equivalent 
+
+Example: 
+@example
+Octave > java_set(x, "field1", val) 
+Octave > x.field1 = val 
+@end example
+
+@seealso{@ref{doc-javafields,,javafields},
+         @ref{doc-java_get,,java_get}}
+@end deftypefn
+
+@c ------------------------------------------------------------------------
+@node javamethods
+@subsection javamethods
+@anchor{doc-javamethods}
+@c - index -
+@cindex methods, displaying available methods of a Java object
+@c - index -
+
+@deftypefn   {Function File} {M =} javamethods (@var{CLASSNAME})
+@deftypefnx  {Function File} {M =} javamethods (@var{OBJECT})
+
+Given a string with a Java class name @var{CLASSNAME} or a regular Java object @var{OBJECT}, this function returns a cell array containing descriptions of all methods of the Java class @var{CLASSNAME} respectively the class of @var{OBJECT}. 
+
+Examples: The first example shows how the methods of a class can be queried, while the second example works with the methods of a concrete instance of a class. Note that creation of a @code{java.lang.Double} object requires an initializer (in the example the value 1.2). 
+@example
+Octave > m = javamethods('java.lang.Double'); 
+Octave > size(m) 
+ans = 
+  1 30 
+
+Octave > m@{7@} 
+ans = double longBitsToDouble(long) 
+
+Octave > o = javaObject('java.lang.Double', 1.2); 
+Octave > m = javamethods(o); 
+Octave > size(m) 
+ans = 
+  1 30 
+
+Octave > m@{7@} 
+ans = double longBitsToDouble(long) 
+@end example
+
+@seealso{@ref{doc-javafields,,javafields},
+         @ref{doc-java_invoke,,java_invoke}}
+@end deftypefn
+
+@c ------------------------------------------------------------------------
+@node javafields
+@subsection javafields
+@anchor{doc-javafields}
+@c - index -
+@cindex fields, displaying available fields of a Java object
+@c - index -
+
+@deftypefn   {Function File} {F =} javafields (@var{CLASSNAME})
+@deftypefnx  {Function File} {F =} javafields (@var{OBJECT})
+
+Given a string with a Java class name @var{CLASSNAME} or a regular Java object @var{OBJECT}, this function returns a cell array containing the descriptions for all fields of the Java class @var{CLASSNAME} respectively the class of @var{OBJECT}. 
+
+Examples: 
+
+The first example shows how the fields of a class can be queried without creating an instance of the class. 
+@example
+Octave > f = javafields('java.lang.Double'); 
+Octave > size(f)
+ans =
+  1 10
+
+Octave > f@{7@}
+ans = public static final int java.lang.Double.MAX_EXPONENT 
+@end example
+
+The second example works with the fields of an instance of a class. Note that creation of a @code{java.lang.Double} object requires an initializer (in the example a value of 1.2 is specified). 
+@example
+Octave > o = javaObject('java.lang.Double', 1.2); 
+Octave > f = javafields(o); 
+Octave > size(f) 
+ans = 
+  1 10 
+
+Octave > f@{7@} 
+ans = public static final int java.lang.Double.MAX_EXPONENT 
+@end example
+
+@seealso{@ref{doc-java_set,,java_set},
+         @ref{doc-java_get,,java_get}}
+@end deftypefn
+
+@c ------------------------------------------------------------------------
+@node msgbox
+@subsection msgbox
+@anchor{doc-msgbox}
+@c - index -
+@cindex dialog, displaying a warning dialog
+@c - index -
+
+@deftypefn   {Function File} {F =} msgbox (@var{MESSAGE})
+@deftypefnx  {Function File} {F =} msgbox (@var{MESSAGE}, @var{TITLE})
+@deftypefnx  {Function File} {F =} msgbox (@var{MESSAGE}, @var{TITLE}, @var{ICON})
+
+Displays a @var{MESSAGE} using a dialog box. The parameter @var{TITLE} can be used to optionally decorate the dialog caption. 
+The third optional parameter @var{ICON} can be either @code{'error'}, @code{'help'} or @code{'warn'}
+and selectes the corresponding icon.
+If it is omitted, no icon is shown.
+
+Examples: The first example shows a dialog box without a caption text, whereas the second example specifies a caption text of its own. 
+The third example also demonstrates how a character 
+according to the @TeX{} symbol set can be specified. It is important to include a space character
+after the symbol code and how to embed a newline character (ASCII code 10) into the string.
+
+@example
+Octave > msgbox('This is an important message'); 
+Octave > msgbox('Do not forget to feed the cat.', 'Remember');
+Octave > msgbox(['I \heartsuit Octave!',10, ...
+                  ' Even if I hate it sometimes.'], ...
+                 'I Confess','warn');
+@end example
+
+@c @image{java-images/image003}
+
+@seealso{@ref{doc-errordlg,,errordlg},
+         @ref{doc-helpdlg,,helpdlg},
+         @ref{doc-warndlg,,warndlg}}
+@end deftypefn
+
+@c ------------------------------------------------------------------------
+@node errordlg
+@subsection errordlg
+@anchor{doc-errordlg}
+@c - index -
+@cindex dialog, displaying an error dialog
+@c - index -
+
+@deftypefn   {Function File} {F =} errordlg (@var{MESSAGE})
+@deftypefnx  {Function File} {F =} errordlg (@var{MESSAGE}, @var{TITLE})
+
+Displays the @var{MESSAGE} using an error dialog box. The @var{TITLE} can be used optionally to decorate the dialog caption instead of the default title "Error Dialog". 
+
+Examples: The first example shows a dialog box with default caption, whereas the second example specifies a its own caption 
+@example
+Octave > errordlg('Oops, an expected error occured'); 
+@end example
+@c @image{java-images/image001
+@example
+Octave > errordlg('Another error occured', 'Oops'); 
+@end example
+
+@seealso{@ref{doc-helpdlg,,helpdlg},
+         @ref{doc-inputdlg,,inputdlg},
+         @ref{doc-listdlg,,listdlg},
+         @ref{doc-questdlg,,questdlg},
+         @ref{doc-warndlg,,warndlg}}
+@end deftypefn
+
+@c ------------------------------------------------------------------------
+@node helpdlg
+@subsection helpdlg
+@anchor{doc-helpdlg}
+@c - index -
+@cindex dialog, displaying a help dialog
+@c - index -
+
+@deftypefn   {Function File} {F =} helpdlg (@var{MESSAGE})
+@deftypefnx  {Function File} {F =} helpdlg (@var{MESSAGE}, @var{TITLE})
+
+Displays the @var{MESSAGE} using a help dialog box. The help message can consist of multiple lines, separated by a newline character. The @var{TITLE} can be used optionally to decorate the dialog caption bar instead of the default title "Help Dialog". 
+
+Examples: The first example shows a dialog box with default caption, whereas the next two examples specify their own caption. Note that if the backslash escape notation is used in a double quoted string, it is immediately replaced by Octave with a newline.
+If it is contained in a single quoted string, it is not replaced by Octave, 
+but later by the dialog function.
+
+@example
+Octave > helpdlg('This is a short notice'); 
+Octave > helpdlg(['line #1',10,'line #2'], 'Inventory'); 
+Octave > helpdlg("1 eel\n9 buckazoids\n2 peas", 'Inventory'); 
+@end example
+
+@c @image{java-images/image004}
+
+@seealso{@ref{doc-errordlg,,errordlg},
+         @ref{doc-inputdlg,,inputdlg},
+         @ref{doc-listdlg,,listdlg},
+         @ref{doc-questdlg,,questdlg},
+         @ref{doc-warndlg,,warndlg}}
+@end deftypefn
+
+@c ------------------------------------------------------------------------
+@node inputdlg
+@subsection inputdlg
+@anchor{doc-inputdlg}
+@c - index -
+@cindex dialog, displaying an input dialog
+@c - index -
+
+@deftypefn   {Function File} {C =} inputdlg (@var{PROMPT})
+@deftypefnx  {Function File} {C =} inputdlg (@var{PROMPT}, @var{TITLE})
+@deftypefnx  {Function File} {C =} inputdlg (@var{PROMPT}, @var{TITLE}, @var{ROWSCOLS})
+@deftypefnx  {Function File} {C =} inputdlg (@var{PROMPT}, @var{TITLE}, @var{ROWSCOLS}, @var{DEFAULTS})
+
+Returns the user's inputs from a multi-textfield dialog box in form of a cell array of strings. If the user closed the dialog with the Cancel button, en empty cell array is returned. This can be checked with the @var{isempty} function. The first argument @var{PROMPT} is mandatory. It is a cell array with strings labeling each text field. The optional string @var{TITLE} can be used as the caption of the dialog. The size of the text fields can be defined by the argument @var{ROWSCOLS}, which can be either a scalar to define the number of columns used for each text field, a vector to define the number of rows for each text field individually, or a matrix to define the number of rows and columns for each text field individually. It is possible to place default values into the text fields by supplying a cell array of strings for the argument @var{DEFAULTS}. 
+
+Examples: The first example shows a simple usage of the input dialog box without defaults. 
+@example
+Octave > prompt = @{'Width','Height','Depth'@}; 
+Octave > dims = inputdlg(prompt, 'Enter Box Dimensions'); 
+Octave > volume = str2num(dims@{1@}) * ... 
+                  str2num(dims@{2@}) * str2num(dims@{3@}); 
+@end example
+
+@c @image{java-images/image005}
+
+The second example shows the application of a scalar for the number of rows and a cell array with default values. 
+@example
+Octave > prompt = @{'Width', 'Height', 'Depth'@}; 
+Octave > defaults = @{'1.1', '2.2', '3.3'@}; 
+Octave > title = 'Enter Box Dimensions'; 
+Octave > dims = inputdlg(prompt, title, 1, defaults); 
+Octave > dims 
+dims = 
+@{
+  [1,1] = 1.1 
+  [2,1] = 2.2 
+  [3,1] = 3.3 
+@}
+@end example
+
+@c @image{java-images/image006}
+
+The third example shows the application of row height and column width specification.. 
+@example
+Octave > prompt = @{'Width', 'Height', 'Depth'@}; 
+Octave > defaults = @{'1.1', '2.2', '3.3'@}; 
+Octave > rc = [1,10; 2,20; 3,30]; 
+Octave > title = 'Enter Box Dimensions'; 
+Octave > dims = inputdlg(prompt, title, rc, defaults); 
+@end example
+
+@c @image{java-images/image007}
+
+@seealso{@ref{doc-errordlg,,errordlg},
+         @ref{doc-helpdlg,,helpdlg},
+         @ref{doc-listdlg,,listdlg},
+         @ref{doc-questdlg,,questdlg},
+         @ref{doc-warndlg,,warndlg}}
+@end deftypefn
+
+@c ------------------------------------------------------------------------
+@node listdlg
+@subsection listdlg
+@anchor{doc-listdlg}
+@c - index -
+@cindex dialog, displaying a list dialog
+@c - index -
+
+@deftypefn   {Function File} {[SEL, OK] =} listdlg (@var{KEY}, @var{VALUE}[, @var{KEY}, @var{VALUE}, ...])
+
+This function returns the inputs from a list dialog box. The result is returned as a vector of indices and a flag. The vector @var{SEL} contains the 1-based indices of all list items selected by the user. The flag @var{OK} is 1 if the user closed the dialog with the OK Button, otherwise it is 0 and @var{SEL} is empty.. The arguments of this function are specified in the form of @var{KEY}, @var{VALUE} pairs. At least the @code{'ListString'} argument pair must be specified. It is also possible to preselect items in the list in order to provide a default selection. 
+
+The @var{KEY} and @var{VALUE} pairs can be selected from the following list: 
+
+@table @code
+@item ListString
+a cell array of strings comprising the content of the list.
+@item SelectionMode
+can be either @code{'single'} or @code{'multiple'}. 
+@item ListSize
+a vector with two elements @code{[width, height]} defining the size of the list field in pixels. 
+@item InitialValue
+a vector containing 1-based indices of preselected elements.
+@item Name
+a string to be used as the dialog caption.
+@item PromptString
+a cell array of strings to be displayed above the list field.
+@item OKString
+a string used to label the OK button.
+@item CancelString
+a string used to label the Cancel button.
+@end table
+
+Example:
+@example
+Octave > [s,ok] = listdlg('ListString', ... 
+                  @{'An item', 'another', 'yet another'@}, ...
+                  'Name', 'Selection Dialog', ...
+                  'SelectionMode', 'Multiple', ...
+                  'PromptString',['Select an item...',10,'...or multiple items']);
+
+Octave > imax = length(s); 
+Octave > for i=1:1:imax 
+Octave >   disp(s(i)); 
+Octave > end 
+@end example
+
+@c @image{java-images/image002}
+
+@seealso{@ref{doc-errordlg,,errordlg},
+         @ref{doc-helpdlg,,helpdlg},
+         @ref{doc-inputdlg,,inputdlg},
+         @ref{doc-questdlg,,questdlg},
+         @ref{doc-warndlg,,warndlg}}
+@end deftypefn
+
+@c ------------------------------------------------------------------------
+@node questdlg
+@subsection questdlg
+@anchor{doc-questdlg}
+@c - index -
+@cindex dialog, displaying a question dialog
+@c - index -
+
+@deftypefn   {Function File} {C =} questdlg (@var{MESSAGE}, @var{TITLE})
+@deftypefnx  {Function File} {C =} questdlg (@var{MESSAGE}, @var{TITLE}, @var{DEFAULT})
+@deftypefnx  {Function File} {C =} questdlg (@var{MESSAGE}, @var{TITLE}, @var{BTN1}, @var{BTN2}, @var{DEFAULT})
+@deftypefnx  {Function File} {C =} questdlg (@var{MESSAGE}, @var{TITLE}, @var{BTN1}, @var{BTN2}, @var{BTN3}, @var{DEFAULT})
+
+Displays the @var{MESSAGE} using a question dialog box with a caption @var{TITLE}. The dialog contains two or three buttons which all close the dialog. It returns the caption of the activated button.
+
+If only @var{MESSAGE} and @var{TITLE} are specified, three buttons with the default captions "Yes",
+"No", "Cancel" are used.
+The string @var{DEFAULT} identifies the default button, which is activated by pressing the ENTER key. It must match one of the strings given in @var{BTN1}, @var{BTN2} or @var{BTN3}. If only two button captions @var{BTN1} and @var{BTN2} are specified, the dialog will have only these two buttons. 
+
+
+Examples: The first example shows a dialog box with two buttons, whereas the next example demonstrates the use of three buttons. 
+@example
+Octave > questdlg('Select your gender', 'Sex', ... 
+                  'Male', 'Female', 'Female'); 
+@end example
+
+@c @image{java-images/image008}
+
+@example
+Octave > questdlg('Select your gender', 'Sex', ... 
+                  'Male', 'dont know', 'Female', 'Female'); 
+@end example
+
+@c @image{java-images/image009}
+
+@seealso{@ref{doc-errordlg,,errordlg},
+         @ref{doc-helpdlg,,helpdlg},
+         @ref{doc-inputdlg,,inputdlg},
+         @ref{doc-listdlg,,listdlg},
+         @ref{doc-warndlg,,warndlg}}
+@end deftypefn
+
+@c ------------------------------------------------------------------------
+@node warndlg
+@subsection warndlg
+@anchor{doc-warndlg}
+@c - index -
+@cindex dialog, displaying a warning dialog
+@c - index -
+
+@deftypefn   {Function File} {F =} warndlg (@var{MESSAGE})
+@deftypefnx  {Function File} {F =} warndlg (@var{MESSAGE}, @var{TITLE})
+
+Displays a @var{MESSAGE} using a warning dialog box. The @var{TITLE} can be used optionally to decorate the dialog caption instead of the default title "Warning Dialog". 
+
+Examples: The first example shows a dialog box with default caption, whereas the second example specifies a caption text of its own. The second example also demonstrates how a character 
+according to the @TeX{} symbol set can be specified. It is important to include a space character
+after the symbol code. The \n character can be used to start a new line. 
+The third example shows an alternate way to embed the newline character (the newline character has the ASCII code 10) into the string.
+Please refer to the Octave manual for the difference between single and double quoted
+strings.
+
+@example
+Octave > warndlg('An expected warning occured'); 
+Octave > warndlg('I \heartsuit Octave!\nEven if I hate her sometimes.', ...
+                 'Confession');
+Octave > warndlg(['I \heartsuit Octave!',10, ...
+                  ' Even if I hate her sometimes.'], ...
+                 'I Confess');
+@end example
+
+@c @image{java-images/image003}
+
+@seealso{@ref{doc-errordlg,,errordlg},
+         @ref{doc-helpdlg,,helpdlg},
+         @ref{doc-inputdlg,,inputdlg},
+         @ref{doc-listdlg,,listdlg},
+         @ref{doc-questdlg,,questdlg}}
+@end deftypefn
+
+@c ------------------------------------------------------------------------
+@node FAQ - Frequently asked Questions
+@section FAQ - Frequently asked Questions
+
+@menu
+* How to distinguish between Octave and Matlab?::  
+* How to make Java classes available?::  
+* How to create an instance of a Java class?::  
+* How can I handle memory limitations?::  
+* How to compile the java package in Octave?::  
+* Which @TeX{} symbols are implemented in the dialog functions?::  
+@end menu
+
+@c ------------------------------------------------------------------------
+@node How to distinguish between Octave and Matlab?
+@subsection How to distinguish between Octave and Matlab? 
+@anchor{doc-FAQ}
+@c - index -
+@cindex Octave and Matlab, how to distinguish between
+@c - index -
+
+Octave and Matlab are very similar, but handle Java slightly different. Therefore it may be necessary to detect the environment and use the appropriate functions. The following function can be used to detect the environment. Due to the persistent variable it can be called repeatedly without a heavy performance hit. 
+
+Example: 
+@example
+%% 
+%% Return: true if the environment is Octave. 
+%% 
+function ret = isOctave 
+  persistent retval; % speeds up repeated calls 
+
+  if isempty(retval)
+    retval = (exist('Octave_VERSION','builtin') > 0); 
+  end 
+
+  ret = retval; 
+end 
+@end example
+
+@c ------------------------------------------------------------------------
+@node How to make Java classes available?
+@subsection How to make Java classes available to Octave?
+@c - index -
+@cindex classpath, setting
+@cindex classpath, difference between static and dynamic
+@cindex static classpath
+@cindex dynamic classpath
+@cindex @code{classpath.txt}
+@cindex classes, making available to Octave
+@c - index -
+
+Java finds classes by searching a @var{classpath}. This is a list of Java archive files and/or directories containing class files.
+In Octave and Matlab the @var{classpath} is composed of two parts:
+@itemize
+@item the @var{static classpath} is initialized once at startup of the JVM, and
+@item the @var{dynamic classpath} which can be modified at runtime.
+@end itemize
+Octave searches the @var{static classpath} first, then the @var{dynamic classpath}.
+Classes appearing in the @var{static} as well as in the @var{dynamic classpath} will therefore be found in the @var{static classpath} and loaded from this location.
+@*
+Classes which shall be used regularly or must be available to all users should be 
+added to the @var{static classpath}. 
+The @var{static classpath} is populated once from the contents of a plain text file named @code{classpath.txt} when the Java Virtual Machine starts. This file contains one line for each individual classpath to be added to the @var{static classpath}.
+These lines can identify single class files, directories containing class files or Java archives with complete class file hierarchies.
+Comment lines starting with a @code{#} or a  @code{%} character are ignored.
+
+The search rules for the file @code{classpath.txt} are:
+@itemize
+@item First, Octave searches for the file @code{classpath.txt} in your home directory,
+If such a file is found, it is read and defines the initial @var{static classpath}.
+Thus it is possible to build an initial static classpath on a 'per user' basis.
+
+@item Next, Octave looks for another file @code{classpath.txt} in the package installation directory.
+This is where @code{javaclasspath.m} resides, usually something like @code{...\share\Octave\packages\java-1.2.8}. 
+You can find this directory by executing the command
+@example
+pkg list
+@end example
+If this file exists, its contents is also appended to the static classpath.
+Note that the archives and class directories defined in this file will affect all users.
+@end itemize
+
+Classes which are used only by a specific script should be placed in the @var{dynamic classpath}. This portion of the classpath can be modified at runtime using the @code{javaaddpath} and @code{javarmpath} functions. 
+
+Example: 
+@example
+Octave > base_path = 'C:/Octave/java_files'; 
+
+Octave > % add two JARchives to the dynamic classpath 
+Octave > javaaddpath([base_path, '/someclasses.jar']); 
+Octave > javaaddpath([base_path, '/moreclasses.jar']); 
+
+Octave > % check the dynamic classpath 
+Octave > p = javaclasspath; 
+Octave > disp(p@{1@}); 
+C:/Octave/java_files/someclasses.jar
+Octave > disp(p@{2@}); 
+C:/Octave/java_files/moreclasses.jar
+
+Octave > % remove the first element from the classpath 
+Octave > javarmpath([base_path, '/someclasses.jar']); 
+Octave > p = javaclasspath; 
+Octave > disp(p@{1@}); 
+C:/Octave/java_files/moreclasses.jar
+
+Octave > % provoke an error
+Octave > disp(p@{2@}); 
+error: A(I): Index exceeds matrix dimension. 
+@end example
+
+Another way to add files to the @var{dynamic classpath} exclusively for your user account is to use the file @code{.octaverc} which is stored in your home directory.
+All Octave commands in this file are executed each time you start a new instance of Octave. 
+The following example adds the directory @code{octave} to Octave's search path and 
+the archive @code{myclasses.jar} in this directory to the Java search path.
+@example
+% content of .octaverc:
+addpath('~/octave');
+javaaddpath('~/octave/myclasses.jar');
+@end example
+
+@c ------------------------------------------------------------------------
+@node How to create an instance of a Java class?
+@subsection How to create an instance of a Java class?
+@c - index -
+@cindex object, how to create
+@cindex instance, how to create
+@c - index -
+
+If your code shall work under Octave as well as Matlab you should use the function @code{javaObject} to create Java objects. The function @code{java_new} is Octave specific and does not exist in the Matlab environment.
+
+Example 1, suitable for Octave but not for Matlab: 
+@example
+   Passenger = java_new('package.FirstClass', row, seat);
+@end example
+
+Example 2, which works in Octave as well as in Matlab: 
+@example
+   Passenger = javaObject('package.FirstClass', row, seat);
+@end example
+
+@c ------------------------------------------------------------------------
+@node How can I handle memory limitations?
+@subsection How can I handle memory limitations?
+@cindex memory, limitations
+
+In order to execute Java code Octave creates a Java Virtual Machine (JVM). Such a JVM allocates a fixed amount of initial memory and may expand this pool up to a fixed maximum memory limit. The default values depend on the Java version (see @ref{doc-javamem,,javamem}).
+The memory pool is shared by all Java objects running in the JVM.
+This strict memory limit is intended mainly to avoid that runaway applications inside web browsers or in enterprise servers can consume all memory and crash the system. 
+When the maximum memory limit is hit, Java code will throw exceptions so that applications will fail or behave unexpectedly.
+
+In Octave as well as in Matlab, you can specify options for the creation of the JVM inside a file named @code{java.opts}. 
+This is a text file where you can enter lines containing @code{-X} and @code{-D} options handed to the JVM during initialization. 
+
+In Octave, the Java options file must be located in the directory where @code{javaclasspath.m} resides, i.e. the package installation directory, usually something like @var{...\share\Octave\packages\java-1.2.8}. You can find this directory by executing 
+@example
+pkg list
+@end example
+
+In Matlab, the options file goes into the @var{MATLABROOT/bin/ARCH} directory or in your personal Matlab startup directory (can be determined by a @samp{pwd} command). @var{MATLABROOT} is the Matlab root directory and @var{ARCH} is your system architecture, which you find by issuing the commands @samp{matlabroot} respectively @samp{computer('arch')}.
+
+The @code{-X} options allow you to increase the maximum amount of memory available to the JVM to 256 Megabytes by adding the following line to the @code{java.opts} file: 
+@example
+-Xmx256m 
+@end example
+
+The maximum possible amount of memory depends on your system. On a Windows system with 2 Gigabytes main memory you should be able to set this maximum to about 1 Gigabyte.
+
+If your application requires a large amount of memory from the beginning, you can also specify the initial amount of memory allocated to the JVM. Adding the following line to the @code{java.opts} file starts the JVM with 64 Megabytes of initial memory:
+@example
+-Xms64m 
+@end example
+
+For more details on the available @code{-X} options of your Java Virtual Machine issue the command @samp{java -X} at the operating system command prompt and consult the Java documentation.
+
+
+The @code{-D} options can be used to define system properties which can then be used by Java classes inside Octave. System properties can be retrieved by using the @code{getProperty()} methods of the @code{java.lang.System} class. The following example line defines the property @var{MyProperty} and assigns it the string @code{12.34}. 
+@example
+-DMyProperty=12.34
+@end example
+The value of this property can then be retrieved as a string by a Java object or in Octave:
+@example
+Octave > javaMethod('java.lang.System', 'getProperty', 'MyProperty');
+ans = 12.34
+@end example
+
+@seealso{@ref{doc-javamem,,javamem}}
+
+@c ------------------------------------------------------------------------
+@node How to compile the java package in Octave?
+@subsection How to compile the java package in Octave?
+@c - index -
+@cindex package, how to compile?
+@cindex compiling the java package, how? 
+@cindex java package, how to compile?
+@cindex java package, how to install?
+@cindex java package, how to uninstall?
+@c - index -
+
+Most Octave installations come with the @var{java} package pre-installed. In case you want to replace this package with a more recent version, you must perform the following steps: 
+
+@c ---------
+@menu
+* Uninstall the currently installed package @var{java}::  
+* Make sure that the build environment is configured properly::  
+* Compile and install the package in Octave::  
+* Test the java package installation::  
+@end menu
+
+@node Uninstall the currently installed package @var{java}
+@subsubsection Uninstall the currently installed package @var{java}
+Check whether the @var{java} package is already installed by issuing
+the @code{pkg list} command:
+@example
+Octave > pkg list
+Package Name  | Version | Installation directory
+--------------+---------+-----------------------
+        java *|   1.2.8 | /home/octavio/octave/java-1.2.8
+Octave > 
+@end example
+
+@noindent
+If the @var{java} package appears in the list you must uninstall it first by issuing the command 
+@example
+Octave > pkg uninstall java
+Octave > pkg list
+@end example
+
+Now the java package should not be listed anymore. If you have used the @var{java} package during the current session of Octave, you have to exit and restart Octave before you can uninstall the package. This is because the system keeps certain libraries in memory after they have been loaded once.
+
+@c ---------
+@node Make sure that the build environment is configured properly
+@subsubsection Make sure that the build environment is configured properly
+The installation process requires that the environment variable @code{JAVA_HOME} points to the Java Development Kit (JDK) on your computer. 
+
+@itemize @bullet
+@item
+Note that JDK is not equal to JRE (Java Runtime Environment). The JDK home directory contains subdirectories with include, library and executable files which are required to compile the @var{java} package. These files are not part of the JRE, so you definitely need the JDK. 
+@item
+Do not use backslashes but ordinary slashes in the path. 
+@end itemize
+
+Set the environment variable @code{JAVA_HOME} according to your local JDK installation. Please adapt the path in the following examples according to the JDK installation on your system.@*
+If you are using a Windows system that might be: 
+@example
+Octave > setenv("JAVA_HOME","C:/Java/jdk1.6.0_21");
+@end example
+Note, that on both system types, Windows as well as Linux, you must use the forward slash '/' as the separator, not the backslash '\'.
+
+If you are using a Linux system this would look probably more like: 
+@example
+Octave > setenv("JAVA_HOME","/usr/local/jdk1.6.0_21");
+@end example
+
+@c ---------
+@node Compile and install the package in Octave
+@subsubsection Compile and install the package in Octave
+If you have for example saved the package archive on your @var{z:} drive the command would be: 
+@example
+Octave> pkg install -verbose z:/java-1.2.8.tar.gz
+@end example
+or if you have Linux and the package file is stored in your home directory: 
+@example
+Octave > pkg install -verbose ~/java-1.2.8.tar.gz
+@end example
+The option @code{-verbose} will produce some lengthy output, which should not show any errors 
+(maybe a few warnings at best). 
+
+You can then produce a list of all installed packages: 
+@example
+Octave > pkg list
+@end example
+
+This list of packages should now include the package @var{java}:
+@example
+Octave > pkg list
+Package Name  | Version | Installation directory
+--------------+---------+-----------------------
+        java *|   1.2.8 | /home/octavio/octave/java-1.2.8
+Octave > 
+@end example
+
+@c ---------
+@node Test the java package installation
+@subsubsection Test the java package installation
+
+The following code creates a Java string object, which however is automatically converted to an Octave string:
+@example
+Octave > s = javaObject('java.lang.String', 'Hello OctaveString') 
+s = Hello OctaveString 
+@end example
+
+Note that the java package automatically transforms the Java String object to an Octave string. This means that you cannot apply Java String methods to the result. 
+
+This "auto boxing" scheme seems to be implemented for the following Java classes: 
+@itemize @bullet
+@item
+java.lang.Integer
+@item
+java.lang.Double 
+@item
+java.lang.Boolean 
+@item
+java.lang.String 
+@end itemize
+
+If you instead create an object for which no "auto-boxing" is implemented, @code{javaObject} returns the genuine Java object: 
+@example
+Octave > v = javaObject('java.util.Vector') 
+v = 
+<Java object: java.util.Vector> 
+Octave > v.add(12); 
+Octave > v.get(0) 
+ans = 12 
+@end example
+
+If you have created such a Java object, you can apply all methods of the Java class to the returned object. Note also that for some objects you must specify an initializer: 
+@example
+% not: 
+Octave > d = javaObject('java.lang.Double') 
+error: [java] java.lang.NoSuchMethodException: java.lang.Double 
+% but: 
+Octave > d = javaObject('java.lang.Double',12.34) 
+d = 12.340 
+@end example
+
+@c ------------------------------------------------------------------------
+@node Which @TeX{} symbols are implemented in the dialog functions?
+@subsection Which @TeX{} symbols are implemented in the dialog functions?
+@c - index -
+@cindex symbols, translation table
+@cindex @TeX{} symbols, translation table
+@cindex translation table for @TeX{} symbols
+@c - index -
+
+The dialog functions contain a translation table for @TeX{} like symbol codes. Thus messages and labels can be tailored to show some common mathematical symbols or Greek characters. No further @TeX{} formatting codes are supported. The characters are translated to their Unicode equivalent. However, not all characters may be displayable on your system. This depends on the font used by the Java system on your computer.
+
+Each @TeX{} symbol code must be terminated by a space character to make it distinguishable from the surrounding text. Therefore the string @samp{\alpha =12.0} will produce the desired result, whereas @samp{\alpha=12.0} would produce the literal text @var{'\alpha=12.0'}.
+
+@seealso{@ref{doc-errordlg,,errordlg},
+         @ref{doc-helpdlg,,helpdlg},
+         @ref{doc-inputdlg,,inputdlg},
+         @ref{doc-listdlg,,listdlg},
+         @ref{doc-msgbox,,msgbox},
+         @ref{doc-questdlg,,questdlg},
+         @ref{doc-warndlg,,warndlg}}
+
+@need 5000
+@c ---------------------------------
+@ifhtml
+@float Table
+The table below shows each @TeX{} character code and the corresponding Unicode character: 
+@multitable @columnfractions 0.18 0.1 0.05 0.18 0.1 0.05 0.18 0.1
+@item \alpha
+@tab 'Ī±'
+@tab
+@tab \beta
+@tab 'Ī²'
+@tab
+@tab \gamma
+@tab 'Ī³'
+@c ----------
+@item \delta
+@tab 'Ī“'
+@tab
+@tab \epsilon
+@tab 'Īµ'
+@tab
+@tab \zeta
+@tab 'Ī¶'
+@c ----------
+@item \eta
+@tab 'Ī·'
+@tab
+@tab \theta
+@tab 'Īø'
+@tab
+@tab \vartheta
+@tab 'Ļ‘'
+@c ----------
+@item \iota
+@tab 'Ī¹'
+@tab
+@tab \kappa
+@tab 'Īŗ'
+@tab
+@tab \lambda
+@tab 'Ī»'
+@c ----------
+@item \mu
+@tab 'Ī¼'
+@tab
+@tab \nu
+@tab 'Ī½'
+@tab
+@tab \xi
+@tab 'Ī¾'
+@c ----------
+@item \pi
+@tab 'Ļ€'
+@tab
+@tab \rho
+@tab 'Ļ'
+@tab
+@tab \sigma
+@tab 'Ļƒ'
+@c ----------
+@item \varsigma
+@tab 'Ļ‚'
+@tab
+@tab \tau
+@tab 'Ļ„'
+@tab
+@tab \phi
+@tab 'Ļ†'
+@c ----------
+@item \chi
+@tab 'Ļ‡'
+@tab
+@tab \psi
+@tab 'Ļˆ'
+@tab
+@tab \omega
+@tab 'Ļ‰'
+@c ----------
+@item \upsilon
+@tab 'Ļ…'
+@tab
+@tab \Gamma
+@tab 'Ī“'
+@tab
+@tab \Delta
+@tab 'Ī”'
+@c ----------
+@item \Theta
+@tab 'Ī˜'
+@tab
+@tab \Lambda
+@tab 'Ī›'
+@tab
+@tab \Pi
+@tab 'Ī '
+@c ----------
+@item \Xi
+@tab 'Īž'
+@tab
+@tab \Sigma
+@tab 'Ī£'
+@tab
+@tab \Upsilon
+@tab 'Ī„'
+@c ----------
+@item \Phi
+@tab 'Ī¦'
+@tab
+@tab \Psi
+@tab 'ĪØ'
+@tab
+@tab \Omega
+@tab 'Ī©'
+@c ----------
+@item \Im
+@tab 'ā„‘'
+@tab
+@tab \Re
+@tab 'ā„œ'
+@tab
+@tab \leq
+@tab 'ā‰¤'
+@c ----------
+@item \geq
+@tab 'ā‰„'
+@tab
+@tab \neq
+@tab 'ā‰ '
+@tab
+@tab \pm
+@tab 'Ā±'
+@c ----------
+@item \infty
+@tab 'āˆž'
+@tab
+@tab \partial
+@tab 'āˆ‚'
+@tab
+@tab \approx
+@tab 'ā‰ˆ'
+@c ----------
+@item \circ
+@tab 'āˆ˜'
+@tab
+@tab \bullet
+@tab 'ā€¢'
+@tab
+@tab \times
+@tab 'Ɨ'
+@c ----------
+@item \sim
+@tab '~'
+@tab
+@tab \nabla
+@tab 'āˆ‡'
+@tab
+@tab \ldots
+@tab 'ā€¦'
+@c ----------
+@item \exists
+@tab 'āˆƒ'
+@tab
+@tab \neg
+@tab 'Ā¬'
+@tab
+@tab \aleph
+@tab 'ā„µ'
+@c ----------
+@item \forall
+@tab 'āˆ€'
+@tab
+@tab \cong
+@tab 'ā‰…'
+@tab
+@tab \wp
+@tab 'ā„˜'
+@c ----------
+@item \propto
+@tab 'āˆ'
+@tab
+@tab \otimes
+@tab 'āŠ—'
+@tab
+@tab \oplus
+@tab 'āŠ•'
+@c ----------
+@item \oslash
+@tab 'āŠ˜'
+@tab
+@tab \cap
+@tab 'āˆ©'
+@tab
+@tab \cup
+@tab 'āˆŖ'
+@c ----------
+@item \ni
+@tab 'āˆ‹'
+@tab
+@tab \in
+@tab 'āˆˆ'
+@tab
+@tab \div
+@tab 'Ć·'
+@c ----------
+@item \equiv
+@tab 'ā‰”'
+@tab
+@tab \int
+@tab 'āˆ«'
+@tab
+@tab \perp
+@tab 'āŠ„'
+@c ----------
+@item \wedge
+@tab 'āˆ§'
+@tab
+@tab \vee
+@tab 'āˆØ'
+@tab
+@tab \supseteq
+@tab 'āŠ‡'
+@c ----------
+@item \supset
+@tab 'āŠƒ'
+@tab
+@tab \subseteq
+@tab 'āŠ†'
+@tab
+@tab \subset
+@tab 'āŠ‚'
+@c ----------
+@item \clubsuit
+@tab 'ā™£'
+@tab
+@tab \spadesuit
+@tab 'ā™ '
+@tab
+@tab \heartsuit
+@tab 'ā™„'
+@c ----------
+@item \diamondsuit
+@tab 'ā™¦'
+@tab
+@tab \copyright
+@tab 'Ā©'
+@tab
+@tab \leftarrow
+@tab 'ā†'
+@c ----------
+@item \uparrow
+@tab 'ā†‘'
+@tab
+@tab \rightarrow
+@tab 'ā†’'
+@tab
+@tab \downarrow
+@tab 'ā†“'
+@c ----------
+@item \leftrightarrow
+@tab 'ā†”'
+@tab
+@tab \updownarrow
+@tab 'ā†•'
+@tab
+@c ----------
+@end multitable
+@caption{@TeX{} character codes and the resulting symbols.}
+@end float
+@end ifhtml
+@c ---------------------------------
+@iftex
+@float Table
+The table below shows each @TeX{} character code and the corresponding Unicode character: 
+@multitable @columnfractions 0.18 0.1 0.05 0.18 0.1 0.05 0.18 0.1
+@headitem @TeX{} code
+@tab Symbol
+@tab
+@tab @TeX{} code
+@tab Symbol
+@tab
+@tab @TeX{} code
+@tab Symbol
+@c ----------
+@item \alpha
+@tab '@math{\alpha}'
+@tab
+@tab \beta
+@tab '@math{\beta}'
+@tab
+@tab \gamma
+@tab '@math{\gamma}'
+@c ----------
+@item \delta
+@tab '@math{\delta}'
+@tab
+@tab \epsilon
+@tab '@math{\epsilon}'
+@tab
+@tab \zeta
+@tab '@math{\zeta}'
+@c ----------
+@item \eta
+@tab '@math{\eta}'
+@tab
+@tab \theta
+@tab '@math{\theta}'
+@tab
+@tab \vartheta
+@tab '@math{\vartheta}'
+@c ----------
+@item \iota
+@tab '@math{\iota}'
+@tab
+@tab \kappa
+@tab '@math{\kappa}'
+@tab
+@tab \lambda
+@tab '@math{\lambda}'
+@c ----------
+@item \mu
+@tab '@math{\mu}'
+@tab
+@tab \nu
+@tab '@math{\nu}'
+@tab
+@tab \xi
+@tab '@math{\xi}'
+@c ----------
+@item \pi
+@tab '@math{\pi}'
+@tab
+@tab \rho
+@tab '@math{\rho}'
+@tab
+@tab \sigma
+@tab '@math{\sigma}'
+@c ----------
+@item \varsigma
+@tab '@math{\varsigma}'
+@tab
+@tab \tau
+@tab '@math{\tau}'
+@tab
+@tab \phi
+@tab '@math{\phi}'
+@c ----------
+@item \chi
+@tab '@math{\chi}'
+@tab
+@tab \psi
+@tab '@math{\psi}'
+@tab
+@tab \omega
+@tab '@math{\omega}'
+@c ----------
+@item \upsilon
+@tab '@math{\upsilon}'
+@tab
+@tab \Gamma
+@tab '@math{\Gamma}'
+@tab
+@tab \Delta
+@tab '@math{\Delta}'
+@c ----------
+@item \Theta
+@tab '@math{\Theta}'
+@tab
+@tab \Lambda
+@tab '@math{\Lambda}'
+@tab
+@tab \Pi
+@tab '@math{\Pi}'
+@c ----------
+@item \Xi
+@tab '@math{\Xi}'
+@tab
+@tab \Sigma
+@tab '@math{\Sigma}'
+@tab
+@tab \Upsilon
+@tab '@math{\Upsilon}'
+@c ----------
+@item \Phi
+@tab '@math{\Phi}'
+@tab
+@tab \Psi
+@tab '@math{\Psi}'
+@tab
+@tab \Omega
+@tab '@math{\Omega}'
+@c ----------
+@item \Im
+@tab '@math{\Im}'
+@tab
+@tab \Re
+@tab '@math{\Re}'
+@tab
+@tab \leq
+@tab '@math{\leq}'
+@c ----------
+@item \geq
+@tab '@math{\geq}'
+@tab
+@tab \neq
+@tab '@math{\neq}'
+@tab
+@tab \pm
+@tab '@math{\pm}'
+@c ----------
+@item \infty
+@tab '@math{\infty}'
+@tab
+@tab \partial
+@tab '@math{\partial}'
+@tab
+@tab \approx
+@tab '@math{\approx}'
+@c ----------
+@item \circ
+@tab '@math{\circ}'
+@tab
+@tab \bullet
+@tab '@math{\bullet}'
+@tab
+@tab \times
+@tab '@math{\times}'
+@c ----------
+@item \sim
+@tab '@math{\sim}'
+@tab
+@tab \nabla
+@tab '@math{\nabla}'
+@tab
+@tab \ldots
+@tab '@math{\ldots}'
+@c ----------
+@item \exists
+@tab '@math{\exists}'
+@tab
+@tab \neg
+@tab '@math{\neg}'
+@tab
+@tab \aleph
+@tab '@math{\aleph}'
+@c ----------
+@item \forall
+@tab '@math{\forall}'
+@tab
+@tab \cong
+@tab '@math{\cong}'
+@tab
+@tab \wp
+@tab '@math{\wp}'
+@c ----------
+@item \propto
+@tab '@math{\propto}'
+@tab
+@tab \otimes
+@tab '@math{\otimes}'
+@tab
+@tab \oplus
+@tab '@math{\oplus}'
+@c ----------
+@item \oslash
+@tab '@math{\oslash}'
+@tab
+@tab \cap
+@tab '@math{\cap}'
+@tab
+@tab \cup
+@tab '@math{\cup}'
+@c ----------
+@item \ni
+@tab '@math{\ni}'
+@tab
+@tab \in
+@tab '@math{\in}'
+@tab
+@tab \div
+@tab '@math{\div}'
+@c ----------
+@item \equiv
+@tab '@math{\equiv}'
+@tab
+@tab \int
+@tab '@math{\int}'
+@tab
+@tab \perp
+@tab '@math{\perp}'
+@c ----------
+@item \wedge
+@tab '@math{\wedge}'
+@tab
+@tab \vee
+@tab '@math{\vee}'
+@tab
+@tab \supseteq
+@tab '@math{\supseteq}'
+@c ----------
+@item \supset
+@tab '@math{\supset}'
+@tab
+@tab \subseteq
+@tab '@math{\subseteq}'
+@tab
+@tab \subset
+@tab '@math{\subset}'
+@c ----------
+@item \clubsuit
+@tab '@math{\clubsuit}'
+@tab
+@tab \spadesuit
+@tab '@math{\spadesuit}'
+@tab
+@tab \heartsuit
+@tab '@math{\heartsuit}'
+@c ----------
+@item \diamondsuit
+@tab '@math{\diamondsuit}'
+@tab
+@tab \copyright
+@tab '@math{\copyright}'
+@tab
+@tab \leftarrow
+@tab '@math{\leftarrow}'
+@c ----------
+@item \uparrow
+@tab '@math{\uparrow}'
+@tab
+@tab \rightarrow
+@tab '@math{\rightarrow}'
+@tab
+@tab \downarrow
+@tab '@math{\downarrow}'
+@c ----------
+@item \leftrightarrow
+@tab '@math{\leftrightarrow}'
+@tab
+@tab \updownarrow
+@tab '@math{\updownarrow}'
+@tab
+@c ----------
+@end multitable
+@caption{@TeX{} character codes and the resulting symbols.}
+@end float
+@end iftex
+@c ---------------------------------
--- a/doc/interpreter/octave.texi	Fri Nov 23 11:43:49 2012 -0500
+++ b/doc/interpreter/octave.texi	Fri Nov 23 15:29:13 2012 -0500
@@ -177,6 +177,7 @@
 * Object Oriented Programming::            
 * GUI Development::            
 * System Utilities::            
+* Java Interface:: 
 * Packages:: 
 * Dynamically Linked Functions::
 * Test and Demo Functions::
@@ -909,6 +910,7 @@
 @include oop.texi
 @include gui.texi
 @include system.texi
+@include java.texi
 @include package.texi
 
 @c maybe add again later, if anyone every writes any really interesting
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libinterp/dldfcn/__java__.cc	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,2039 @@
+/* Copyright (C) 2007 Michael Goffioul
+**
+** 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/>.
+*/
+
+#include "__java__.h"
+
+#include "parse.h"
+#include "Cell.h"
+#include "file-stat.h"
+#include "file-ops.h"
+#include "cmd-edit.h"
+#ifdef __WIN32__
+#include <windows.h>
+#endif
+#include "load-path.h"
+#include "oct-env.h"
+#include "oct-shlib.h"
+#include "oct-env.h"
+
+#include <algorithm>
+#include <map>
+#include <iostream>
+#include <fstream>
+
+#include <clocale>
+
+typedef jint (JNICALL *JNI_CreateJavaVM_t) (JavaVM **pvm, JNIEnv **penv, void *args);
+typedef jint (JNICALL *JNI_GetCreatedJavaVMs_t) (JavaVM **pvm, jsize bufLen, jsize *nVMs);
+
+extern "C" JNIEXPORT jboolean JNICALL Java_org_octave_Octave_call
+  (JNIEnv *, jclass, jstring, jobjectArray, jobjectArray);
+extern "C" JNIEXPORT void JNICALL Java_org_octave_OctaveReference_doFinalize
+  (JNIEnv *, jclass, jint);
+extern "C" JNIEXPORT void JNICALL Java_org_octave_Octave_doInvoke
+  (JNIEnv *, jclass, jint, jobjectArray);
+extern "C" JNIEXPORT void JNICALL Java_org_octave_Octave_doEvalString
+  (JNIEnv *, jclass, jstring);
+extern "C" JNIEXPORT jboolean JNICALL Java_org_octave_Octave_needThreadedInvokation
+  (JNIEnv *, jclass);
+
+static octave_value _java_new ( const octave_value_list& args );
+static octave_value _java_invoke ( const octave_value_list& args );
+  
+static JavaVM *jvm = 0;
+static bool jvm_attached = false;
+
+// Need to keep hold of the shared library handle until exit.
+static octave_shlib jvm_lib;
+
+static std::map<int,octave_value> listener_map;
+static std::map<int,octave_value> octave_ref_map;
+static int octave_java_refcount = 0;
+static long octave_thread_ID = -1;
+
+bool Vjava_convert_matrix = false;
+bool Vjava_unsigned_conversion = true;
+bool Vjava_debug = false;
+
+class JVMArgs
+{
+public:
+  JVMArgs ()
+    {
+      vm_args.version = JNI_VERSION_1_2;
+      vm_args.nOptions = 0;
+      vm_args.options = 0;
+      vm_args.ignoreUnrecognized = false;
+    }
+
+  ~JVMArgs ()
+    {
+      clean ();
+    }
+
+  JavaVMInitArgs* to_args ()
+    {
+      update ();
+      return &vm_args;
+    }
+
+  void add (const std::string& opt)
+    {
+      java_opts.push_back (opt);
+    }
+
+  void read_java_opts (const std::string& filename)
+    {
+      std::ifstream js (filename.c_str ());
+
+      if (! js.bad () && ! js.fail ())
+        {
+          std::string line;
+
+          while (! js.eof () && ! js.fail ())
+            {
+              std::getline (js, line);
+              if (line.length () > 2 && 
+                  (line.find ("-D") == 0 || line.find ("-X") == 0))
+                java_opts.push_back (line);
+              else if (line.length () > 0 && Vjava_debug)
+                std::cerr << "invalid JVM option, skipping: " << line << std::endl;
+            }
+        }
+    }
+
+private:
+  void clean ()
+    {
+      if (vm_args.options != 0)
+        {
+          for (int i=0; i<vm_args.nOptions; i++)
+            free (vm_args.options[i].optionString);
+          free (vm_args.options);
+
+          vm_args.options = 0;
+          vm_args.nOptions = 0;
+        }
+    }
+
+  void update ()
+    {
+      clean ();
+      if (java_opts.size () > 0)
+        {
+          int index = 0;
+
+          vm_args.nOptions = java_opts.size ();
+          vm_args.options = (JavaVMOption*) malloc (sizeof (JavaVMOption) * vm_args.nOptions);
+          for (std::list<std::string>::const_iterator it = java_opts.begin (); it != java_opts.end (); ++it)
+            {
+              if (Vjava_debug)
+                std::cout << *it << std::endl;
+              vm_args.options[index++].optionString = strdup ((*it).c_str ());
+            }
+          java_opts.clear ();
+        }
+    }
+
+private:
+  JavaVMInitArgs vm_args;
+  std::list<std::string> java_opts;
+};
+
+static dim_vector compute_array_dimensions (JNIEnv* jni_env, jobject obj);
+
+#ifdef __WIN32__
+static std::string read_registry_string (const std::string& key, const std::string& value)
+{
+  HKEY hkey;
+  DWORD len;
+  std::string retval = "";
+
+  if (! RegOpenKeyEx (HKEY_LOCAL_MACHINE, key.c_str (), 0, KEY_READ, &hkey))
+    {
+      if (! RegQueryValueEx (hkey, value.c_str (), 0, 0, 0, &len))
+        {
+          retval.resize (len);
+          if (RegQueryValueEx (hkey, value.c_str (), 0, 0, (LPBYTE)&retval[0], &len))
+            retval = "";
+	  else if (retval[len-1] == '\0')
+	    retval.resize (--len);
+        }
+      RegCloseKey (hkey);
+    }
+  return retval;
+}
+
+static std::string get_module_filename (HMODULE hMod)
+{
+  int n = 1024;
+  std::string retval(n, '\0');
+  bool found = false;
+
+  while (n < 65536)
+    {
+      int status = GetModuleFileName(hMod, &retval[0], n);
+
+      if (status < n)
+        {
+          retval.resize(n);
+          found = true;
+          break;
+        }
+      else
+        {
+          n *= 2;
+          retval.resize(n);
+        }
+    }
+  return (found ? retval : "");
+}
+
+static void set_dll_directory (const std::string& dir = "")
+{
+  typedef BOOL (WINAPI *dllfcn_t) (LPCTSTR path);
+
+  static dllfcn_t dllfcn = NULL;
+  static bool first = true;
+
+  if (! dllfcn && first)
+    {
+      HINSTANCE hKernel32 = GetModuleHandle ("kernel32");
+      dllfcn = reinterpret_cast<dllfcn_t> (GetProcAddress (hKernel32, "SetDllDirectoryA"));
+      first = false;
+    }
+
+  if (dllfcn)
+    dllfcn (dir.empty () ? NULL : dir.c_str ());
+}
+#endif
+
+static std::string get_module_path(const std::string& name, bool strip_name = true) 
+{
+  std::string retval;
+
+  retval = octave_env::make_absolute (load_path::find_file (name), 
+#ifdef HAVE_OCTAVE_32
+				      octave_env::getcwd ());
+#else
+                      octave_env::get_current_directory ());
+#endif
+
+  if (! retval.empty () && strip_name)
+    {
+      size_t pos = retval.rfind (file_ops::dir_sep_str () + name);
+
+      if (pos != std::string::npos)
+        retval.resize (pos);
+      else
+        throw std::string("No module path in ")+retval;
+    }
+  else
+    throw std::string("Could not find file ")+name;
+
+  return retval;
+}
+
+static std::string initial_java_dir (bool arch_dependent = false)
+{
+  static std::string path1;
+  static std::string path2;
+
+  if (arch_dependent)
+    {
+      if (path1.empty ())
+        path1 = get_module_path ("__java__.oct", true);
+      return path1;
+    }
+  else
+    {
+      if (path2.empty ())
+        path2 = get_module_path ("javaclasspath.m", true);
+      return path2;
+    }
+}
+
+/*
+ * Read the content of a file filename (usually "classpath.txt")
+ *
+ * Returns a string with all lines concatenated and separated 
+ * by the path separator character.
+ * The return string also starts with a path separator so that 
+ * it can be appended easily to a base classpath.
+ *
+ * The file "classpath.txt" must contain single lines, each 
+ * with a classpath.
+ * Comment lines starting with a '#' or a '%' in column 1 are allowed.
+ *
+ * On Windiows the usual path separator is  a ';', on Unix a ':'.
+ *
+ * Created: 28 Aug 2010 Martin Hepperle
+ */
+static std::string read_classpath_txt (const std::string& filepath)
+{
+    std::string classpath;
+
+    std::ifstream fs (filepath.c_str ());
+    
+    if (! fs.bad () && ! fs.fail ())
+    {
+        std::string line;
+
+        while (! fs.eof () && ! fs.fail ())
+        {
+            std::getline (fs, line);
+            if (line.length () > 1 )
+            {
+               if ( (line.at(0) == '#') ||
+                    (line.at(0) == '%')  )
+               {
+                  // this is a comment line: skip
+               }
+               else
+               {
+                  // prepend separator character
+                  classpath.append(dir_path::path_sep_str());
+                  // append content of line without trailing blanks
+                  int iLast = line.find_last_not_of(' ');
+                  classpath.append(file_ops::tilde_expand(line.substr(0,iLast+1)));
+               }
+            }
+        }
+    }
+    return ( classpath );
+}
+
+
+static std::string initial_class_path ()
+{
+   std::string retval = initial_java_dir ();
+
+   // find octave.jar file
+   if (! retval.empty ())
+    {
+      std::string jar_file = retval + file_ops::dir_sep_str () + "octave.jar";
+      file_stat jar_exists (jar_file);
+
+      if (jar_exists)
+       {
+         // initialize static classpath to octave.jar
+         retval = jar_file;
+
+         /*
+          * The base classpath has been set. 
+          * Try to find the optional file "classpath.txt" in two places.
+          * The users classes will take precedence over the settings 
+          * defined in the package directory
+          */
+         std::string str_filename = "classpath.txt";
+         std::string cp_file;
+         file_stat   cp_exists;
+         /*
+          * Try to read the file "classpath.txt" in the user's home directory
+          */
+         cp_file = file_ops::tilde_expand ( "~" + file_ops::dir_sep_str () + str_filename );
+         cp_exists = file_stat(cp_file);
+         if (cp_exists)
+          {
+            /*
+             * The file "classpath.txt" has been found: add its contents to the static classpath
+             */
+            std::string theClassPath = read_classpath_txt (cp_file);
+            retval.append(theClassPath);
+          }
+         /*
+          * Try to read a file "classpath.txt" in the package directory
+          */
+         cp_file = initial_java_dir () + file_ops::dir_sep_str () + str_filename;
+         cp_exists = file_stat(cp_file);
+         if (cp_exists)
+          {
+            /*
+             * The file "classpath.txt" has been found: add its contents to the static classpath
+             */
+            std::string theClassPath = read_classpath_txt (cp_file);
+            retval.append(theClassPath);
+          }
+       }
+      else
+       {
+        throw std::string("octave jar does not exist: ") + jar_file;
+       }
+    }
+  else
+    {
+     throw std::string("initial java dir is empty");
+    }
+
+  return retval;
+}
+
+static void initialize_jvm ()
+{
+  JNIEnv *current_env;
+
+  if (jvm) return;
+
+  const char *static_locale = setlocale(LC_ALL, NULL);
+  const std::string locale(static_locale);
+
+#if defined (__WIN32__)
+
+  HMODULE hMod = GetModuleHandle("jvm.dll");
+  std::string jvm_lib_path;
+  std::string old_cwd;
+
+  if (hMod == NULL)
+  {
+    // In windows, find the location of the JRE from the registry
+    // and load the symbol from the dll.
+    std::string key, value;
+
+    key = "software\\javasoft\\java runtime environment";
+
+    value = octave_env::getenv ("JAVA_VERSION");
+    if (value.empty ())
+    {
+      value = "Currentversion";
+      std::string regval = read_registry_string (key,value);
+      if (regval.empty ())
+        throw std::string ("unable to find Java Runtime Environment: ")+key+"::"+value;
+      value = regval;
+    }
+
+    key = key + "\\" + value;
+    value = "RuntimeLib";
+    jvm_lib_path = read_registry_string (key,value);
+    if (jvm_lib_path.empty())
+      throw std::string ("unable to find Java Runtime Environment: ")+key+"::"+value;
+
+    std::string jvm_bin_path;
+
+    value = "JavaHome";
+    jvm_bin_path = read_registry_string (key, value);
+    if (! jvm_bin_path.empty ())
+      {
+	jvm_bin_path = (jvm_bin_path + std::string ("\\bin"));
+#ifdef HAVE_OCTAVE_32
+    old_cwd = octave_env::getcwd ();
+#else
+    old_cwd = octave_env::get_current_directory ();
+#endif
+	set_dll_directory (jvm_bin_path);
+	octave_env::chdir (jvm_bin_path);
+      }
+  }
+  else
+  {
+    // JVM seems to be already loaded, better to use that DLL instead
+    // of looking in the registry, to avoid opening a different JVM.
+    jvm_lib_path = get_module_filename(hMod);
+    if (jvm_lib_path.empty())
+      throw std::string ("unable to find Java Runtime Environment");
+  }
+
+#else
+
+  std::string jvm_lib_path = JAVA_HOME+std::string("/jre/lib/")+JAVA_ARCH+"/server/libjvm.so";
+
+#endif
+
+  jsize nVMs = 0;
+
+# if !defined (__APPLE__) && !defined (__MACH__)
+
+  octave_shlib lib (jvm_lib_path);
+  if (!lib) 
+    throw std::string("unable to load Java Runtime Environment from ")+jvm_lib_path;
+
+#if defined (__WIN32__)
+  set_dll_directory ();
+  if (! old_cwd.empty ())
+    octave_env::chdir (old_cwd);
+#endif
+
+  JNI_CreateJavaVM_t create_vm = (JNI_CreateJavaVM_t)lib.search("JNI_CreateJavaVM");
+  JNI_GetCreatedJavaVMs_t get_vm = (JNI_GetCreatedJavaVMs_t)lib.search("JNI_GetCreatedJavaVMs");
+  if (!create_vm)
+    throw std::string("unable to find JNI_CreateJavaVM in ")+jvm_lib_path;
+  if (!get_vm)
+    throw std::string("unable to find JNI_GetCreatedJavaVMs in ")+jvm_lib_path;
+
+  if (get_vm(&jvm, 1, &nVMs) == 0 && nVMs > 0)
+
+#else
+
+  // FIXME: There exists a problem on the Mac platform that
+  //   octave_shlib lib (jvm_lib_path)
+  // doesn't work with 'not-bundled' *.oct files.
+
+  if (JNI_GetCreatedJavaVMs(&jvm, 1, &nVMs) == 0 && nVMs > 0)
+
+#endif
+
+  {
+    // At least one JVM exists, try to attach to it
+
+    switch (jvm->GetEnv((void**)&current_env, JNI_VERSION_1_2))
+    {
+      case JNI_EDETACHED:
+        // Attach the current thread
+        JavaVMAttachArgs vm_args;
+        vm_args.version = JNI_VERSION_1_2;
+        vm_args.name = (char*)"octave";
+        vm_args.group = NULL;
+        if (jvm->AttachCurrentThread((void**)&current_env, &vm_args) < 0)
+          throw std::string("JVM internal error, unable to attach octave to existing JVM");
+        break;
+      case JNI_EVERSION:
+        throw std::string("JVM internal error, the required JNI version is not supported");
+        break;
+      case JNI_OK:
+        // Don't do anything, the current thread is already attached to JVM
+        break;
+    }
+
+    jvm_attached = true;
+    //printf("JVM attached\n");
+  }
+  else
+  {
+    // No JVM exists, create one
+
+    JVMArgs vm_args;
+
+    vm_args.add ("-Djava.class.path=" + initial_class_path ());
+    vm_args.add ("-Doctave.java.path=" + initial_java_dir (true));
+    vm_args.add ("-Xrs");
+    vm_args.add ("-Djava.system.class.loader=org.octave.OctClassLoader");
+    vm_args.read_java_opts (initial_java_dir (false) + file_ops::dir_sep_str () + "java.opts");
+
+# if !defined (__APPLE__) && !defined (__MACH__)
+
+    if (create_vm (&jvm, &current_env, vm_args.to_args ()) != JNI_OK)
+      throw std::string("unable to start Java VM in ")+jvm_lib_path;
+    //printf("JVM created\n");
+  }
+  
+  jvm_lib = lib;
+
+#else
+
+  if (JNI_CreateJavaVM (&jvm, reinterpret_cast<void **>(&current_env),
+                       vm_args.to_args ()) != JNI_OK)
+      throw std::string("unable to start Java VM in ")+jvm_lib_path;
+
+  }
+
+#endif
+
+  setlocale(LC_ALL, locale.c_str());
+}
+
+static void terminate_jvm(void)
+{
+  if (jvm)
+    {
+      if (jvm_attached)
+        jvm->DetachCurrentThread ();
+      else
+        jvm->DestroyJavaVM ();
+      jvm = 0;
+      jvm_attached = false;
+
+      if (jvm_lib)
+        jvm_lib.close ();
+    }
+}
+
+std::string jstring_to_string (JNIEnv* jni_env, jstring s)
+{
+  std::string retval;
+  if (jni_env)
+    {
+      const char *cstr = jni_env->GetStringUTFChars (s, 0);
+      retval = cstr;
+      jni_env->ReleaseStringUTFChars (s, cstr);
+    }
+  return retval;
+}
+
+std::string jstring_to_string (JNIEnv* jni_env, jobject obj)
+{
+  std::string retval;
+  if (jni_env && obj)
+    {
+      jclass_ref cls (jni_env, jni_env->FindClass ("java/lang/String"));
+      if (cls)
+        {
+          if (jni_env->IsInstanceOf (obj, cls))
+            retval = jstring_to_string (jni_env, reinterpret_cast<jstring> (obj));
+        }
+    }
+  return retval;
+}
+
+static octave_value check_exception (JNIEnv* jni_env)
+{
+  octave_value retval;
+  jthrowable_ref ex (jni_env, jni_env->ExceptionOccurred ());
+
+  if (ex)
+    {
+      if (Vjava_debug)
+        jni_env->ExceptionDescribe ();
+      jni_env->ExceptionClear ();
+
+      jclass_ref jcls (jni_env, jni_env->GetObjectClass (ex));
+      jmethodID mID = jni_env->GetMethodID (jcls, "toString", "()Ljava/lang/String;");
+      jstring_ref js (jni_env, reinterpret_cast<jstring> (jni_env->CallObjectMethod (ex, mID)));
+      std::string msg = jstring_to_string (jni_env, js);
+
+      error ("[java] %s", msg.c_str ());
+    }
+  else
+    retval = Matrix ();
+  return retval;
+}
+
+static jclass find_octave_class (JNIEnv *jni_env, char *name)
+{
+  static std::string class_loader;
+  static jclass uiClass = 0;
+ 
+  jclass jcls = jni_env->FindClass (name);
+
+  if (jcls == 0)
+    {
+      jni_env->ExceptionClear ();
+
+      if (! uiClass)
+        {
+          if (class_loader.empty ())
+            {
+              jclass_ref syscls (jni_env, jni_env->FindClass ("java/lang/System"));
+              jmethodID mID = jni_env->GetStaticMethodID (syscls, "getProperty", "(Ljava/lang/String;)Ljava/lang/String;");
+              jstring_ref js (jni_env, jni_env->NewStringUTF ("octave.class.loader"));
+              js = reinterpret_cast<jstring> (jni_env->CallStaticObjectMethod (syscls, mID, jstring (js)));
+              class_loader = jstring_to_string (jni_env, jstring (js));
+              std::replace (class_loader.begin(), class_loader.end (), '.', '/');
+            }
+
+          jclass_ref uicls (jni_env, jni_env->FindClass (class_loader.c_str ()));
+
+          if (! uicls)
+            {
+              jni_env->ExceptionClear ();
+
+              /* Try the netbeans way */
+              std::replace (class_loader.begin(), class_loader.end (), '/', '.');
+              jclass_ref jcls2 (jni_env, jni_env->FindClass ("org/openide/util/Lookup"));
+              jmethodID mID = jni_env->GetStaticMethodID (jcls2, "getDefault", "()Lorg/openide/util/Lookup;");
+              jobject_ref lObj (jni_env, jni_env->CallStaticObjectMethod (jcls2, mID));
+              mID = jni_env->GetMethodID (jcls2, "lookup", "(Ljava/lang/Class;)Ljava/lang/Object;");
+              jclass_ref cLoaderCls (jni_env, jni_env->FindClass ("java/lang/ClassLoader"));
+              jobject_ref cLoader (jni_env, jni_env->CallObjectMethod (lObj, mID, jclass (cLoaderCls)));
+              mID = jni_env->GetMethodID (cLoaderCls, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
+              jstring_ref js (jni_env, jni_env->NewStringUTF (class_loader.c_str ()));
+              uicls = reinterpret_cast<jclass> (jni_env->CallObjectMethod (cLoader, mID, jstring (js)));
+            }
+
+          if (uicls)
+            uiClass = reinterpret_cast<jclass> (jni_env->NewGlobalRef (jclass (uicls)));
+        }
+
+      if (uiClass)
+        {
+          jmethodID mID = jni_env->GetStaticMethodID (uiClass, "findClass", "(Ljava/lang/String;)Ljava/lang/Class;");
+          jstring_ref js (jni_env, jni_env->NewStringUTF (name));
+          jcls = reinterpret_cast<jclass> (jni_env->CallStaticObjectMethod (uiClass, mID, jstring (js)));
+        }
+    }
+  return jcls;
+}
+
+static dim_vector compute_array_dimensions (JNIEnv* jni_env, jobject obj)
+{
+  jobjectArray_ref jobj (jni_env, reinterpret_cast<jobjectArray> (obj));
+  jclass_ref jcls (jni_env, jni_env->GetObjectClass (obj));
+  jclass_ref ccls (jni_env, jni_env->GetObjectClass (jcls));
+  jmethodID isArray_ID = jni_env->GetMethodID (ccls, "isArray", "()Z"),
+            getComponentType_ID = jni_env->GetMethodID (ccls, "getComponentType", "()Ljava/lang/Class;");
+  dim_vector dv (1, 1);
+  int idx = 0;
+
+  jobj.detach ();
+  while (jcls && jni_env->CallBooleanMethod (jcls, isArray_ID))
+    {
+      int len = (jobj ? jni_env->GetArrayLength (jobj) : 0);
+      if (idx >= dv.length ())
+        dv.resize (idx+1);
+      dv (idx) = len;
+      jcls = reinterpret_cast<jclass> (jni_env->CallObjectMethod (jcls, getComponentType_ID));
+      jobj = (len > 0 ? reinterpret_cast<jobjectArray> (jni_env->GetObjectArrayElement (jobj, 0)) : 0);
+      idx++;
+    }
+  return dv;
+}
+
+static jobject make_java_index (JNIEnv* jni_env, const octave_value_list& idx)
+{
+  jclass_ref ocls (jni_env, jni_env->FindClass ("[I"));
+  jobjectArray retval = jni_env->NewObjectArray (idx.length (), ocls, 0);
+  for (int i=0; i<idx.length (); i++)
+    {
+      idx_vector v = idx(i).index_vector ();
+      if (! error_state)
+        {
+          jintArray_ref i_array (jni_env, jni_env->NewIntArray (v.length ()));
+          jint *buf = jni_env->GetIntArrayElements (i_array, 0);
+          for (int k=0; k<v.length (); k++)
+            buf[k] = v(k);
+          jni_env->ReleaseIntArrayElements (i_array, buf, 0);
+          jni_env->SetObjectArrayElement (retval, i, i_array);
+          check_exception (jni_env);
+          if (error_state)
+            break;
+        }
+      else
+        break;
+    }
+  return retval;
+}
+
+static octave_value get_array_elements (JNIEnv* jni_env, jobject jobj, const octave_value_list& idx)
+{
+  octave_value retval;
+  jobject_ref resObj (jni_env);
+  jobject_ref java_idx (jni_env, make_java_index (jni_env, idx));
+  
+  if (! error_state)
+    {
+      jclass_ref helperClass (jni_env, find_octave_class (jni_env, (char*)"org/octave/ClassHelper"));
+      jmethodID mID = jni_env->GetStaticMethodID (helperClass, "arraySubsref", "(Ljava/lang/Object;[[I)Ljava/lang/Object;");
+      resObj = jni_env->CallStaticObjectMethod (helperClass, mID, jobj, jobject (java_idx));
+    }
+
+  if (resObj)
+    retval = box (jni_env, resObj);
+  else
+    retval = check_exception (jni_env);
+
+  return retval;
+}
+
+static octave_value set_array_elements (JNIEnv* jni_env, jobject jobj, const octave_value_list& idx, const octave_value& rhs)
+{
+  octave_value retval;
+  jclass_ref rhsCls (jni_env);
+  jobject_ref resObj (jni_env), rhsObj (jni_env);
+  jobject_ref java_idx (jni_env, make_java_index (jni_env, idx));
+  
+  if (! error_state && unbox (jni_env, rhs, rhsObj, rhsCls))
+    {
+      jclass_ref helperClass (jni_env, find_octave_class (jni_env, (char*)"org/octave/ClassHelper"));
+      jmethodID mID = jni_env->GetStaticMethodID (helperClass, "arraySubsasgn",
+          "(Ljava/lang/Object;[[ILjava/lang/Object;)Ljava/lang/Object;");
+      resObj = jni_env->CallStaticObjectMethod (helperClass, mID,
+          jobj, jobject (java_idx), jobject (rhsObj));
+    }
+
+  if (resObj)
+    retval = box (jni_env, resObj);
+  else
+    retval = check_exception (jni_env);
+
+  return retval;
+}
+
+static string_vector get_invoke_list (JNIEnv* jni_env, jobject jobj)
+{
+  std::list<std::string> name_list;
+  if (jni_env)
+  {
+    jclass_ref cls (jni_env, jni_env->GetObjectClass (jobj));
+    jclass_ref ccls (jni_env, jni_env->GetObjectClass (cls));
+    jmethodID getMethods_ID = jni_env->GetMethodID (ccls, "getMethods", "()[Ljava/lang/reflect/Method;"),
+              getFields_ID = jni_env->GetMethodID (ccls, "getFields", "()[Ljava/lang/reflect/Field;");
+    jobjectArray_ref mList (jni_env, reinterpret_cast<jobjectArray> (jni_env->CallObjectMethod (cls, getMethods_ID))),
+                     fList (jni_env, reinterpret_cast<jobjectArray> (jni_env->CallObjectMethod (cls, getFields_ID)));
+    int mLen = jni_env->GetArrayLength (mList), fLen = jni_env->GetArrayLength (fList);
+    jclass_ref mCls (jni_env, jni_env->FindClass ("java/lang/reflect/Method")),
+               fCls (jni_env, jni_env->FindClass ("java/lang/reflect/Field"));
+    jmethodID m_getName_ID = jni_env->GetMethodID (mCls, "getName", "()Ljava/lang/String;"),
+              f_getName_ID = jni_env->GetMethodID (fCls, "getName", "()Ljava/lang/String;");
+    for (int i=0; i<mLen; i++)
+      {
+        jobject_ref meth (jni_env, jni_env->GetObjectArrayElement (mList, i));
+        jstring_ref methName (jni_env, reinterpret_cast<jstring> (jni_env->CallObjectMethod (meth, m_getName_ID)));
+        name_list.push_back (jstring_to_string (jni_env, methName));
+      }
+    for (int i=0; i<fLen; i++)
+      {
+        jobject_ref field (jni_env, jni_env->GetObjectArrayElement (fList, i));
+        jstring_ref fieldName (jni_env, reinterpret_cast<jstring> (jni_env->CallObjectMethod (field, f_getName_ID)));
+        name_list.push_back (jstring_to_string (jni_env, fieldName));
+      }
+  }
+
+  string_vector v (name_list);
+  return v.sort (true);
+}
+
+static octave_value convert_to_string (JNIEnv *jni_env, jobject java_object, bool force, char type)
+{
+  octave_value retval;
+
+  if (jni_env && java_object)
+    {
+      jclass_ref cls (jni_env, jni_env->FindClass ("java/lang/String"));
+      if (jni_env->IsInstanceOf (java_object, cls))
+        retval = octave_value (jstring_to_string (jni_env, java_object), type);
+      else if (force)
+        {
+          cls = jni_env->FindClass ("[Ljava/lang/String;");
+          if (jni_env->IsInstanceOf (java_object, cls))
+            {
+              jobjectArray array = reinterpret_cast<jobjectArray> (java_object);
+              int len = jni_env->GetArrayLength (array);
+              Cell c (len, 1);
+              for (int i=0; i<len; i++)
+                {
+                  jstring_ref js (jni_env, reinterpret_cast<jstring> (jni_env->GetObjectArrayElement (array, i)));
+                  if (js)
+                    c(i) = octave_value (jstring_to_string (jni_env, js), type);
+                  else
+                    {
+                      c(i) = check_exception (jni_env);
+                      if (error_state)
+                        break;
+                    }
+                }
+              retval = octave_value (c);
+            }
+          else
+            {
+              cls = jni_env->FindClass ("java/lang/Object");
+              jmethodID mID = jni_env->GetMethodID (cls, "toString", "()Ljava/lang/String;");
+              jstring_ref js (jni_env, reinterpret_cast<jstring> (jni_env->CallObjectMethod (java_object, mID)));
+              if (js)
+                retval = octave_value (jstring_to_string (jni_env, js), type);
+              else
+                retval = check_exception (jni_env);
+            }
+        }
+      else
+        error ("unable to convert Java object to string");
+    }
+
+  return retval;
+}
+
+#define TO_JAVA(obj) dynamic_cast<octave_java*>((obj).internal_rep())
+
+octave_value box (JNIEnv* jni_env, jobject jobj, jclass jcls)
+{
+  octave_value retval;
+  jclass_ref cls (jni_env);
+
+  if (! jobj)
+    retval = Matrix ();
+
+  if (retval.is_undefined ())
+    {
+      cls = jni_env->FindClass ("java/lang/Integer");
+      if (jni_env->IsInstanceOf (jobj, cls))
+        {
+          jmethodID m = jni_env->GetMethodID (cls, "intValue", "()I");
+          retval = jni_env->CallIntMethod (jobj, m);
+        }
+    }
+
+  if (retval.is_undefined ())
+    {
+      cls = jni_env->FindClass ("java/lang/Double");
+      if (jni_env->IsInstanceOf (jobj, cls))
+        {
+          jmethodID m = jni_env->GetMethodID (cls, "doubleValue", "()D");
+          retval = jni_env->CallDoubleMethod (jobj, m);
+        }
+    }
+
+  if (retval.is_undefined ())
+    {
+      cls = jni_env->FindClass ("java/lang/Boolean");
+      if (jni_env->IsInstanceOf (jobj, cls))
+        {
+          jmethodID m = jni_env->GetMethodID (cls, "booleanValue", "()Z");
+          // MH retval = jni_env->CallBooleanMethod (jobj, m);
+          retval = (jni_env->CallBooleanMethod (jobj, m) ? true : false); 
+         }
+    }
+
+  if (retval.is_undefined ())
+    {
+      cls = jni_env->FindClass ("java/lang/String");
+      if (jni_env->IsInstanceOf (jobj, cls))
+        {
+          retval = jstring_to_string (jni_env, jobj);
+        }
+    }
+
+  if (retval.is_undefined () && Vjava_convert_matrix)
+    {
+      cls = find_octave_class (jni_env, (char*)"org/octave/Matrix");
+      if (jni_env->IsInstanceOf (jobj, cls))
+        {
+          jmethodID mID = jni_env->GetMethodID (cls, "getDims", "()[I");
+          jintArray_ref iv (jni_env, reinterpret_cast<jintArray> (jni_env->CallObjectMethod (jobj, mID)));
+          jint *iv_data = jni_env->GetIntArrayElements (jintArray (iv), 0);
+          dim_vector dims;
+          dims.resize (jni_env->GetArrayLength (jintArray (iv)));
+          for (int i=0; i<dims.length (); i++)
+            dims(i) = iv_data[i];
+          jni_env->ReleaseIntArrayElements (jintArray (iv), iv_data, 0);
+          mID = jni_env->GetMethodID (cls, "getClassName", "()Ljava/lang/String;");
+          jstring_ref js (jni_env, reinterpret_cast<jstring> (jni_env->CallObjectMethod (jobj, mID)));
+          std::string s = jstring_to_string (jni_env, js);
+          if (s == "double")
+            {
+              NDArray m (dims);
+              mID = jni_env->GetMethodID (cls, "toDouble", "()[D");
+              jdoubleArray_ref dv (jni_env, reinterpret_cast<jdoubleArray> (jni_env->CallObjectMethod (jobj, mID)));
+              jni_env->GetDoubleArrayRegion (dv, 0, m.length (), m.fortran_vec ());
+              retval = m;
+            }
+          else if (s == "byte")
+            {
+              if (Vjava_unsigned_conversion)
+                {
+                  uint8NDArray m (dims);
+                  mID = jni_env->GetMethodID (cls, "toByte", "()[B");
+                  jbyteArray_ref dv (jni_env, reinterpret_cast<jbyteArray> (jni_env->CallObjectMethod (jobj, mID)));
+                  jni_env->GetByteArrayRegion (dv, 0, m.length (), (jbyte*)m.fortran_vec ());
+                  retval = m;
+                }
+              else
+                {
+                  int8NDArray m (dims);
+                  mID = jni_env->GetMethodID (cls, "toByte", "()[B");
+                  jbyteArray_ref dv (jni_env, reinterpret_cast<jbyteArray> (jni_env->CallObjectMethod (jobj, mID)));
+                  jni_env->GetByteArrayRegion (dv, 0, m.length (), (jbyte*)m.fortran_vec ());
+                  retval = m;
+                }
+            }
+          else if (s == "integer")
+            {
+              if (Vjava_unsigned_conversion)
+                {
+                  uint32NDArray m (dims);
+                  mID = jni_env->GetMethodID (cls, "toInt", "()[I");
+                  jintArray_ref dv (jni_env, reinterpret_cast<jintArray> (jni_env->CallObjectMethod (jobj, mID)));
+                  jni_env->GetIntArrayRegion (dv, 0, m.length (), (jint*)m.fortran_vec ());
+                  retval = m;
+                }
+              else
+                {
+                  int32NDArray m (dims);
+                  mID = jni_env->GetMethodID (cls, "toInt", "()[I");
+                  jintArray_ref dv (jni_env, reinterpret_cast<jintArray> (jni_env->CallObjectMethod (jobj, mID)));
+                  jni_env->GetIntArrayRegion (dv, 0, m.length (), (jint*)m.fortran_vec ());
+                  retval = m;
+                }
+            }
+        }
+    }
+
+  if (retval.is_undefined ())
+    {
+      cls = find_octave_class (jni_env, (char*)"org/octave/OctaveReference");
+      if (jni_env->IsInstanceOf (jobj, cls))
+        {
+          jmethodID mID = jni_env->GetMethodID (cls, "getID", "()I");
+          int ID = jni_env->CallIntMethod (jobj, mID);
+          std::map<int,octave_value>::iterator it = octave_ref_map.find (ID);
+
+          if (it != octave_ref_map.end ())
+            retval = it->second;
+        }
+    }
+
+  if (retval.is_undefined ())
+    retval = octave_value (new octave_java (jobj, jcls));
+
+  return retval;
+}
+
+octave_value box_more (JNIEnv* jni_env, jobject jobj, jclass jcls)
+{
+  octave_value retval = box (jni_env, jobj, jcls);
+
+  if (retval.class_name () == "octave_java")
+    {
+      retval = octave_value ();
+
+      jclass_ref cls (jni_env);
+
+      if (retval.is_undefined ())
+        {
+          cls = jni_env->FindClass ("[D");
+          if (jni_env->IsInstanceOf (jobj, cls))
+            {
+              jdoubleArray jarr = reinterpret_cast<jdoubleArray> (jobj);
+              int len = jni_env->GetArrayLength (jarr);
+              if (len > 0)
+                {
+                  Matrix m (1, len);
+                  jni_env->GetDoubleArrayRegion (jarr, 0, len, m.fortran_vec ());
+                  retval = m;
+                }
+			  else
+                retval = Matrix ();
+            }
+        }
+	  
+	  if (retval.is_undefined ())
+	  {
+        cls = jni_env->FindClass ("[[D");
+        if (jni_env->IsInstanceOf (jobj, cls))
+          {
+            jobjectArray jarr = reinterpret_cast<jobjectArray> (jobj);
+            int rows = jni_env->GetArrayLength (jarr), cols = 0;
+            if (rows > 0)
+              {
+                Matrix m;
+                for (int r = 0; r < rows; r++)
+                  {
+                    jdoubleArray_ref row (jni_env, reinterpret_cast<jdoubleArray> (jni_env->GetObjectArrayElement (jarr, r)));
+                    if (m.length () == 0)
+                      {
+                        cols = jni_env->GetArrayLength (row);
+                        m.resize (cols, rows);
+                      }
+                    jni_env->GetDoubleArrayRegion (row, 0, cols, m.fortran_vec () + r * cols);
+                  }
+                retval = m.transpose ();
+              }
+            else
+              retval = Matrix();
+          }
+	  }
+
+      if (retval.is_undefined ())
+        {
+          cls = jni_env->FindClass ("[Ljava/lang/String;");
+          if (jni_env->IsInstanceOf (jobj, cls))
+            {
+              jobjectArray jarr = reinterpret_cast<jobjectArray> (jobj);
+              int len = jni_env->GetArrayLength (jarr);
+              Cell m(len, 1);
+              for (int i=0; i<len; i++)
+                {
+                  jstring_ref js (jni_env, reinterpret_cast<jstring> (jni_env->GetObjectArrayElement (jarr, i)));
+                  m(i) = jstring_to_string (jni_env, js);
+                }
+              retval = m;
+            }
+        }
+    }
+
+  if (retval.is_undefined ())
+    retval = octave_value (new octave_java (jobj, jcls));
+
+  return retval;
+}
+
+int unbox (JNIEnv* jni_env, const octave_value& val, jobject_ref& jobj, jclass_ref& jcls)
+{
+  int found = 1;
+
+  if (val.class_name () == "octave_java")
+    {
+      octave_java *ovj = TO_JAVA (val);
+      jobj = ovj->to_java ();
+      jobj.detach ();
+      jcls = jni_env->GetObjectClass (jobj);
+    }
+  else if (val.is_string ())
+    {
+      std::string s = val.string_value ();
+      jobj = jni_env->NewStringUTF (s.c_str ());
+      jcls = jni_env->GetObjectClass (jobj);
+    }
+  else if (val.is_bool_scalar ()) 
+   { 
+      bool bval = val.bool_value (); 
+      jclass_ref bcls (jni_env, jni_env->FindClass ("java/lang/Boolean")); 
+      jfieldID fid = jni_env->GetStaticFieldID (bcls, "TYPE", "Ljava/lang/Class;"); 
+      jmethodID mid = jni_env->GetMethodID (bcls, "<init>", "(Z)V"); 
+      jcls = reinterpret_cast<jclass> (jni_env->GetStaticObjectField (bcls, fid)); 
+      jobj = jni_env->NewObject (bcls, mid, bval); 
+   } 
+  else if (val.is_real_scalar ())
+    {
+      double dval = val.double_value ();
+      jclass_ref dcls (jni_env, jni_env->FindClass ("java/lang/Double"));
+      jfieldID fid = jni_env->GetStaticFieldID (dcls, "TYPE", "Ljava/lang/Class;");
+      jmethodID mid = jni_env->GetMethodID (dcls, "<init>", "(D)V");
+      jcls = reinterpret_cast<jclass> (jni_env->GetStaticObjectField (dcls, fid));
+      jobj = jni_env->NewObject (dcls, mid, dval);
+    }
+  else if (val.is_empty ())
+    {
+      jobj = 0;
+      //jcls = jni_env->FindClass ("java/lang/Object");
+      jcls = 0;
+    }
+  else if (!Vjava_convert_matrix && ((val.is_real_matrix () && (val.rows() == 1 || val.columns() == 1)) || val.is_range ()))
+    {
+      Matrix m = val.matrix_value ();
+      jdoubleArray dv = jni_env->NewDoubleArray (m.length ());
+      //for (int i=0; i<m.length (); i++)
+        jni_env->SetDoubleArrayRegion (dv, 0, m.length (), m.fortran_vec ());
+      jobj = dv;
+      jcls = jni_env->GetObjectClass (jobj);
+    }
+  else if (Vjava_convert_matrix && (val.is_matrix_type () || val.is_range()) && val.is_real_type ())
+    {
+      jclass_ref mcls (jni_env, find_octave_class (jni_env, (char*)"org/octave/Matrix"));
+      dim_vector dims = val.dims ();
+      jintArray_ref iv (jni_env, jni_env->NewIntArray (dims.length ()));
+      jint *iv_data = jni_env->GetIntArrayElements (jintArray (iv), 0);
+      for (int i=0; i<dims.length (); i++)
+        iv_data[i] = dims(i);
+      jni_env->ReleaseIntArrayElements (jintArray (iv), iv_data, 0);
+      if (val.is_double_type ())
+        {
+          NDArray m = val.array_value ();
+          jdoubleArray_ref dv (jni_env, jni_env->NewDoubleArray (m.length ()));
+          jni_env->SetDoubleArrayRegion (jdoubleArray (dv), 0, m.length (), m.fortran_vec ());
+          jmethodID mID = jni_env->GetMethodID (mcls, "<init>", "([D[I)V");
+          jobj = jni_env->NewObject (jclass (mcls), mID, jdoubleArray (dv), jintArray (iv));
+          jcls = jni_env->GetObjectClass (jobj);
+        }
+      else if (val.is_int8_type ())
+        {
+          int8NDArray m = val.int8_array_value ();
+          jbyteArray_ref bv (jni_env, jni_env->NewByteArray (m.length ()));
+          jni_env->SetByteArrayRegion (jbyteArray (bv), 0, m.length (), (jbyte*)m.fortran_vec ());
+          jmethodID mID = jni_env->GetMethodID (mcls, "<init>", "([B[I)V");
+          jobj = jni_env->NewObject (jclass (mcls), mID, jbyteArray (bv), jintArray (iv));
+          jcls = jni_env->GetObjectClass (jobj);
+        }
+      else if (val.is_uint8_type ())
+        {
+          uint8NDArray m = val.uint8_array_value ();
+          jbyteArray_ref bv (jni_env, jni_env->NewByteArray (m.length ()));
+          jni_env->SetByteArrayRegion (jbyteArray (bv), 0, m.length (), (jbyte*)m.fortran_vec ());
+          jmethodID mID = jni_env->GetMethodID (mcls, "<init>", "([B[I)V");
+          jobj = jni_env->NewObject (jclass (mcls), mID, jbyteArray (bv), jintArray (iv));
+          jcls = jni_env->GetObjectClass (jobj);
+        }
+      else if (val.is_int32_type ())
+        {
+          int32NDArray m = val.int32_array_value ();
+          jintArray_ref v (jni_env, jni_env->NewIntArray (m.length ()));
+          jni_env->SetIntArrayRegion (jintArray (v), 0, m.length (), (jint*)m.fortran_vec ());
+          jmethodID mID = jni_env->GetMethodID (mcls, "<init>", "([I[I)V");
+          jobj = jni_env->NewObject (jclass (mcls), mID, jintArray (v), jintArray (iv));
+          jcls = jni_env->GetObjectClass (jobj);
+        }
+      else
+        {
+          found = 0;
+          error ("cannot convert matrix of type `%s'", val.class_name ().c_str ());
+        }
+    }
+  else if (val.is_cellstr ())
+    {
+      Cell cellStr = val.cell_value ();
+      jclass_ref scls (jni_env, jni_env->FindClass ("java/lang/String"));
+      jobjectArray array = jni_env->NewObjectArray (cellStr.length (), scls, 0);
+      for (int i=0; i<cellStr.length (); i++)
+        {
+          jstring_ref jstr (jni_env, jni_env->NewStringUTF (cellStr(i).string_value().c_str()));
+          jni_env->SetObjectArrayElement (array, i, jstr);
+        }
+      jobj = array;
+      jcls = jni_env->GetObjectClass (jobj);
+    }
+  else
+    {
+      jclass rcls = find_octave_class (jni_env, (char*)"org/octave/OctaveReference");
+      jmethodID mID = jni_env->GetMethodID (rcls, "<init>", "(I)V");
+      int ID = octave_java_refcount++;
+
+      jobj = jni_env->NewObject (rcls, mID, ID);
+      jcls = rcls;
+      octave_ref_map[ID] = val;
+    }
+
+  return found;
+}
+
+int unbox (JNIEnv* jni_env, const octave_value_list& args, jobjectArray_ref& jobjs, jobjectArray_ref& jclss)
+{
+  int found = 1;
+  jclass_ref ocls (jni_env, jni_env->FindClass ("java/lang/Object"));
+  jclass_ref ccls (jni_env, jni_env->FindClass ("java/lang/Class"));
+
+  if (! jobjs)
+    jobjs = jni_env->NewObjectArray (args.length (), ocls, 0);
+  if (! jclss)
+    jclss = jni_env->NewObjectArray (args.length (), ccls, 0);
+  for (int i=0; i<args.length (); i++)
+    {
+      jobject_ref jobj (jni_env);
+      jclass_ref jcls (jni_env);
+
+      if (! unbox (jni_env, args(i), jobj, jcls))
+        {
+          found = 0;
+          break;
+        }
+      jni_env->SetObjectArrayElement (jobjs, i, jobj);
+      jni_env->SetObjectArrayElement (jclss, i, jcls);
+    }
+
+  return found;
+}
+
+
+static long get_current_thread_ID(JNIEnv *jni_env)
+{
+  if (jni_env)
+    {
+      jclass_ref cls (jni_env, jni_env->FindClass ("java/lang/Thread"));
+      jmethodID mID = jni_env->GetStaticMethodID (cls, "currentThread", "()Ljava/lang/Thread;");
+      jobject_ref jthread (jni_env, jni_env->CallStaticObjectMethod (cls, mID));
+      if (jthread)
+        {
+          jclass_ref jth_cls (jni_env, jni_env->GetObjectClass (jthread));
+          mID = jni_env->GetMethodID (jth_cls, "getId", "()J");
+		  long result = jni_env->CallLongMethod (jthread, mID);
+		  //printf("current java thread ID = %ld\n", result);
+		  return result;
+        }
+    }
+  return -1;
+}
+
+static int java_event_hook (void)
+{
+  JNIEnv *current_env = octave_java::thread_jni_env ();
+
+  if (current_env)
+    {
+      jclass_ref cls (current_env, find_octave_class (current_env, (char*)"org/octave/Octave"));
+      jmethodID mID = current_env->GetStaticMethodID (cls, "checkPendingAction", "()V");
+      current_env->CallStaticVoidMethod (cls, mID);
+    }
+  return 0;
+}
+
+static void initialize_java (void)
+{
+  if (! jvm)
+    {
+      try
+        {
+          initialize_jvm ();
+  
+	  JNIEnv *current_env = octave_java::thread_jni_env ();
+
+          octave_java::register_type ();
+          command_editor::add_event_hook (java_event_hook);
+          octave_thread_ID = get_current_thread_ID (current_env);
+          //printf("octave thread ID=%ld\n", octave_thread_ID);
+        }
+      catch (std::string msg)
+        {
+          error (msg.c_str ());
+        }
+    }
+}
+
+DEFUN_DLD (java_init, args, , "")
+{
+  
+  octave_value retval;
+
+  retval = 0;
+  initialize_java ();
+  if (! error_state)
+    retval = 1;
+
+  return retval;
+}
+
+DEFUN_DLD (java_exit, args, , "")
+{
+  octave_value retval;
+
+  terminate_jvm ();
+
+  return retval;
+}
+
+DEFUN_DLD (java_new, args, ,
+    "-*- texinfo -*-\n\
+@deftypefn {Loadable Function} {@var{obj} =} java_new (@var{name}, @var{arg1}, ...)\n\
+Create a Java object of class @var{name}, by calling the class constructor with the\n\
+arguments @var{arg1}, ...\n\
+\n\
+@example\n\
+  x = java_new (\"java.lang.StringBuffer\", \"Initial string\")\n\
+@end example\n\
+\n\
+@seealso{java_invoke, java_get, java_set}\n\
+@end deftypefn")
+{
+  return _java_new ( args );
+}
+
+
+DEFUN_DLD (javaObject, args, ,
+    "-*- texinfo -*-\n\
+@deftypefn {Loadable Function} {@var{obj} =} javaObject (@var{name}, @var{arg1}, ...)\n\
+Create a Java object of class @var{name}, by calling the class constructor with the\n\
+arguments @var{arg1}, ...\n\
+The first example creates an unitialized object, \
+while the second example supplies an initializer argument.\n\
+\n\
+@example\n\
+  x = javaObject (\"java.lang.StringBuffer\")\n\
+  x = javaObject (\"java.lang.StringBuffer\", \"Initial string\")\n\
+@end example\n\
+\n\
+@seealso{java_invoke, java_new, java_get, java_set}\n\
+@end deftypefn")
+{
+  return _java_new ( args );
+}
+
+// internally called from java_new and javaObject for backward compatibility
+static octave_value _java_new ( const octave_value_list& args )
+{
+  octave_value retval;
+
+  initialize_java ();
+  if (! error_state)
+    {
+      JNIEnv *current_env = octave_java::thread_jni_env ();
+
+      if (args.length () > 0)
+        {
+          std::string name = args(0).string_value ();
+          if (! error_state)
+          {
+            octave_value_list tmp;
+            for (int i=1; i<args.length (); i++)
+              tmp(i-1) = args(i);
+            retval = octave_java::do_java_create (current_env, name, tmp);
+          }
+          else
+            error ("java_new: first argument must be a string");
+        }
+      else
+        print_usage ();
+    }
+
+  return retval;
+}
+
+DEFUN_DLD (java_invoke, args, ,
+    "-*- texinfo -*-\n\
+@deftypefn {Loadable Function} {@var{ret} =} java_invoke (@var{obj}, @var{name}, @var{arg1}, ...)\n\
+Invoke the method @var{name} on the Java object @var{obj} with the arguments\n\
+@var{arg1}, ... For static methods, @var{obj} can be a string representing the\n\
+fully qualified name of the corresponding class. The function returns the result\n\
+of the method invocation.\n\
+\n\
+When @var{obj} is a regular Java object, the structure-like indexing can be used\n\
+as a shortcut syntax. For instance, the two following statements are equivalent\n\
+\n\
+@example\n\
+  ret = java_invoke (x, \"method1\", 1.0, \"a string\")\n\
+  ret = x.method1 (1.0, \"a string\")\n\
+@end example\n\
+\n\
+@seealso{java_get, java_set, java_new}\n\
+@end deftypefn")
+{
+  return _java_invoke ( args );
+}
+
+DEFUN_DLD (javaMethod, args, ,
+    "-*- texinfo -*-\n\
+@deftypefn {Loadable Function} {@var{ret} =} javaMethod (@var{name}, @var{obj}, @var{arg1}, ...)\n\
+Invoke the method @var{name} on the Java object @var{obj} with the arguments\n\
+@var{arg1}, ... For static methods, @var{obj} can be a string representing the\n\
+fully qualified name of the corresponding class. The function returns the result\n\
+of the method invocation.\n\
+\n\
+When @var{obj} is a regular Java object, the structure-like indexing can be used\n\
+as a shortcut syntax. For instance, the two following statements are equivalent\n\
+\n\
+@example\n\
+  ret = javaMethod (\"method1\", x, 1.0, \"a string\")\n\
+  ret = x.method1 (1.0, \"a string\")\n\
+@end example\n\
+\n\
+@seealso{java_get, java_set, java_new}\n\
+@end deftypefn")
+{
+  octave_value retval;
+
+  if (args.length() > 1)
+    {
+    // swap first two arguments
+      octave_value_list tmp;
+      tmp(0) = args(1);
+      tmp(1) = args(0);
+      // copy remaining arguments
+      for (int i=2; i<args.length (); i++)
+        tmp(i) = args(i);
+        retval = _java_invoke ( tmp );
+     }
+     else
+     {
+       print_usage ();
+     }
+  return retval;
+}
+
+// internally called from java_invoke and javaMethod for backward compatibility
+static octave_value _java_invoke ( const octave_value_list& args )
+{
+  octave_value retval;
+
+  initialize_java ();
+  if (! error_state)
+    {
+      JNIEnv *current_env = octave_java::thread_jni_env ();
+
+      if (args.length() > 1)
+        {
+          std::string name = args(1).string_value ();
+          if (! error_state)
+            {
+              octave_value_list tmp;
+              for (int i=2; i<args.length (); i++)
+                tmp(i-2) = args(i);
+
+              if (args(0).class_name () == "octave_java")
+                {
+                  octave_java *jobj = TO_JAVA (args(0));
+                  retval = jobj->do_java_invoke (current_env, name, tmp);
+                }
+              else if (args(0).is_string ())
+                {
+                  std::string cls = args(0).string_value ();
+                  retval = octave_java::do_java_invoke (current_env, cls, name, tmp);
+                }
+              else
+                error ("java_invoke: first argument must be a Java object or a string");
+            }
+          else
+            error ("java_invoke: second argument must be a string");
+        }
+      else
+        print_usage ();
+    }
+
+  return retval;
+}
+
+DEFUN_DLD (java_get, args, ,
+    "-*- texinfo -*-\n\
+@deftypefn {Loadable Function} {@var{val} =} java_get (@var{obj}, @var{name})\n\
+Get the value of the field @var{name} of the Java object @var{obj}. For\n\
+static fields, @var{obj} can be a string representing the fully qualified\n\
+name of the corresponding class.\n\
+\n\
+When @var{obj} is a regular Java object, the structure-like indexing can be used\n\
+as a shortcut syntax. For instance, the two following statements are equivalent\n\
+\n\
+@example\n\
+  java_get (x, \"field1\")\n\
+  x.field1\n\
+@end example\n\
+\n\
+@seealso{java_set, java_invoke, java_new}\n\
+@end deftypefn")
+{
+  octave_value retval;
+
+  initialize_java ();
+  if (! error_state)
+    {
+      JNIEnv *current_env = octave_java::thread_jni_env ();
+
+      if (args.length () == 2)
+        {
+          std::string name = args(1).string_value ();
+          if (! error_state)
+            {
+              if (args(0).class_name () == "octave_java")
+                {
+                  octave_java *jobj = TO_JAVA (args(0));
+                  retval = jobj->do_java_get (current_env, name);
+                }
+              else if (args(0).is_string ())
+                {
+                  std::string cls = args(0).string_value ();
+                  retval = octave_java::do_java_get (current_env, cls, name);
+                }
+              else
+                error ("java_get: first argument must be a Java object or a string");
+            }
+          else
+            error ("java_get: second argument must be a string");
+        }
+      else
+        print_usage ();
+    }
+
+  return retval;
+}
+
+DEFUN_DLD (java_set, args, ,
+    "-*- texinfo -*-\n\
+@deftypefn {Loadable Function} {@var{obj} =} java_set (@var{obj}, @var{name}, @var{val})\n\
+Set the value of the field @var{name} of the Java object @var{obj} to @var{val}.\n\
+For static fields, @var{obj} can be a string representing the fully qualified named\n\
+of the corresponding Java class.\n\
+\n\
+When @var{obj} is a regular Java object, the structure-like indexing can be used as\n\
+a shortcut syntax. For instance, the two following statements are equivalent\n\
+\n\
+@example\n\
+  java_set (x, \"field1\", val)\n\
+  x.field1 = val\n\
+@end example\n\
+\n\
+@seealso{java_get, java_invoke, java_new}\n\
+@end deftypefn")
+{
+  octave_value retval;
+
+  initialize_java ();
+  if (! error_state)
+    {
+      JNIEnv *current_env = octave_java::thread_jni_env ();
+
+      if (args.length () == 3)
+        {
+          std::string name = args(1).string_value ();
+          if (! error_state)
+            {
+              if (args(0).class_name () == "octave_java")
+                {
+                  octave_java *jobj = TO_JAVA (args(0));
+                  retval = jobj->do_java_set (current_env, name, args(2));
+                }
+              else if (args(0).is_string ())
+                {
+                  std::string cls = args(0).string_value ();
+                  retval = octave_java::do_java_set (current_env, cls, name, args(2));
+                }
+              else
+                error ("java_set: first argument must be a Java object or a string");
+            }
+          else
+            error ("java_set: second argument must be a string");
+        }
+      else
+        print_usage ();
+    }
+
+  return retval;
+}
+
+DEFUN_DLD (java2mat, args, , "")
+{
+  octave_value_list retval;
+
+  initialize_java ();
+  if (! error_state)
+    {
+      JNIEnv *current_env = octave_java::thread_jni_env ();
+
+      if (args.length () == 1)
+        {
+          if (args(0).class_name () == "octave_java")
+            {
+              octave_java *jobj = TO_JAVA (args(0));
+              retval(0) = box_more (current_env, jobj->to_java (), 0);
+            }
+          else
+            retval(0) = args(0);
+        }
+      else
+        print_usage ();
+    }
+
+  return retval;
+}
+
+DEFUN_DLD (__java__, args, , "")
+{
+  return octave_value ();
+}
+
+DEFUN_DLD (java_convert_matrix, args, nargout, "")
+{
+  return SET_INTERNAL_VARIABLE (java_convert_matrix);
+}
+
+DEFUN_DLD (java_unsigned_conversion, args, nargout, "")
+{
+  return SET_INTERNAL_VARIABLE (java_unsigned_conversion);
+}
+
+DEFUN_DLD (java_debug, args, nargout, "")
+{
+  return SET_INTERNAL_VARIABLE (java_debug);
+}
+
+JNIEXPORT jboolean JNICALL Java_org_octave_Octave_call
+  (JNIEnv *env, jclass, jstring funcName, jobjectArray argin, jobjectArray argout)
+{
+  std::string fname = jstring_to_string (env, funcName);
+  int nargout = env->GetArrayLength (argout);
+  int nargin = env->GetArrayLength (argin);
+  octave_value_list varargin, varargout;
+
+  for (int i=0; i<nargin; i++)
+    varargin(i) = box (env, env->GetObjectArrayElement (argin, i), 0);
+  varargout = feval (fname, varargin, nargout);
+
+  if (! error_state)
+    {
+      jobjectArray_ref out_objs (env, argout), out_clss (env);
+
+      out_objs.detach ();
+      if (unbox (env, varargout, out_objs, out_clss))
+        return true;
+    }
+
+  return false;
+}
+
+JNIEXPORT void JNICALL Java_org_octave_OctaveReference_doFinalize
+  (JNIEnv *env, jclass, jint ID)
+{
+  octave_ref_map.erase (ID);
+}
+
+JNIEXPORT void JNICALL Java_org_octave_Octave_doInvoke
+  (JNIEnv *env, jclass, jint ID, jobjectArray args)
+{
+  std::map<int,octave_value>::iterator it = octave_ref_map.find (ID);
+
+  if (it != octave_ref_map.end ())
+    {
+      octave_value val = it->second;
+      int len = env->GetArrayLength (args);
+      octave_value_list oct_args;
+
+      for (int i=0; i<len; i++)
+        {
+          jobject_ref jobj (env, env->GetObjectArrayElement (args, i));
+          oct_args(i) = box (env, jobj, 0);
+          if (error_state)
+            break;
+        }
+
+      if (! error_state)
+        {
+          BEGIN_INTERRUPT_WITH_EXCEPTIONS;
+
+          if (val.is_function_handle ())
+            {
+              octave_function *fcn = val.function_value ();
+              feval (fcn, oct_args);
+            }
+          else if (val.is_cell () && val.length () > 0 &&
+              (val.rows () == 1 || val.columns() == 1) &&
+              val.cell_value()(0).is_function_handle ())
+            {
+              Cell c = val.cell_value ();
+              octave_function *fcn = c(0).function_value ();
+
+              for (int i=1; i<c.length (); i++)
+                oct_args(len+i-1) = c(i);
+
+              if (! error_state)
+                feval (fcn, oct_args);
+            }
+		  else
+            error ("trying to invoke non-invocable object");
+
+          END_INTERRUPT_WITH_EXCEPTIONS;
+        }
+    }
+}
+
+JNIEXPORT void JNICALL Java_org_octave_Octave_doEvalString
+  (JNIEnv *env, jclass, jstring cmd)
+{
+  std::string s = jstring_to_string (env, cmd);
+  int pstatus;
+
+  eval_string (s, false, pstatus, 0);
+}
+
+JNIEXPORT jboolean JNICALL Java_org_octave_Octave_needThreadedInvokation
+  (JNIEnv *env, jclass)
+{
+  return (get_current_thread_ID (env) != octave_thread_ID);
+}
+
+// octave_java class definition
+
+DEFINE_OCTAVE_ALLOCATOR (octave_java);
+
+DEFINE_OV_TYPEID_FUNCTIONS_AND_DATA (octave_java,
+		"octave_java",
+		"octave_java");
+
+dim_vector octave_java::dims(void) const
+{
+  JNIEnv *current_env = thread_jni_env ();
+
+  if (current_env && java_object)
+    return compute_array_dimensions (current_env, java_object);
+  else
+    return dim_vector (1, 1);
+}
+
+JNIEnv* octave_java::thread_jni_env (void)
+{
+  JNIEnv *env = NULL;
+
+  if (jvm)
+    jvm->GetEnv ((void**)&env, JNI_VERSION_1_2);
+
+  return env;
+}
+
+octave_value_list octave_java::subsref(const std::string& type, const std::list<octave_value_list>& idx, int nargout)
+{
+  octave_value_list retval;
+  int skip = 1;
+
+  JNIEnv *current_env = thread_jni_env ();
+
+  switch (type[0])
+    {
+      case '.':
+        if (type.length () > 1 && type[1] == '(')
+          {
+            octave_value_list ovl;
+            count++;
+            ovl(0) = octave_value (this);
+            ovl(1) = (idx.front ())(0);
+            std::list<octave_value_list>::const_iterator it = idx.begin ();
+            ovl.append (*++it);
+            retval = feval (std::string ("java_invoke"), ovl, 1);
+            skip++;
+          }
+        else
+          {
+            octave_value_list ovl;
+            count++;
+            ovl(0) = octave_value (this);
+            ovl(1) = (idx.front ())(0);
+            retval = feval (std::string ("java_get"), ovl, 1);
+          }
+        break;
+      case '(':
+        if (current_env)
+          retval = get_array_elements (current_env, to_java (), idx.front ());
+        break;
+      default:
+        error ("subsref: Java object cannot be indexed with %c", type[0]);
+        break;
+    }
+
+  if (idx.size () > 1 && type.length () > 1)
+    retval = retval(0).next_subsref (nargout, type, idx, skip);
+
+  return retval;
+}
+
+octave_value octave_java::subsasgn (const std::string& type, const std::list<octave_value_list>&idx, const octave_value &rhs)
+{
+  octave_value retval;
+
+  JNIEnv *current_env = thread_jni_env ();
+
+  switch (type[0])
+    {
+      case '.':
+        if (type.length () == 1)
+          {
+            // field assignment
+            octave_value_list ovl;
+            count++;
+            ovl(0) = octave_value (this);
+            ovl(1) = (idx.front ())(0);
+            ovl(2) = rhs;
+            feval ("java_set", ovl, 0);
+            if (! error_state)
+              {
+                count++;
+                retval = octave_value (this);
+              }
+          }
+        else if (type.length () > 2 && type[1] == '(')
+          {
+            std::list<octave_value_list> new_idx;
+            std::list<octave_value_list>::const_iterator it = idx.begin ();
+            new_idx.push_back (*it++);
+            new_idx.push_back (*it++);
+            octave_value_list u = subsref (type.substr (0, 2), new_idx, 1);
+            if (! error_state)
+              {
+                std::list<octave_value_list> next_idx (idx);
+                next_idx.erase (next_idx.begin ());
+                next_idx.erase (next_idx.begin ());
+                u(0).subsasgn (type.substr (2), next_idx, rhs);
+                if (! error_state)
+                  {
+                    count++;
+                    retval = octave_value (this);
+                  }
+              }
+	  }
+        else if (type[1] == '.')
+          {
+            octave_value_list u = subsref (type.substr (0, 1), idx, 1);
+            if (! error_state)
+              {
+                std::list<octave_value_list> next_idx (idx);
+                next_idx.erase (next_idx.begin ());
+                u(0).subsasgn (type.substr (1), next_idx, rhs);
+                if (! error_state)
+                  {
+                    count++;
+                    retval = octave_value (this);
+                  }
+              }
+          }
+        else
+          error ("invalid indexing/assignment on Java object");
+        break;
+      case '(':
+        if (current_env)
+          {
+            set_array_elements (current_env, to_java (), idx.front (), rhs);
+            if (! error_state)
+              {
+                count++;
+                retval = octave_value (this);
+              }
+          }
+        break;
+      default:
+        error ("Java object cannot be indexed with %c", type[0]);
+        break;
+    }
+
+  return retval;
+}
+
+string_vector octave_java::map_keys (void) const
+{
+  JNIEnv *current_env = thread_jni_env ();
+
+  if (current_env)
+    return get_invoke_list (current_env, to_java ());
+  else
+    return string_vector ();
+}
+
+octave_value octave_java::convert_to_str_internal (bool, bool force, char type) const
+{
+  JNIEnv *current_env = thread_jni_env ();
+
+  if (current_env)
+    return convert_to_string (current_env, to_java (), force, type);
+  else
+    return octave_value ("");
+}
+
+octave_value octave_java::do_java_invoke (JNIEnv* jni_env, const std::string& name,
+    const octave_value_list& args)
+{
+  octave_value retval;
+
+  if (jni_env)
+    {
+      jobjectArray_ref arg_objs (jni_env), arg_types (jni_env);
+      if (unbox (jni_env, args, arg_objs, arg_types))
+        {
+          jclass_ref helperClass (jni_env, find_octave_class (jni_env, (char*)"org/octave/ClassHelper"));
+          jmethodID mID = jni_env->GetStaticMethodID (helperClass, "invokeMethod",
+              "(Ljava/lang/Object;Ljava/lang/String;[Ljava/lang/Object;[Ljava/lang/Class;)Ljava/lang/Object;");
+          jstring_ref methName (jni_env, jni_env->NewStringUTF (name.c_str ()));
+          jobjectArray_ref resObj (jni_env, reinterpret_cast<jobjectArray> (jni_env->CallStaticObjectMethod (helperClass, mID,
+              to_java (), jstring (methName), jobjectArray (arg_objs), jobjectArray (arg_types))));
+          if (resObj)
+            retval = box (jni_env, resObj);
+          else
+            retval = check_exception (jni_env);
+        }
+    }
+  return retval;
+}
+
+octave_value octave_java:: do_java_invoke (JNIEnv* jni_env, const std::string& class_name,
+    const std::string& name, const octave_value_list& args)
+{
+  octave_value retval;
+
+  if (jni_env)
+    {
+      jobjectArray_ref arg_objs (jni_env), arg_types (jni_env);
+      if (unbox (jni_env, args, arg_objs, arg_types))
+        {
+          jclass_ref helperClass (jni_env, find_octave_class (jni_env, (char*)"org/octave/ClassHelper"));
+          jmethodID mID = jni_env->GetStaticMethodID (helperClass, "invokeStaticMethod",
+              "(Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;[Ljava/lang/Class;)Ljava/lang/Object;");
+          jstring_ref methName (jni_env, jni_env->NewStringUTF (name.c_str ()));
+          jstring_ref clsName (jni_env, jni_env->NewStringUTF (class_name.c_str ()));
+          jobject_ref resObj (jni_env, jni_env->CallStaticObjectMethod (helperClass, mID,
+              jstring (clsName), jstring (methName), jobjectArray (arg_objs), jobjectArray (arg_types)));
+          if (resObj)
+            retval = box (jni_env, resObj);
+          else
+            retval = check_exception (jni_env);
+        }
+    }
+  return retval;
+}
+
+octave_value octave_java::do_java_create (JNIEnv* jni_env, const std::string& name, const octave_value_list& args)
+{
+  octave_value retval;
+
+  if (jni_env)
+    {
+      jobjectArray_ref arg_objs (jni_env), arg_types (jni_env);
+      if (unbox (jni_env, args, arg_objs, arg_types))
+        {
+          jclass_ref helperClass (jni_env, find_octave_class (jni_env, (char*)"org/octave/ClassHelper"));
+          jmethodID mID = jni_env->GetStaticMethodID (helperClass, "invokeConstructor",
+              "(Ljava/lang/String;[Ljava/lang/Object;[Ljava/lang/Class;)Ljava/lang/Object;");
+          jstring_ref clsName (jni_env, jni_env->NewStringUTF (name.c_str ()));
+          jobject_ref resObj (jni_env, jni_env->CallStaticObjectMethod (helperClass, mID,
+              jstring (clsName), jobjectArray (arg_objs), jobjectArray (arg_types)));
+          if (resObj)
+            retval = box (jni_env, resObj);
+          else
+            check_exception (jni_env);
+        }
+    }
+  return retval;
+}
+
+octave_value octave_java::do_java_get (JNIEnv* jni_env, const std::string& name)
+{
+  octave_value retval;
+
+  if (jni_env)
+    {
+      jclass_ref helperClass (jni_env, find_octave_class (jni_env, (char*)"org/octave/ClassHelper"));
+      jmethodID mID = jni_env->GetStaticMethodID (helperClass, "getField",
+          "(Ljava/lang/Object;Ljava/lang/String;)Ljava/lang/Object;");
+      jstring_ref fName (jni_env, jni_env->NewStringUTF (name.c_str ()));
+      jobject_ref resObj (jni_env, jni_env->CallStaticObjectMethod (helperClass, mID,
+          to_java (), jstring (fName)));
+      if (resObj)
+        retval = box (jni_env, resObj);
+      else
+        retval = check_exception (jni_env);
+    }
+  return retval;
+}
+
+octave_value octave_java::do_java_get (JNIEnv* jni_env, const std::string& class_name, const std::string& name)
+{
+  octave_value retval;
+
+  if (jni_env)
+    {
+      jclass_ref helperClass (jni_env, find_octave_class (jni_env, (char*)"org/octave/ClassHelper"));
+      jmethodID mID = jni_env->GetStaticMethodID (helperClass, "getStaticField",
+          "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;");
+      jstring_ref cName (jni_env, jni_env->NewStringUTF (class_name.c_str ()));
+      jstring_ref fName (jni_env, jni_env->NewStringUTF (name.c_str ()));
+      jobject_ref resObj (jni_env, jni_env->CallStaticObjectMethod (helperClass, mID,
+          jstring (cName), jstring (fName)));
+      if (resObj)
+        retval = box (jni_env, resObj);
+      else
+        retval = check_exception (jni_env);
+    }
+  return retval;
+}
+
+octave_value octave_java::do_java_set (JNIEnv* jni_env, const std::string& name, const octave_value& val)
+{
+  octave_value retval;
+
+  if (jni_env)
+    {
+      jobject_ref jobj (jni_env);
+      jclass_ref jcls (jni_env);
+
+      if (unbox (jni_env, val, jobj, jcls))
+        {
+          jclass_ref helperClass (jni_env, find_octave_class (jni_env, (char*)"org/octave/ClassHelper"));
+          jmethodID mID = jni_env->GetStaticMethodID (helperClass, "setField",
+              "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)V");
+          jstring_ref fName (jni_env, jni_env->NewStringUTF (name.c_str ()));
+          jni_env->CallStaticObjectMethod (helperClass, mID, to_java (), jstring (fName), jobject (jobj));
+          check_exception (jni_env);
+        }
+    }
+  return retval;
+}
+
+octave_value octave_java::do_java_set (JNIEnv* jni_env, const std::string& class_name, const std::string& name, const octave_value& val)
+{
+  octave_value retval;
+
+  if (jni_env)
+    {
+      jobject_ref jobj (jni_env);
+      jclass_ref jcls (jni_env);
+
+      if (unbox (jni_env, val, jobj, jcls))
+        {
+          jclass_ref helperClass (jni_env, find_octave_class (jni_env, (char*)"org/octave/ClassHelper"));
+          jmethodID mID = jni_env->GetStaticMethodID (helperClass, "setStaticField",
+              "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Object;)V");
+          jstring_ref cName (jni_env, jni_env->NewStringUTF (class_name.c_str ()));
+          jstring_ref fName (jni_env, jni_env->NewStringUTF (name.c_str ()));
+          jni_env->CallStaticObjectMethod (helperClass, mID, jstring (cName), jstring (fName), jobject (jobj));
+          check_exception (jni_env);
+        }
+    }
+  return retval;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libinterp/dldfcn/__java__.h	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,272 @@
+/* Copyright (C) 2007 Michael Goffioul
+**
+** 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/>.
+*/
+
+#ifndef __JAVA__H__
+#define __JAVA__H__
+
+#include "oct.h"
+#include "config.h"
+#ifndef OCTAVE_EXPORT
+#include "oct-dlldefs.h"
+#endif // OCTAVE_EXPORT
+#include <jni.h>
+
+#ifdef JAVAPKG_BUILD
+# define JAVAPKG_API OCTAVE_EXPORT
+#else
+# define JAVAPKG_API OCTAVE_IMPORT
+#endif
+
+template <class T>
+class java_local_ref
+{
+public:
+  java_local_ref (JNIEnv *_env)
+    : jobj (0), detached (false), env (_env)
+    { }
+
+  java_local_ref (JNIEnv *_env, T obj)
+    : jobj (obj), detached (false), env (_env)
+    { }
+
+  ~java_local_ref (void)
+    {
+      release ();
+    }
+
+  T& operator= (T obj)
+    {
+      release ();
+      jobj = obj;
+      detached = false;
+      return jobj;
+    }
+  operator bool () const { return (jobj != 0); }
+  operator T () { return jobj; }
+
+  void detach () { detached = true; }
+
+private:
+  void release (void)
+    {
+      if (env && jobj && ! detached)
+        env->DeleteLocalRef (jobj);
+      jobj = 0;
+    }
+
+  java_local_ref (void)
+    : jobj (0), detached (false), env (0)
+    { }
+	
+
+protected:
+  T jobj;
+  bool detached;
+  JNIEnv *env;
+};
+
+typedef java_local_ref<jobject> jobject_ref;
+typedef java_local_ref<jclass> jclass_ref;
+typedef java_local_ref<jstring> jstring_ref;
+typedef java_local_ref<jobjectArray> jobjectArray_ref;
+typedef java_local_ref<jintArray> jintArray_ref;
+typedef java_local_ref<jbyteArray> jbyteArray_ref;
+typedef java_local_ref<jdoubleArray> jdoubleArray_ref;
+typedef java_local_ref<jthrowable> jthrowable_ref;
+
+extern JAVAPKG_API std::string jstring_to_string (JNIEnv* jni_env, jstring s);
+extern JAVAPKG_API std::string jstring_to_string (JNIEnv* jni_env, jobject obj);
+extern JAVAPKG_API octave_value box (JNIEnv* jni_env, jobject jobj, jclass jcls = 0);
+extern JAVAPKG_API octave_value box_more (JNIEnv* jni_env, jobject jobj, jclass jcls = 0);
+extern JAVAPKG_API int unbox (JNIEnv* jni_env, const octave_value& val, jobject_ref& jobj, jclass_ref& jcls);
+extern JAVAPKG_API int unbox (JNIEnv* jni_env, const octave_value_list& args, jobjectArray_ref& jobjs, jobjectArray_ref& jclss);
+
+extern JAVAPKG_API bool Vjava_convert_matrix;
+extern JAVAPKG_API bool Vjava_unsigned_conversion;
+extern JAVAPKG_API bool Vjava_debug;
+
+class JAVAPKG_API octave_java : public octave_base_value
+{
+public:
+  octave_java (void)
+    : java_object (0), java_class (0)
+    { }
+
+  octave_java (const octave_java& jobj)
+    : java_object (0), java_class (0)
+    {
+      init (jobj.java_object, jobj.java_class);
+    }
+
+  octave_java (jobject obj, jclass cls = 0)
+    : java_object (0)
+    {
+      init (obj, cls);
+    }
+
+  ~octave_java (void)
+    {
+      release ();
+    }
+
+  jobject to_java () const { return java_object; }
+  jclass to_class () const { return java_class; }
+  std::string java_class_name () const { return java_type; }
+	
+  octave_base_value* clone(void) const { return new octave_java(*this); }
+  octave_base_value* empty_clone(void) const { return new octave_java(); }
+
+  bool is_defined(void) const { return true; }
+
+  bool is_map (void) const { return true; }
+
+  string_vector map_keys(void) const;
+
+  dim_vector dims(void) const;
+
+  void print(std::ostream& os, bool pr_as_read_syntax = false) const
+    {
+      os << "<Java object: " << java_type << ">";
+      newline(os);
+    }
+
+  void print_raw(std::ostream& os, bool pr_as_read_syntax = false) const
+    {
+      print(os, pr_as_read_syntax);
+    }
+
+  octave_value_list subsref (const std::string& type, const std::list<octave_value_list>& idx, int nargout);
+	
+  octave_value subsref (const std::string& type,
+			const std::list<octave_value_list>& idx)
+    {
+      octave_value_list retval = subsref (type, idx, 1);
+      return (retval.length () > 0 ? retval(0) : octave_value ());
+    }
+
+  octave_value subsasgn (const std::string& type, const std::list<octave_value_list>& idx, const octave_value& rhs);
+
+  octave_value convert_to_str_internal (bool pad, bool force, char type) const;
+
+  bool is_string (void) const
+    {
+      JNIEnv *current_env = thread_jni_env ();
+
+      if (current_env && java_object)
+        {
+          jclass_ref cls (current_env, current_env->FindClass ("java/lang/String"));
+          return current_env->IsInstanceOf (java_object, cls);
+        }
+      return false;
+    }
+
+  static JNIEnv* thread_jni_env (void);
+
+  octave_value do_java_invoke (JNIEnv* jni_env, const std::string& name,
+      const octave_value_list& args);
+  
+  octave_value do_java_invoke (const std::string& name, const octave_value_list& args)
+    { return do_java_invoke(thread_jni_env (), name, args); }
+
+  static octave_value do_java_invoke (JNIEnv* jni_env, const std::string& class_name,
+    const std::string& name, const octave_value_list& args);
+  
+  static octave_value do_java_invoke (const std::string& class_name, 
+      const std::string& name, const octave_value_list& args)
+    { return do_java_invoke(thread_jni_env (), class_name, name, args); }
+
+  static octave_value do_java_create (JNIEnv* jni_env, const std::string& name,
+      const octave_value_list& args);
+  
+  static octave_value do_java_create (const std::string& name, const octave_value_list& args)
+    { return do_java_create (thread_jni_env (), name, args); }
+
+  octave_value do_java_get (JNIEnv* jni_env, const std::string& name);
+  
+  octave_value do_java_get (const std::string& name)
+    { return do_java_get (thread_jni_env (), name); }
+
+  static octave_value do_java_get (JNIEnv* jni_env, const std::string& class_name,
+      const std::string& name);
+  
+  static octave_value do_java_get (const std::string& class_name, const std::string& name)
+    { return do_java_get (thread_jni_env (), class_name, name); }
+
+  octave_value do_java_set (JNIEnv* jni_env, const std::string& name, const octave_value& val);
+  
+  octave_value do_java_set (const std::string& name, const octave_value& val)
+    { return do_java_set (thread_jni_env (), name, val); }
+
+  static octave_value do_java_set (JNIEnv* jni_env, const std::string& class_name,
+      const std::string& name, const octave_value& val);
+  
+  static octave_value do_java_set (const std::string& class_name, const std::string& name,
+      const octave_value& val)
+    { return do_java_set (thread_jni_env (), class_name, name, val); }
+
+private:
+  void init (jobject jobj, jclass jcls)
+    {
+      JNIEnv *current_env = thread_jni_env ();
+
+      if (current_env)
+        {
+          if (jobj)
+            java_object = current_env->NewGlobalRef (jobj);
+          if (jcls)
+            java_class = reinterpret_cast<jclass> (current_env->NewGlobalRef (jcls));
+          else if (java_object)
+            {
+              jclass_ref ocls (current_env, current_env->GetObjectClass (java_object));
+              java_class = reinterpret_cast<jclass> (current_env->NewGlobalRef (jclass (ocls)));
+            }
+
+          if (java_class)
+            {
+              jclass_ref clsCls (current_env, current_env->GetObjectClass (java_class));
+              jmethodID mID = current_env->GetMethodID (clsCls, "getCanonicalName", "()Ljava/lang/String;");
+              jobject_ref resObj (current_env, current_env->CallObjectMethod (java_class, mID));
+              java_type = jstring_to_string (current_env, resObj);
+            }
+        }
+    }
+
+  void release ()
+    {
+      JNIEnv *current_env = thread_jni_env ();
+
+      if (current_env)
+        {
+          if (java_object)
+            current_env->DeleteGlobalRef (java_object);
+          if (java_class)
+            current_env->DeleteGlobalRef (java_class);
+          java_object = 0;
+          java_class = 0;
+        }
+    }
+
+private:
+  DECLARE_OCTAVE_ALLOCATOR
+	
+  DECLARE_OV_TYPEID_FUNCTIONS_AND_DATA
+
+  jobject java_object;
+  jclass java_class;
+  std::string java_type;
+};
+
+#endif /* __JAVA__H__ */
--- a/libinterp/dldfcn/module-files	Fri Nov 23 11:43:49 2012 -0500
+++ b/libinterp/dldfcn/module-files	Fri Nov 23 15:29:13 2012 -0500
@@ -5,6 +5,7 @@
 __glpk__.cc|$(GLPK_CPPFLAGS)|$(GLPK_LDFLAGS)|$(GLPK_LIBS)
 __init_fltk__.cc|$(GRAPHICS_CFLAGS) $(FT2_CPPFLAGS)|$(GRAPHICS_LDFLAGS) $(FT2_LDFLAGS)|$(GRAPHICS_LIBS) $(FT2_LIBS)
 __init_gnuplot__.cc
+__java__.cc|$(JAVA_CPPFLAGS)||$(JAVA_LIBS)
 __magick_read__.cc|$(MAGICK_CPPFLAGS)|$(MAGICK_LDFLAGS)|$(MAGICK_LIBS)
 __voronoi__.cc|$(QHULL_CPPFLAGS)|$(QHULL_LDFLAGS)|$(QHULL_LIBS)
 amd.cc|$(SPARSE_XCPPFLAGS)|$(SPARSE_XLDFLAGS)|$(SPARSE_XLIBS)
--- a/libinterp/link-deps.mk	Fri Nov 23 11:43:49 2012 -0500
+++ b/libinterp/link-deps.mk	Fri Nov 23 15:29:13 2012 -0500
@@ -17,6 +17,7 @@
   $(X11_LIBS) \
   $(CARBON_LIBS) \
   $(LLVM_LIBS) \
+  $(JAVA_LIBS) \
   $(LAPACK_LIBS)
 
 LIBOCTINTERP_LINK_OPTS = \
--- a/scripts/Makefile.am	Fri Nov 23 11:43:49 2012 -0500
+++ b/scripts/Makefile.am	Fri Nov 23 15:29:13 2012 -0500
@@ -36,6 +36,8 @@
 
 IMAGES =
 
+JAR_FILES =
+
 ## Read subdirs to set all variables above
 include @ftp/module.mk
 include audio/module.mk
@@ -46,6 +48,7 @@
 include help/module.mk
 include image/module.mk
 include io/module.mk
+include java/module.mk
 include linear-algebra/module.mk
 include miscellaneous/module.mk
 include optimization/module.mk
@@ -68,16 +71,16 @@
 include testfun/module.mk
 include time/module.mk
 
-nobase_fcnfile_DATA = $(FCN_FILES) $(GEN_FCN_FILES)
+nobase_fcnfile_DATA = $(FCN_FILES) $(GEN_FCN_FILES) $(JAR_FILES)
 
 image_DATA = $(IMAGES)
 
 FCN_FILES_IN = $(GEN_FCN_FILES:.m=.in)
 
 if AMCOND_BUILD_DOCS
-all-local: $(GEN_FCN_FILES) $(PKG_ADD_FILES) .DOCSTRINGS
+all-local: $(GEN_FCN_FILES) $(PKG_ADD_FILES) $(JAR_FILES) .DOCSTRINGS
 else
-all-local: $(GEN_FCN_FILES) $(PKG_ADD_FILES)
+all-local: $(GEN_FCN_FILES) $(PKG_ADD_FILES) $(JAR_FILES)
 endif
 
 octave_dirstamp = $(am__leading_dot)dirstamp
@@ -118,6 +121,10 @@
 	$(srcdir)/mk-pkg-add $(srcdir) $(io_FCN_FILES) -- $(io_GEN_FCN_FILES) > $@-t
 	mv $@-t $@
 
+java/PKG_ADD: $(java_FCN_FILES) $(java_GEN_FCN_FILES) java/$(octave_dirstamp) mk-pkg-add
+	$(srcdir)/mk-pkg-add $(srcdir) $(java_FCN_FILES) -- $(java_GEN_FCN_FILES) > $@-t
+	mv $@-t $@
+
 linear-algebra/PKG_ADD: $(linear_algebra_FCN_FILES) $(linear_algebra_GEN_FCN_FILES) linear-algebra/$(octave_dirstamp) mk-pkg-add
 	$(srcdir)/mk-pkg-add $(srcdir) $(linear_algebra_FCN_FILES) -- $(linear_algebra_GEN_FCN_FILES) > $@-t
 	mv $@-t $@
@@ -211,6 +218,7 @@
 $(help_GEN_FCN_FILES): help/$(octave_dirstamp)
 $(image_GEN_FCN_FILES): image/$(octave_dirstamp)
 $(io_GEN_FCN_FILES): io/$(octave_dirstamp)
+$(java_GEN_FCN_FILES): java/$(octave_dirstamp)
 $(linear_algebra_GEN_FCN_FILES): linear-algebra/$(octave_dirstamp)
 $(miscellaneous_GEN_FCN_FILES): miscellaneous/$(octave_dirstamp)
 $(optimization_GEN_FCN_FILES): optimization/$(octave_dirstamp)
@@ -260,6 +268,9 @@
 io/$(octave_dirstamp):
 	$(MKDIR_P) io
 	: > io/$(octave_dirstamp)
+java/$(octave_dirstamp):
+	$(MKDIR_P) java
+	: > java/$(octave_dirstamp)
 linear-algebra/$(octave_dirstamp):
 	$(MKDIR_P) linear-algebra
 	: > linear-algebra/$(octave_dirstamp)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/dlgtest.m	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,255 @@
+%
+% Install the java package.
+% Test the dlg... functions of the java package.
+%
+% Author: Martin Hepperle
+% Version August 2010
+%
+function dlgtest ( reinstall )
+
+   % Windows example paths
+   if ispc()
+      % NOTE: do NOT use backslashes as separator, only forward slashes!
+      pkgpath = 'z:/java-1.2.8.tar.gz';
+      java_home = getenv ("JAVA_HOME");
+   elseif isunix()
+      % Linux example paths
+      pkgpath = '~/java-1.2.8.tar.gz';
+      java_home = getenv ("JAVA_HOME");
+   else
+      pkgpath = 'unknown';
+      java_home = 'unknown';   
+   end
+
+   if nargin<1
+      disp('usage: dlgtest ( reinstall )');
+      disp( 'where: reinstall = 0 : do not reinstall java package');
+      disp(['       reinstall = 1 : reinstall java package from ', pkgpath, ...
+            ', using Java JDK from ', java_home]);
+      return
+   end
+
+  if ! exist (java_home, "dir")
+    disp(['Java JDK home directory ', java_home,' does not exist.']);
+    disp('Please adapt java_home in dlgtest.m.');
+    return;
+  end
+
+  if reinstall == 1
+    if ! exist (pkgpath, "file")
+      disp(['Package file ', pkgpath, ' does not exist.']);
+      disp('Please adapt pkgpath in dlgtest.m.');
+      return;
+    end
+  end
+
+  page_screen_output(0);
+
+  if reinstall == 1
+    disp('- uninstalling package java');
+    pkg uninstall java
+
+    disp(['- installing package java from ',pkgpath]);
+    disp(['  using JDK from ',java_home]);
+    setenv('JAVA_HOME',java_home)
+    %% pkg does not understand variables as arguments?
+    eval(['pkg install ', pkgpath])
+    disp('Done.');
+  end
+
+  page_screen_output(1);
+
+  answer = 1;
+  while (answer > 0 )
+
+    disp('');
+    disp('0 ... STOP');
+    disp('1 ... listdlg tests');
+    disp('2 ... errordlg tests');
+    disp('3 ... warndlg tests');
+    disp('4 ... helpdlg tests');
+    disp('5 ... inputdlg tests');
+    disp('6 ... TeX code tests');
+    
+    answer = str2num(input ('Run which test?   [0] > ','s'));
+
+    disp('');
+    
+    switch answer
+      case 1
+        test_listdlg();
+      case 2
+        test_errordlg();
+      case 3
+        test_warndlg();
+      case 4
+        test_helpdlg();
+      case 5
+        test_inputdlg();
+      case 6
+        test_TeXCodes();
+    end
+  end
+
+   %   d = javaObject('javax.swing.JDialog');
+   %   cp = d.getContentPane;
+   %   b = javaObject('javax.swing.JButton','OK');
+   %   cp.add(b);
+   %   d.pack;
+   %   d.setVisible(true);
+
+
+   page_screen_output(1);
+
+end
+
+function test_listdlg
+
+   %-----------------------------------------------
+   disp('- test listdlg with selectionmode single. No caption, no prompt.');
+   itemlist = {'An item \\alpha', 'another', 'yet another'};
+   s = listdlg ( 'ListString',itemlist, 'SelectionMode','Single' );
+   imax = length(s);
+   for i=1:1:imax
+      disp(['Selected: ',num2str(i),': ', itemlist{s(i)}]);
+   end
+
+   %-----------------------------------------------
+   disp('- test listdlg with selectionmode and preselection. Has caption and two lines prompt.');
+   s = listdlg ( 'ListString',itemlist, ...
+                 'SelectionMode','Multiple', ...
+                 'Name','Selection Dialog', ...
+                 'InitialValue',[1,2,3,4],
+                 'PromptString',{'Select an item...', '...or multiple items'} );
+   imax = length(s);
+   for i=1:1:imax
+      disp(['Selected: ',num2str(i),': ', itemlist{s(i)}]);
+   end
+
+end
+
+function test_errordlg
+   %-----------------------------------------------
+   disp('- test errordlg with prompt only.');
+   errordlg('Oops, an expected error occured');
+   %-----------------------------------------------
+   disp('- test errordlg with prompt and caption.');
+   errordlg('Oops another error','This is a very long and informative caption');
+end
+
+function test_warndlg
+   %-----------------------------------------------
+   disp('- test warndlg with prompt only.');
+   warndlg('Oh, a warning occured');
+   %-----------------------------------------------
+   disp('- test warndlg with prompt and caption.');
+   warndlg('Oh, No...','This is the last Warning');
+end
+
+function test_helpdlg
+   %-----------------------------------------------
+   disp('- test helpdlg with a help message only.');
+   helpdlg("Below, you should see 3 lines:\nline #1\nline #2, and\nline #3.");
+   %-----------------------------------------------
+   disp('- test helpdlg with help message and caption.');
+   helpdlg('You should see a single line.','A help dialog');
+end
+
+function test_inputdlg
+   %-----------------------------------------------
+   disp('- test inputdlg with prompt and caption only.');
+   prompt = {'Width','Height','Depth'};
+   dims = inputdlg ( prompt, 'Enter Box Dimensions' );
+   if isempty(dims)
+      helpdlg('Canceled by user', 'Information');
+   else
+      volume  = str2num(dims{1}) * str2num(dims{2}) * str2num(dims{3});
+      surface = 2 * (str2num(dims{1}) * str2num(dims{2}) + ...
+                     str2num(dims{2}) * str2num(dims{3}) + ...
+                     str2num(dims{1}) * str2num(dims{3}));
+      helpdlg(sprintf('Results:\nVolume = %.3f\nSurface = %.3f', volume, surface), 'Box Dimensions');
+   end
+
+   %-----------------------------------------------
+   disp('- test inputdlg with prescribed scalar (2 lines per text field) and defaults.');
+   prompt = {'Width','Height','Depth'};
+   default = {'1.1','2.2','3.3'};
+   rc = 2;
+   dims = inputdlg ( prompt, 'Enter Box Dimensions',rc,default );
+   if isempty(dims)
+      helpdlg('Canceled by user', 'Information');
+   else
+      volume  = str2num(dims{1}) * str2num(dims{2}) * str2num(dims{3});
+      surface = 2 * (str2num(dims{1}) * str2num(dims{2}) + ...
+                     str2num(dims{2}) * str2num(dims{3}) + ...
+                     str2num(dims{1}) * str2num(dims{3}));
+      helpdlg(sprintf('Results:\nVolume = %.3f\nSurface = %.3f', volume, surface), 'Box Dimensions');
+   end
+   %-----------------------------------------------
+   disp('- test inputdlg with prescribed vector [1,2,3] for # of lines per text field and defaults.');
+   prompt = {'Width','Height','Depth'};
+   default = {'1.10', '2.10', '3.10'};
+   rc = [1,2,3];  % NOTE: must be an array
+   dims = inputdlg ( prompt, 'Enter Box Dimensions',rc,default );
+   if isempty(dims)
+      helpdlg('Canceled by user', 'Information');
+   else
+      volume  = str2num(dims{1}) * str2num(dims{2}) * str2num(dims{3});
+      surface = 2 * (str2num(dims{1}) * str2num(dims{2}) + ...
+                     str2num(dims{2}) * str2num(dims{3}) + ...
+                     str2num(dims{1}) * str2num(dims{3}));
+      helpdlg(sprintf('Results:\nVolume = %.3f\nSurface = %.3f', volume, surface), 'Box Dimensions');
+   end
+   %-----------------------------------------------
+   disp('- test inputdlg with prescribed row by column sizes and defaults.');
+   prompt = {'Width','Height','Depth'};
+   default = {'1.10', '2.20', '3.30'};
+   rc = [1,10; 2,20; 3,30];  % NOTE: must be an array
+   dims = inputdlg ( prompt, 'Enter Box Dimensions',rc,default );
+   if isempty(dims)
+      helpdlg('Canceled by user', 'Information');
+   else
+      volume  = str2num(dims{1}) * str2num(dims{2}) * str2num(dims{3});
+      surface = 2 * (str2num(dims{1}) * str2num(dims{2}) + ...
+                     str2num(dims{2}) * str2num(dims{3}) + ...
+                     str2num(dims{1}) * str2num(dims{3}));
+      helpdlg(sprintf('Results:\nVolume = %.3f\nSurface = %.3f', volume, surface), 'Box Dimensions');
+   end
+end
+
+%% show a table of TeX symbol codes and the resulting Unicode character
+function test_TeXCodes
+   %-----------------------------------------------
+   disp('- test TeX code to Unicode translation.');
+
+   msgbox ( ['\\alpha  = ''\alpha ''      \\beta  = ''\beta ''      \\gamma  = ''\gamma ''', 10, ...
+             '\\delta  = ''\delta ''      \\epsilon  = ''\epsilon ''      \\zeta  = ''\zeta ''', 10, ...
+             '\\eta  = ''\eta ''      \\theta  = ''\theta ''      \\vartheta  = ''\vartheta ''', 10, ...
+             '\\iota  = ''\iota ''      \\kappa  = ''\kappa ''      \\lambda  = ''\lambda ''', 10, ...
+             '\\mu  = ''\mu ''      \\nu  = ''\nu ''      \\xi  = ''\xi ''', 10, ...
+             '\\pi  = ''\pi ''      \\rho  = ''\rho ''      \\sigma  = ''\sigma ''', 10, ...
+             '\\varsigma  = ''\varsigma ''      \\tau  = ''\tau ''      \\phi  = ''\phi ''', 10, ...
+             '\\chi  = ''\chi ''      \\psi  = ''\psi ''      \\omega  = ''\omega ''', 10, ...
+             '\\upsilon  = ''\upsilon ''      \\Gamma  = ''\Gamma ''      \\Delta  = ''\Delta ''', 10, ...
+             '\\Theta  = ''\Theta ''      \\Lambda  = ''\Lambda ''      \\Pi  = ''\Pi ''', 10, ...
+             '\\Xi  = ''\Xi ''      \\Sigma  = ''\Sigma ''      \\Upsilon  = ''\Upsilon ''', 10, ...
+             '\\Phi  = ''\Phi ''      \\Psi  = ''\Psi ''      \\Omega  = ''\Omega ''', 10, ...
+             '\\Im  = ''\Im ''      \\Re  = ''\Re ''      \\leq  = ''\leq ''', 10, ...
+             '\\geq  = ''\geq ''      \\neq  = ''\neq ''      \\pm  = ''\pm ''', 10, ...
+             '\\infty  = ''\infty ''      \\partial  = ''\partial ''      \\approx  = ''\approx ''', 10, ...
+             '\\circ  = ''\circ ''      \\bullet  = ''\bullet ''      \\times  = ''\times ''', 10, ...
+             '\\sim  = ''\sim ''      \\nabla  = ''\nabla ''      \\ldots  = ''\ldots ''', 10, ...
+             '\\exists  = ''\exists ''      \\neg  = ''\neg ''      \\aleph  = ''\aleph ''', 10, ...
+             '\\forall  = ''\forall ''      \\cong  = ''\cong ''      \\wp  = ''\wp ''', 10, ...
+             '\\propto  = ''\propto ''      \\otimes  = ''\otimes ''      \\oplus  = ''\oplus ''', 10, ...
+             '\\oslash  = ''\oslash ''      \\cap  = ''\cap ''      \\cup  = ''\cup ''', 10, ...
+             '\\ni  = ''\ni ''      \\in  = ''\in ''      \\div  = ''\div ''', 10, ...
+             '\\equiv  = ''\equiv ''      \\int  = ''\int ''      \\perp  = ''\perp ''', 10, ...
+             '\\wedge  = ''\wedge ''      \\vee  = ''\vee ''      \\supseteq  = ''\supseteq ''', 10, ...
+             '\\supset  = ''\supset ''      \\subseteq  = ''\subseteq ''      \\subset  = ''\subset ''', 10, ...
+             '\\clubsuit  = ''\clubsuit ''      \\spadesuit  = ''\spadesuit ''      \\heartsuit  = ''\heartsuit ''', 10, ...
+             '\\diamondsuit  = ''\diamondsuit ''      \\copyright  = ''\copyright ''      \\leftarrow  = ''\leftarrow ''', 10, ...
+             '\\uparrow  = ''\uparrow ''      \\rightarrow  = ''\rightarrow ''      \\downarrow  = ''\downarrow ''', 10, ...
+             '\\leftrightarrow  = ''\leftrightarrow ''      \\updownarrow  = ''\updownarrow '''], ...
+             'TeX symbol code table Test');
+end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/errordlg.m	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,37 @@
+## Copyright (C) 2010 Martin Hepperle
+##
+## 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/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function file} {@var{P} =} errordlg (@var{MESSAGE} [,@var{TITLE}])
+##
+## Displays the @var{MESSAGE} using an error dialog box. 
+## The @var{TITLE} can be used optionally to decorate the dialog caption.
+## The return value is always 1.
+##
+## @end deftypefn
+## @seealso{helpdlg, inputdlg, listdlg, questdlg, warndlg}
+
+function ret = errordlg(message,varargin)
+  
+  switch length (varargin)
+  case 0
+     title = "Error Dialog";
+  otherwise
+     title = varargin{1};
+  endswitch
+
+  ret = java_invoke ("org.octave.JDialogBox", "errordlg", message, title);
+
+endfunction
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/helpdlg.m	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,38 @@
+## Copyright (C) 2010 Martin Hepperle
+##
+## 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/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function file} {@var{P} =} helpdlg (@var{MESSAGE} [,@var{TITLE}])
+##
+## Displays a @var{MESSAGE} in a help dialog box. 
+## The help message can have multiple lines, separated by a newline character '\n'.
+## The @var{TITLE} can be used optionally to decorate the dialog caption.
+## The return value is always 1.
+##
+## @end deftypefn
+## @seealso{errordlg, inputdlg, listdlg, questdlg, warndlg}
+
+function ret = helpdlg(message,varargin)
+  
+  switch length (varargin)
+  case 0
+     title = "Help Dialog";
+  otherwise
+     title = varargin{1};
+  endswitch
+
+  ret = java_invoke ("org.octave.JDialogBox", "helpdlg", message, title);
+
+endfunction
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/inputdlg.m	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,106 @@
+## Copyright (C) 2010 Martin Hepperle
+##
+## 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/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function file} {@var{P} =} inputdlg (@var{PROMPT} [,@var{TITLE} [,@var{ROWSCOLS}, @var{DEFAULTS}]])
+##
+## Returns the user's inputs from a multi-textfield dialog box in form of a cell array of strings.
+## If the dialog is closed by the Cancel button, an empty cell array is returned.
+##
+## @table @samp
+## @item PROMPT
+## The first argument @var{PROMPT} is mandatory.
+## It is a cell array with strings labeling each textfield. 
+## @item TITLE
+## The optional string @var{TITLE} can be used as the caption of the dialog. 
+## @item ROWSCOLS
+## The size of the text fields can be defined by the argument @var{ROWSCOLS}, 
+##  which can have three forms:
+## - a scalar value which defines the number of rows used for each text field.
+## - a vector which defines the individual number of rows used for each text field.
+## - a matrix which defines the individual number of rows and columns used for each text field.
+## @item DEFAULTS
+## It is possible to place default values into the text fields by supplying
+## the a cell array of strings or number for the argument @var{DEFAULTS}.
+## @end table
+##
+## @end deftypefn
+## @seealso{errordlg, helpdlg, listdlg, questdlg, warndlg}
+
+function varargout = inputdlg(prompt,varargin)
+  
+  switch length (varargin)
+  case 0
+     title = "Input Dialog";
+     lineNo = 1;
+     defaults = cellstr(cell(size(prompt)));
+  case 1
+     title = varargin{1};
+     lineNo = 1;
+     defaults = cellstr(cell(size(prompt)));
+  case 2
+     title = varargin{1};
+     lineNo = varargin{2};
+     defaults = cellstr(cell(size(prompt)));
+  otherwise
+     title = varargin{1};
+     lineNo = varargin{2};
+     defaults = varargin{3};
+  end
+
+
+  % specification of text field sizes as in Matlab 
+  % Matlab requires a matrix for lineNo, not a cell array...
+  % rc = [1,10; 2,20; 3,30];
+  %     c1  c2
+  % r1  1   10   first  text field is 1x10
+  % r2  2   20   second text field is 2x20
+  % r3  3   30   third  text field is 3x30
+  if isscalar(lineNo)
+    % only scalar value in lineTo, copy from lineNo and add defaults
+    rowscols = zeros(size(prompt)(2),2);
+    % cols
+    rowscols(:,2) = 25;
+    rowscols(:,1) = lineNo;
+  elseif isvector(lineNo)
+      % only one column in lineTo, copy from vector lineNo and add defaults
+      rowscols = zeros(size(prompt)(2),2);
+      % rows from colum vector lineNo, columns are set to default
+      rowscols(:,2) = 25;
+      rowscols(:,1) = lineNo(:);         
+  elseif ismatrix(lineNo)
+    if (size(lineNo)(1) == size(prompt)(2)) && (size(lineNo)(2) == 2)
+      % (rows x columns) match, copy array lineNo
+      rowscols = lineNo;
+    end
+  else
+    % dunno
+    disp('inputdlg: unknown form of lineNo argument.');
+    lineNo
+  end
+  
+  % convert numeric values in defaults cell array to strings
+  defs = cellfun(@num2str,defaults,'UniformOutput',false);
+  rc = arrayfun(@num2str,rowscols,'UniformOutput',false);
+
+  user_inputs = java_invoke ("org.octave.JDialogBox", "inputdlg", prompt, title, rc, defs);
+  
+   if isempty(user_inputs)
+      varargout{1} = {};  % empty
+   else
+      varargout{1} = cellstr (user_inputs);
+   end
+
+end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/java.m	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,19 @@
+## Copyright (C) 2010 Martin Hepperle
+##
+## 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/>.
+
+## -*- texinfo -*-
+## Please enter @code{doc java} to view the documentation for 
+## the package @code{java}.
+##
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/javaArray.m	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,48 @@
+## Copyright (C) 2007 Michael Goffioul
+##
+## 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/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function file} {@var{a} =} javaArray (@var{class},@var{[M,N,...]})
+## @deftypefnx {Function file} {@var{a} =} javaArray (@var{class},@var{M},@var{N},...)
+##
+## Creates a Java array of size [@var{M},@var{N},...] with elements of
+## class @var{class}. @var{class} can be a Java object representing a class
+## or a string containing the fully qualified class name.
+##
+## The generated array is uninitialized, all elements are set to null
+## if @var{class} is a reference type, or to a default value (usually 0)
+## if @var{class} is a primitive type.
+##
+## @example
+##   a = javaArray ("java.lang.String", 2, 2);
+##   a(1,1) = "Hello";
+## @end example
+##
+## @end deftypefn
+
+function [ ret ] = javaArray (class_name, varargin)
+
+  switch length (varargin)
+  case 0
+    error ("missing array size");
+  case 1
+    dims = varargin{1};
+  otherwise
+    dims = [varargin{:}];
+  endswitch
+
+  ret = java_invoke ("org.octave.ClassHelper", "createArray", class_name, dims);
+
+endfunction
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/javaaddpath.m	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,44 @@
+## Copyright (C) 2007 Michael Goffioul
+## Copyright (C) 2010 Martin Hepperle
+##
+## 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/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function file} {} javaaddpath (@var{path})
+##
+## Adds @var{path} to the dynamic class path of the Java virtual
+## machine. @var{path} can be either a directory where .class files
+## can be found, or a .jar file containing Java classes.
+##
+## @end deftypefn
+## @seealso{javaclasspath}
+
+function javaaddpath (class_path)
+
+  if (nargin != 1)
+    print_usage ();
+  else
+    % MH 30-08-2010: added tilde_expand to allow for specification of user's home
+    new_path = canonicalize_file_name (tilde_expand (class_path));
+    if (exist (new_path, "dir"))
+      if (! strcmp (new_path (end), filesep))
+        new_path = [new_path, filesep];
+      endif
+    elseif (! exist (new_path, "file"))
+      error ("invalid Java classpath: %s", class_path);
+    endif
+    success = java_invoke ("org.octave.ClassHelper", "addClassPath", new_path);
+  endif 
+   
+endfunction
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/javaclasspath.m	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,106 @@
+## Copyright (C) 2007 Michael Goffioul, 2010 Martin Hepperle
+##
+## 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/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function file}  {}          javaclasspath
+## @deftypefnx {Function file} {@var{STATIC} =} javaclasspath
+## @deftypefnx {Function file} {[@var{STATIC}, @var{DYNAMIC}] =} javaclasspath
+## @deftypefnx {Function file} {@var{PATH} =} javaclasspath (@var{WHAT})
+##
+## Returns the class path of the Java virtual machine in
+## the form of a cell array of strings. 
+##
+## If called without input parameter:@*
+## @itemize
+## @item If no output variable is given, the result is simply printed 
+## on the standard output.
+## @item If one output variable @var{STATIC} is given, the result is
+## the static classpath.
+## @item If two output variables @var{STATIC} and @var{DYNAMIC} are 
+## given, the first variable will contain the static classpath,
+## the second will be filled with the dynamic claspath.
+## @end itemize
+## 
+## If called with a single input parameter @var{WHAT}:@*
+## @itemize
+## @item If @var{WHAT} is '-static' the static classpath is returned.
+## @item If @var{WHAT} is '-dynamic' the dynamic  classpath is returned.
+## @item If @var{WHAT} is '-all' the static and the dynamic classpath 
+## are returned in a single cell array
+## @end itemize
+## @end deftypefn
+## @seealso{javaaddpath,javarmpath}
+
+function varargout = javaclasspath (which)
+
+  % dynamic classpath
+  dynamic_path = java_invoke ("org.octave.ClassHelper", "getClassPath");
+  dynamic_path_list = strsplit (dynamic_path, pathsep ());
+
+  % static classpath
+  static_path = java_invoke ('java.lang.System', 'getProperty', 'java.class.path');
+  static_path_list = strsplit (static_path, pathsep ());
+  if (length (static_path_list) > 1)
+    % remove first element (which is .../octave.jar)
+    static_path_list = static_path_list(2:length (static_path_list));
+  else
+    static_path_list = {};
+  end
+
+  switch nargin
+    case 0
+      switch nargout
+        case 0
+          disp_path_list ( 'STATIC', static_path_list )
+          disp('');
+          disp_path_list ( 'DYNAMIC', dynamic_path_list )
+        case 1
+          varargout{1} = cellstr (dynamic_path_list);
+        case 2
+          varargout{1} = cellstr (dynamic_path_list);
+          varargout{2} = cellstr (static_path_list);
+      endswitch
+        
+    case 1
+      switch nargout
+        case 0
+          if (strcmp (which, '-static') == 1)
+            disp_path_list ( 'STATIC', static_path_list )
+          elseif (strcmp (which, '-dynamic') == 1)
+            disp_path_list ( 'DYNAMIC', dynamic_path_list )
+          end
+        case 1
+          if (strcmp (which, '-static') == 1)
+            varargout{1} = cellstr (static_path_list);
+          elseif (strcmp (which, '-dynamic') == 1)
+            varargout{1} = cellstr (dynamic_path_list);
+          elseif (strcmp (which, '-all') == 1)
+            varargout{1} = cellstr ([static_path_list, dynamic_path_list]);
+          end
+      endswitch
+  endswitch
+  
+end
+#
+# Display cell array of paths
+#
+function disp_path_list ( which, path_list )
+  printf ('   %s JAVA PATH\n\n', which);
+  if (length (path_list) > 0)
+    printf ('      %s\n', path_list{:});
+  else
+    printf ('      - empty -\n');
+  endif
+end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/javafields.m	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,44 @@
+## Copyright (C) 2007 Michael Goffioul
+##
+## 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/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function file} {@var{P} =} javafields (@var{class})
+##
+## Returns the fields of a Java object in the form of a cell 
+## array of strings. If no output variable is
+## given, the result is simply printed on the standard output.
+##
+## @end deftypefn
+## @seealso{javamethods}
+
+function varargout = javafields(classname)
+  
+  if (nargin != 1)
+     print_usage ();
+  else
+     c_methods = java_invoke ("org.octave.ClassHelper", "getFields",classname);
+     method_list = strsplit (c_methods, ';');
+
+     switch nargout
+     case 0
+       if (! isempty (method_list))
+         disp(method_list);
+       endif
+     case 1
+       varargout{1} = cellstr (method_list);
+     endswitch
+  endif
+
+endfunction
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/javamem.m	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,84 @@
+## Copyright (C) 2010 Philip Nienhuis, <prnienhuis@users.sf.net>
+## 
+## 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 Octave; see the file COPYING.  If not, see
+## <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} javamem
+## @deftypefnx {Function File} [@var{jmem}] = javamem
+## Show current memory status of the Java virtual machine (JVM)
+## & run garbage collector.
+##
+## When no return argument is given the info is echoed to the screen.
+## Otherwise, output cell array @var{jmem} contains Maximum, Total,
+## and Free memory (in bytes).
+##
+## All Java-based routines are run in the JVM's shared memory pool,
+## a dedicated and separate part of memory claimed by the JVM from
+## your computer's total memory (which comprises physical RAM and
+## virtual memory / swap space on hard disk).
+##
+## The maximum available memory can be set using the file java.opts
+## (in the same subdirectory where javaaddpath.m lives, see 
+## "which javaaddpath". Usually that is: @*
+## [/usr]/share/octave/packages/java-<version>.
+##
+## java.opts is a plain text file, one option per line. The
+## default initial memory size and default maximum memory size (which
+## are both system dependent) can be overridden like so: @*
+## -Xms64m @*
+## -Xmx512m @*
+## (in megabytes in this example.)
+## You can adapt these values to your own requirements if your system
+## has limited available physical memory or when you get Java memory
+## errors.
+##
+## "Total memory" is what the operating system has currently assigned
+## to the JVM and depends on actual and active memory usage.
+## "Free memory" is self-explanatory. During operation of Java-based
+## octave functions the amounts of Total and Free memory will vary,
+## due to Java's own cleaning up and your operating system's memory
+## management.
+##
+## @end deftypefn
+
+## Author: Philip Nienhuis
+## Created: 2010-03-25
+## Updates: 
+## 2010-03-26 Changed name to javamem & indentation to double spaces
+## 2010-08-25 Corrected text on java memory assignments
+## 2010-09-05 Further overhauled help text
+
+function [ j_mem ] = javamem ()
+
+  rt = java_invoke ('java.lang.Runtime', 'getRuntime');
+  rt.gc;
+  jmem = cell (3, 1);
+  jmem{1} = rt.maxMemory ().doubleValue ();
+  jmem{2} = rt.totalMemory ().doubleValue ();
+  jmem{3} = rt.freeMemory ().doubleValue ();
+
+  if (nargout < 1)
+    printf ("\nJava virtual machine (JVM) memory info:\n");
+    printf ("Maximum available memory:        %5d MiB;\n", jmem{1} / 1024 / 1024);
+    printf ("   (...running garbage collector...)\n");
+    printf ("OK, current status:\n");
+    printf ("Total memory in virtual machine: %5d MiB;\n", jmem{2} / 1024 / 1024);
+    printf ("Free memory in virtual machine:  %5d MiB;\n", jmem{3} / 1024 / 1024);
+    printf ("%d CPUs available.\n", rt.availableProcessors ());
+  else
+    j_mem = jmem;
+  endif
+
+endfunction
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/javamethods.m	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,44 @@
+## Copyright (C) 2007 Michael Goffioul
+##
+## 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/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function file} {@var{P} =} javamethods (@var{class})
+##
+## Returns the methods of a Java object in the form of a cell 
+## array of strings. If no output variable is
+## given, the result is simply printed on the standard output.
+##
+## @end deftypefn
+## @seealso{methods}
+
+function varargout = javamethods (classname)
+  
+  if (nargin != 1)
+     print_usage ();
+  else
+     c_methods = java_invoke ("org.octave.ClassHelper", "getMethods", classname);
+     method_list = strsplit (c_methods, ';');
+
+     switch nargout
+     case 0
+       if (! isempty (method_list))
+         disp(method_list);
+       endif
+     case 1
+       varargout{1} = cellstr (method_list);
+     endswitch
+  endif
+
+endfunction
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/javarmpath.m	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,45 @@
+## Copyright (C) 2007 Michael Goffioul
+## Copyright (C) 2010 Martin Hepperle
+##
+## 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/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function file} {} javarmpath (@var{path})
+##
+## Removes @var{path} from the dynamic class path of the Java virtual
+## machine. @var{path} can be either a directory where .class files
+## can be found, or a .jar file containing Java classes.
+##
+## @end deftypefn
+## @seealso{javaaddpath,javaclasspath}
+
+function javarmpath (class_path)
+
+  if (nargin != 1)
+    print_usage ();
+  else
+    % MH 30-08-2010: added tilde_expand to allow for specification of user's home
+    old_path = canonicalize_file_name (tilde_expand(class_path));
+    if (exist (old_path, "dir"))
+      if (! strcmp (old_path (end), filesep))
+        old_path = [old_path, filesep];
+      end
+    end
+    success = java_invoke ('org.octave.ClassHelper', 'removeClassPath', old_path);
+    if (! success)
+      disp (['Warning: ', old_path, ' not found in Java classpath.', 10]);
+    end
+  end
+
+end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/listdlg.m	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,126 @@
+## Copyright (C) 2010 Martin Hepperle
+##
+## 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/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function file} {@var{[SEL,OK]} =} listdlg (@var{KEY} ,@var{VALUE} [, @var{KEY} ,@var{VALUE}, ...]])
+##
+## Returns the user's inputs from a list dialog box in form of a vector of 
+## selection indices SEL and a flag OK indicating how the user closed the dialog box.
+## The returned flag OK is 1 if the user closed the box with the OK button, 
+## otherwise it is 0 and SEL is empty. 
+## The indices in SEL are 1 based, i.e. the first list item carries the index 1.
+##
+## The arguments are specified in form of @var{KEY}, @var{VALUE} pairs. 
+## At least the 'ListString' argument pair must be specified.
+##
+## @var{KEY}s and @var{VALUE}s pairs can be selected from the following list:
+##
+## @table @samp
+## @item ListString
+##    a cell array of strings comprising the content of the list.
+## @item SelectionMode
+##    can be either @samp{Single} or @samp{Multiple}.
+## @item ListSize
+##    a vector with two elements [width, height] defining the size of the list field in pixels.
+## @item InitialValue
+##    a vector containing 1-based indices of preselected elements.
+## @item Name
+##    a string to be used as the dialog caption.
+## @item PromptString
+##    a cell array of strings to be displayed above the list field.
+## @item OKString
+##    a string used to label the OK button.
+## @item CancelString
+##    a string used to label the Cancel  button.
+## @end table
+##
+## Example:
+##
+## @example
+##   [sel, ok] = listdlg ( 'ListString',@{'An item', 'another', 'yet another'@}, 'SelectionMode','Multiple' );
+##   if ok == 1
+##      imax = length(sel);
+##      for i=1:1:imax
+##         disp(sel(i));
+##      end
+##   end
+## @end example
+##
+## @end deftypefn
+## @seealso{errordlg, helpdlg, inputdlg, questdlg, warndlg}
+
+function varargout = listdlg(varargin)
+
+   if nargin < 2
+     print_usage ();
+     return;
+   end
+   
+   listcell = {''};
+   selmode = 'single';
+   listsize = [300,160];   % vector!
+   initialvalue = [1];     % vector!
+   name = '';
+   prompt = {''};
+   okstring = 'OK';
+   cancelstring = 'Cancel';
+   
+   % handle key, value pairs
+   for i=1:2:nargin-1
+      if strcmp(varargin{i},'ListString')
+         listcell = varargin{i+1};
+      elseif strcmp(varargin{i},'SelectionMode')
+         selmode = varargin{i+1};
+      elseif strcmp(varargin{i},'ListSize')
+         listsize = varargin{i+1};
+      elseif strcmp(varargin{i},'InitialValue')
+         initialvalue = varargin{i+1};
+      elseif strcmp(varargin{i},'Name')
+         name = varargin{i+1};
+      elseif strcmp(varargin{i},'PromptString')
+         prompt = varargin{i+1};
+      elseif strcmp(varargin{i},'OKString')
+         okstring = varargin{i+1};
+      elseif strcmp(varargin{i},'CancelString')
+         cancelstring = varargin{i+1};
+      end      
+   end
+
+   % make sure prompt strings are a cell array
+   if ! iscell(prompt)
+      prompt = {prompt};
+   end
+
+   % make sure listcell strings are a cell array
+   if ! iscell(listcell)
+      listcell = {listcell};
+   end
+
+   
+   % transform matrices to cell arrays of strings
+   listsize = arrayfun(@num2str,listsize,'UniformOutput',false);
+   initialvalue = arrayfun(@num2str,initialvalue,'UniformOutput',false);
+   
+   ret = java_invoke ('org.octave.JDialogBox', 'listdlg', listcell, ...
+                      selmode, listsize, initialvalue, name, prompt, ...
+                      okstring, cancelstring );
+   if length(ret) > 0
+      varargout = {ret, 1};
+   else
+      varargout = {{}, 0};
+   end
+  
+
+end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/module.mk	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,78 @@
+FCN_FILE_DIRS += java
+
+EXTRA_DIST += java/octave.jar
+
+java_FCN_FILES = \
+  java/dlgtest.m \
+  java/errordlg.m \
+  java/helpdlg.m \
+  java/inputdlg.m \
+  java/java.m \
+  java/javaArray.m \
+  java/javaaddpath.m \
+  java/javaclasspath.m \
+  java/javafields.m \
+  java/javamem.m \
+  java/javamethods.m \
+  java/javarmpath.m \
+  java/listdlg.m \
+  java/msgbox.m \
+  java/questdlg.m \
+  java/warndlg.m
+
+FCN_FILES += $(java_FCN_FILES)
+
+PKG_ADD_FILES += java/PKG_ADD
+
+DIRSTAMP_FILES += java/$(octave_dirstamp)
+
+JAR_FILES += java/octave.jar
+
+org_octave_dir = org/octave
+
+JAVA_SRC = \
+  $(org_octave_dir)/ClassHelper.java \
+  $(org_octave_dir)/OctClassLoader.java \
+  $(org_octave_dir)/Octave.java \
+  $(org_octave_dir)/OctaveReference.java \
+  $(org_octave_dir)/Matrix.java \
+  $(org_octave_dir)/JDialogBox.java \
+  $(org_octave_dir)/DlgListener.java \
+  $(org_octave_dir)/TeXtranslator.java \
+  $(org_octave_dir)/TeXcode.java
+
+JAVA_CLASSES = $(JAVA_SRC:.java=.class)
+
+JAVA_IMAGES = \
+  $(org_octave_dir)/images/question.png \
+  $(org_octave_dir)/images/error.png \
+  $(org_octave_dir)/images/warning.png \
+  $(org_octave_dir)/images/information.png \
+  $(org_octave_dir)/images/octave.png
+
+java_JAVA_SRC = $(addprefix java/, $(JAVA_SRC))
+
+java_JAVA_CLASSES = $(addprefix java/, $(JAVA_CLASSES))
+
+java_JAVA_IMAGES = $(addprefix java/, $(JAVA_IMAGES))
+
+java_JAVA_IMAGES_src = $(addprefix $(srcdir)/java/, $(JAVA_IMAGES))
+
+java_JAVA_CLASSES_src = $(addprefix $(srcdir)/java/, $(java_JAVA_CLASSES))
+
+%.class : %.java
+	$(MKDIR_P) java/$(org_octave_dir)
+	( cd $(srcdir)/java; $(JAVAC) -source 1.3 -target 1.3 -d $(abs_builddir)/java $(org_octave_dir)/$(<F) )
+
+java/images.stamp: $(java_JAVA_IMAGES_src)
+	if [ "x$(srcdir)" != "x." ]; then \
+	  $(MKDIR_P) java/$(org_octave_dir)/images; \
+	  cp $(java_JAVA_IMAGES_src) java/$(org_octave_dir)/images; \
+	fi
+	touch $@
+
+java/octave.jar: java/images.stamp $(java_JAVA_CLASSES)
+	( cd java; $(JAR) cf octave.jar.t $(JAVA_CLASSES) $(JAVA_IMAGES) )
+	mv $@.t $@
+
+EXTRA_DIST += $(java_JAVA_SRC) $(java_JAVA_IMAGES)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/msgbox.m	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,54 @@
+## Copyright (C) 2010 Martin Hepperle
+##
+## 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/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function file} {@var{P} =} msgbox (@var{MESSAGE} [,@var{TITLE} [,@var{ICON}]])
+##
+## Displays the @var{MESSAGE} using a message dialog. 
+## The @var{TITLE} is an optional string, which can be used to decorate the dialog caption.
+## The @var{ICON} can be used optionally to select a dialog icon. 
+## It can be one of @code{'error'}, @code{'help'} or @code{'warn'}.
+## The return value is always 1.
+##
+## @end deftypefn
+## @seealso{helpdlg, questdlg, warndlg}
+
+function ret = msgbox(message,varargin)
+  
+  switch length (varargin)
+  case 0
+     title = "";
+     dlg = 'emptydlg';
+  case 1
+     title = varargin{1};
+     dlg = 'emptydlg';
+  otherwise
+   % two or more arguments
+    title = varargin{1};
+    icon =  varargin{2};
+    if strcmp(icon,'error') == 1
+      dlg = 'errordlg';
+    elseif strcmp(icon,'help') == 1
+      dlg = 'helpdlg';
+    elseif strcmp(icon,'warn') == 1
+      dlg = 'warndlg';
+    else
+      dlg = 'emptydlg';
+    end
+  endswitch
+
+  ret = java_invoke ('org.octave.JDialogBox', dlg, message, title );
+
+endfunction
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/org/octave/ClassHelper.java	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,955 @@
+/* Copyright (C) 2007 Michael Goffioul
+ **
+ ** 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/>.
+ */
+
+package org.octave;
+
+import java.lang.reflect.*;
+
+public class ClassHelper
+{
+   private static OctClassLoader loader;
+
+   static
+   {
+      ClassLoader l = ClassHelper.class.getClassLoader ();
+      loader = ( l instanceof OctClassLoader ? ( OctClassLoader ) l :
+                 new OctClassLoader ( l ) );
+   }
+
+
+   /**
+    * Add the given path to the classpath.
+    * @param name String - path to addd to the classpath
+    * @return boolean - true if the given path exists and was added to the classpath.
+    * @throws Exception
+    */
+   public static boolean addClassPath ( String name )
+      throws Exception
+   {
+      boolean found = false;
+      java.io.File f = new java.io.File ( name );
+      if ( f.exists () )
+      {
+         loader.addClassPath ( name );
+         found = true;
+      }
+      return ( found );
+   }
+
+
+   // new -MH-
+   /**
+    *
+    * @param name String - path to remove from classpath.
+    * @return boolean - true if the given path existed in the classpath before it was removed.
+    * @throws Exception
+    */
+   public static boolean removeClassPath ( String name )
+      throws Exception
+   {
+      boolean found = false;
+      java.io.File f = new java.io.File ( name );
+      java.net.URL urlToRemove = f.toURI ().toURL ();
+      // save urls in current class path
+      java.net.URL[] urls = loader.getURLs ();
+
+      // create a completely new class loader because java.net.URLClassLoader has no removeClassPath() method
+      ClassLoader l = ClassHelper.class.getClassLoader ();
+      loader = ( l instanceof OctClassLoader ? ( OctClassLoader ) l :
+                 new OctClassLoader ( l ) );
+
+      // add the previous urls back, except for the one
+      for ( int i = 0; i < urls.length; i++ )
+      {
+         java.net.URL url = urls[i];
+         if ( !url.equals ( urlToRemove ) )
+         {
+            loader.addURL ( url );
+         }
+         else
+         {
+            // path to remove
+            found = true;
+         }
+      }
+
+      return ( found );
+   }
+
+
+   public static String getClassPath ()
+   {
+      StringBuffer buf = new StringBuffer ();
+      String pathSep = System.getProperty ( "path.separator" );
+      java.net.URL[] urls = loader.getURLs ();
+
+      for ( int i = 0; i < urls.length; i++ )
+      {
+         try
+         {
+            java.io.File f = new java.io.File ( urls[i].toURI () );
+            if ( buf.length () > 0 )
+            {
+               buf.append ( pathSep );
+            }
+            buf.append ( f.toString () );
+         }
+         catch ( java.net.URISyntaxException ex )
+         {}
+      }
+      return buf.toString ();
+   }
+
+
+   // new -MH-
+   // return list of methods for given class name
+   public static String getMethods ( String classname )
+      throws ClassNotFoundException
+   {
+      return ( getMethods ( Class.forName ( classname ) ) );
+   }
+
+
+   // new -MH-
+   // return list of methods for given class instance
+   public static String getMethods ( Object obj )
+      throws ClassNotFoundException
+   {
+      return ( getMethods ( obj.getClass () ) );
+   }
+
+
+   // new -MH-
+   // return list of methods for given class
+   public static String getMethods ( Class klass )
+   {
+      StringBuffer sb = new StringBuffer ();
+
+      Method theMethod[] = klass.getMethods ();
+      for ( int i = 0; i < theMethod.length; i++ )
+      {
+         if ( i > 0 )
+         {
+            sb.append ( ";" );
+         }
+         sb.append ( theMethod[i].getReturnType ().getCanonicalName () );
+         sb.append ( " " );
+         sb.append ( theMethod[i].getName () );
+         sb.append ( "(" );
+
+         Class theParameter[] = theMethod[i].getParameterTypes ();
+         for ( int j = 0; j < theParameter.length; j++ )
+         {
+            if ( j > 0 )
+            {
+               sb.append ( ", " );
+            }
+            sb.append ( theParameter[j].getCanonicalName () );
+         }
+         sb.append ( ")" );
+
+         Class theExceptions[] = theMethod[i].getExceptionTypes ();
+         if ( theExceptions.length > 0 )
+         {
+            sb.append ( " throws " );
+            for ( int j = 0; j < theExceptions.length; j++ )
+            {
+               if ( j > 0 )
+               {
+                  sb.append ( ", " );
+               }
+               sb.append ( theExceptions[j].getCanonicalName () );
+            }
+         }
+      }
+
+      return ( sb.toString () );
+   }
+
+
+   // new -MH-
+   // return list of fields for given class
+   public static String getFields ( Class klass )
+   {
+      StringBuffer sb = new StringBuffer ();
+
+      Field theField[] = klass.getFields ();
+      for ( int i = 0; i < theField.length; i++ )
+      {
+         if ( i > 0 )
+         {
+            sb.append ( ";" );
+         }
+         sb.append ( theField[i].toString () );
+      }
+
+      return ( sb.toString () );
+   }
+
+
+   // new -MH-
+   // return list of fields for given class name
+   public static String getFields ( String classname )
+      throws ClassNotFoundException
+   {
+      return ( getFields ( Class.forName ( classname ) ) );
+   }
+
+
+   // new -MH-
+   // return list of fields for given class instance
+   public static String getFields ( Object obj )
+      throws ClassNotFoundException
+   {
+      return ( getFields ( obj.getClass () ) );
+   }
+
+
+   public static Method findMethod ( Class cls, String name, Class[] argTypes )
+   {
+      try
+      {
+         return cls.getMethod ( name, argTypes );
+      }
+      catch ( Exception e )
+      {
+         Method[] mList = cls.getMethods ();
+         Method m;
+         for ( int i = 0; i < mList.length; i++ )
+         {
+            m = mList[i];
+            if ( m.getName ().equals ( name ) &&
+                 m.getParameterTypes ().length == argTypes.length &&
+                 isCallableFrom ( m, argTypes ) )
+            {
+               return m;
+            }
+         }
+         return null;
+      }
+   }
+
+
+   public static Constructor findConstructor ( Class cls, Class[] argTypes )
+   {
+      try
+      {
+         return cls.getConstructor ( argTypes );
+      }
+      catch ( Exception e )
+      {
+         Constructor[] cList = cls.getConstructors ();
+         //System.out.println("# constructors: " + cList.length);
+         Constructor c;
+         for ( int i = 0; i < cList.length; i++ )
+         {
+            //System.out.println("Considering constructor: " + cList[i]);
+            c = cList[i];
+            if ( c.getParameterTypes ().length == argTypes.length &&
+                 isCallableFrom ( c, argTypes ) )
+            {
+               return c;
+            }
+         }
+         return null;
+      }
+   }
+
+
+   private static Object invokeMethod ( Method m, Object target, Object[] args )
+      throws Exception
+   {
+      try
+      {
+         return m.invoke ( target, args );
+      }
+      catch ( IllegalAccessException ex )
+      {
+         String mName = m.getName ();
+         Class[] pTypes = m.getParameterTypes ();
+         Class currClass = target.getClass ();
+
+         while ( currClass != null )
+         {
+            try
+            {
+               Method meth = currClass.getMethod ( mName, pTypes );
+               if ( !meth.equals ( m ) )
+               {
+                  return meth.invoke ( target, args );
+               }
+            }
+            catch ( NoSuchMethodException ex2 )
+            {}
+            catch ( IllegalAccessException ex2 )
+            {}
+
+            Class[] ifaceList = currClass.getInterfaces ();
+            for ( int i = 0; i < ifaceList.length; i++ )
+            {
+               try
+               {
+                  Method meth = ifaceList[i].getMethod ( mName, pTypes );
+                  return meth.invoke ( target, args );
+               }
+               catch ( NoSuchMethodException ex2 )
+               {}
+               catch ( IllegalAccessException ex2 )
+               {}
+            }
+
+            currClass = currClass.getSuperclass ();
+         }
+
+         throw ex;
+      }
+   }
+
+
+   public static Object invokeMethod ( Object target, String name,
+                                       Object[] args, Class[] argTypes )
+      throws Throwable
+   {
+      Method m = findMethod ( target.getClass (), name, argTypes );
+      if ( m != null )
+      {
+         try
+         {
+            Object result = invokeMethod ( m, target,
+                                           castArguments ( args, argTypes,
+               m.getParameterTypes () ) );
+            return result;
+         }
+         catch ( InvocationTargetException ex )
+         {
+            throw ex.getCause ();
+         }
+      }
+      else
+      {
+         throw new NoSuchMethodException ( name );
+      }
+   }
+
+
+   public static Object invokeStaticMethod ( String cls, String name,
+                                             Object[] args, Class[] argTypes )
+      throws Throwable
+   {
+      Method m = findMethod ( Class.forName ( cls, true, loader ), name,
+                              argTypes );
+      if ( m != null )
+      {
+         try
+         {
+            Object result = m.invoke ( null,
+                                       castArguments ( args, argTypes,
+               m.getParameterTypes () ) );
+            return result;
+         }
+         catch ( InvocationTargetException ex )
+         {
+            throw ex.getCause ();
+         }
+      }
+      else
+      {
+         throw new NoSuchMethodException ( name );
+      }
+   }
+
+
+   public static Object invokeConstructor ( String cls, Object[] args,
+                                            Class[] argTypes )
+      throws Throwable
+   {
+      Constructor c = findConstructor ( Class.forName ( cls, true, loader ),
+                                        argTypes );
+      if ( c != null )
+      {
+         try
+         {
+            Object result = c.newInstance ( castArguments ( args, argTypes,
+               c.getParameterTypes () ) );
+            return result;
+         }
+         catch ( InvocationTargetException ex )
+         {
+            throw ex.getCause ();
+         }
+      }
+      else
+      {
+         throw new NoSuchMethodException ( cls );
+      }
+   }
+
+
+   public static Object getField ( Object target, String name )
+      throws Throwable
+   {
+      try
+      {
+         Field f = target.getClass ().getField ( name );
+         return f.get ( target );
+      }
+      catch ( NoSuchFieldException ex )
+      {
+         try
+         {
+            return invokeMethod ( target, name, new Object[0], new Class[0] );
+         }
+         catch ( NoSuchMethodException ex2 )
+         {
+            throw ex;
+         }
+      }
+   }
+
+
+   public static Object getStaticField ( String cls, String name )
+      throws Throwable
+   {
+      try
+      {
+         Field f = Class.forName ( cls, true, loader ).getField ( name );
+         return f.get ( null );
+      }
+      catch ( NoSuchFieldException ex )
+      {
+         try
+         {
+            return invokeStaticMethod ( cls, name, new Object[0], new Class[0] );
+         }
+         catch ( NoSuchMethodException ex2 )
+         {
+            throw ex;
+         }
+      }
+   }
+
+
+   public static void setField ( Object target, String name, Object value )
+      throws Exception
+   {
+      Field f = target.getClass ().getField ( name );
+      f.set ( target, castArgument ( value, value.getClass (), f.getType () ) );
+   }
+
+
+   public static void setStaticField ( String cls, String name, Object value )
+      throws Exception
+   {
+      Field f = Class.forName ( cls, true, loader ).getField ( name );
+      f.set ( null, castArgument ( value, value.getClass (), f.getType () ) );
+   }
+
+
+   private static boolean isCallableFrom ( Method m, Class[] argTypes )
+   {
+      Class[] expTypes = m.getParameterTypes ();
+      for ( int i = 0; i < argTypes.length; i++ )
+      {
+         if ( !isCallableFrom ( expTypes[i], argTypes[i] ) )
+         {
+            return false;
+         }
+      }
+      return true;
+   }
+
+
+   private static boolean isCallableFrom ( Constructor c, Class[] argTypes )
+   {
+      Class[] expTypes = c.getParameterTypes ();
+      for ( int i = 0; i < argTypes.length; i++ )
+      {
+         if ( !isCallableFrom ( expTypes[i], argTypes[i] ) )
+         {
+            return false;
+         }
+      }
+      return true;
+   }
+
+
+   private static boolean isCallableFrom ( Class expCls, Class argCls )
+   {
+      //System.out.println("isCallableFrom: "+expCls.getCanonicalName() + " <=? " + argCls.getCanonicalName());
+      if ( argCls == null )
+      {
+         return!expCls.isPrimitive ();
+      }
+      else if ( expCls.isAssignableFrom ( argCls ) )
+      {
+         return true;
+      }
+      else if ( ( isNumberClass ( expCls ) || isBooleanClass ( expCls ) ) &&
+                isNumberClass ( argCls ) )
+      {
+         return true;
+      }
+      else if ( isCharClass ( expCls ) && argCls.equals ( Character.class ) )
+      {
+         /*
+          modified into a more strict check to avoid char to string matching
+          to avoid matching method signatureslike
+          java_method(char) with octave_call('a String')
+          Date: 28-08-2010
+          Author: Martin Hepperle
+          */
+         return true;
+      }
+      else if ( isStringClass ( expCls ) && argCls.equals ( String.class ) )
+      {
+         /*
+          added for strict String to String matching
+          java_method(String) with octave_call('a String')
+          but not
+          java_method(char) with octave_call('a String')
+          Date: 28-08-2010
+          Author: Martin Hepperle
+          */
+         return true;
+      }
+      else if ( expCls.isArray () && argCls.isArray () &&
+                isCallableFrom ( expCls.getComponentType (),
+                                 argCls.getComponentType () ) )
+      {
+         return true;
+      }
+      else if ( expCls.equals ( Object.class ) && argCls.isPrimitive () )
+      {
+         return true;
+      }
+      else
+      {
+         return false;
+      }
+   }
+
+
+   private static boolean isNumberClass ( Class cls )
+   {
+      return (
+         cls.equals ( Integer.TYPE ) ||
+         cls.equals ( Integer.class ) ||
+         cls.equals ( Short.TYPE ) ||
+         cls.equals ( Short.class ) ||
+         cls.equals ( Long.TYPE ) ||
+         cls.equals ( Long.class ) ||
+         cls.equals ( Float.TYPE ) ||
+         cls.equals ( Float.class ) ||
+         cls.equals ( Double.TYPE ) ||
+         cls.equals ( Double.class )
+         );
+   }
+
+
+   private static boolean isBooleanClass ( Class cls )
+   {
+      return (
+         cls.equals ( Boolean.class ) ||
+         cls.equals ( Boolean.TYPE )
+         );
+   }
+
+
+   private static boolean isCharClass ( Class cls )
+   {
+      return (
+         cls.equals ( Character.class ) ||
+         cls.equals ( Character.TYPE )
+         );
+   }
+
+
+   /**
+    * Check whether the supplied class is a String class.
+    *
+    * Added for more strict char/string mathicng of method signatures
+    * Date: 28-08-2010
+    * Author: Martin Hepperle
+    * @param cls Class - the class to check
+    * @return boolean - true if clas is of class java.lang.String
+    */
+   private static boolean isStringClass ( Class cls )
+   {
+      return (
+         cls.equals ( String.class )
+         );
+   }
+
+
+   private static Object[] castArguments ( Object[] args, Class[] argTypes,
+                                           Class[] expTypes )
+   {
+      for ( int i = 0; i < args.length; i++ )
+      {
+         args[i] = castArgument ( args[i], argTypes[i], expTypes[i] );
+      }
+      return args;
+   }
+
+
+   private static Object castArgument ( Object obj, Class type, Class expType )
+   {
+      // System.out.println("expType:"+expType.getCanonicalName() + " <= type:" + type.getCanonicalName());
+      if ( type == null || expType.isAssignableFrom ( type ) )
+      {
+         return obj;
+      }
+      else if ( isNumberClass ( expType ) )
+      {
+         if ( expType.equals ( Integer.TYPE ) || expType.equals ( Integer.class ) )
+         {
+            return new Integer ( ( ( Number ) obj ).intValue () );
+         }
+         else if ( expType.equals ( Double.TYPE ) || expType.equals ( Double.class ) )
+         {
+            return new Double ( ( ( Number ) obj ).doubleValue () );
+         }
+         else if ( expType.equals ( Short.TYPE ) || expType.equals ( Short.class ) )
+         {
+            return new Short ( ( ( Number ) obj ).shortValue () );
+         }
+         else if ( expType.equals ( Long.TYPE ) || expType.equals ( Long.class ) )
+         {
+            return new Long ( ( ( Number ) obj ).longValue () );
+         }
+      }
+      else if ( isBooleanClass ( expType ) )
+      {
+         return new Boolean ( ( ( Number ) obj ).intValue () != 0 );
+      }
+      else if ( isCharClass ( expType ) )
+      {
+         String s = obj.toString ();
+         if ( s.length () != 1 )
+         {
+            throw new ClassCastException ( "cannot cast " + s + " to character" );
+         }
+         return new Character ( s.charAt ( 0 ) );
+      }
+      else if ( expType.isArray () && type.isArray () )
+      {
+         return castArray ( obj, type.getComponentType (),
+                            expType.getComponentType () );
+      }
+      else if ( type.isPrimitive () )
+      {
+         return obj;
+      }
+      return null;
+   }
+
+
+   private static Object castArray ( Object obj, Class elemType,
+                                     Class elemExpType )
+   {
+      int len = Array.getLength ( obj );
+      Object result = Array.newInstance ( elemExpType, len );
+      for ( int i = 0; i < len; i++ )
+      {
+         Array.set ( result, i,
+                     castArgument ( Array.get ( obj, i ), elemType, elemExpType ) );
+      }
+      return result;
+   }
+
+
+   private static int getArrayClassNDims ( Class cls )
+   {
+      if ( cls != null && cls.isArray () )
+      {
+         return ( 1 + getArrayClassNDims ( cls.getComponentType () ) );
+      }
+      else
+      {
+         return 0;
+      }
+   }
+
+
+   private static Class getArrayElemClass ( Class cls )
+   {
+      if ( cls.isArray () )
+      {
+         return getArrayElemClass ( cls.getComponentType () );
+      }
+      else
+      {
+         return cls;
+      }
+   }
+
+
+   private static Object getArrayElements ( Object array, int[][] idx,
+                                            int offset,
+                                            int ndims, Class elemType )
+   {
+      if ( offset >= ndims )
+      {
+         Object elem = Array.get ( array, idx[offset][0] );
+         if ( offset < idx.length - 1 )
+         {
+            return getArrayElements ( elem, idx, offset + 1, ndims, elemType );
+         }
+         else
+         {
+            return elem;
+         }
+      }
+      else
+      {
+         Class compType = elemType.getComponentType ();
+         Object retval = Array.newInstance ( compType, idx[offset].length );
+         for ( int i = 0; i < idx[offset].length; i++ )
+         {
+            Object elem = Array.get ( array, idx[offset][i] );
+            if ( offset < idx.length - 1 )
+            {
+               elem = getArrayElements ( elem, idx, offset + 1, ndims, compType );
+            }
+            Array.set ( retval, i, elem );
+         }
+         return retval;
+      }
+   }
+
+
+   public static Object arraySubsref ( Object obj, int[][] idx )
+      throws Exception
+   {
+      if ( !obj.getClass ().isArray () )
+      {
+         throw new IllegalArgumentException ( "not a Java array" );
+      }
+
+      if ( idx.length == 1 )
+      {
+         if ( idx[0].length == 1 )
+         {
+            return Array.get ( obj, idx[0][0] );
+         }
+         else
+         {
+            Object retval = Array.newInstance ( obj.getClass ().
+                                                getComponentType (),
+                                                idx[0].length );
+            for ( int i = 0; i < idx[0].length; i++ )
+            {
+               Array.set ( retval, i, Array.get ( obj, idx[0][i] ) );
+            }
+            return retval;
+         }
+      }
+      else
+      {
+         int[] dims = new int[idx.length];
+         for ( int i = 0; i < idx.length; i++ )
+         {
+            dims[i] = idx[i].length;
+         }
+
+         if ( dims.length != getArrayClassNDims ( obj.getClass () ) )
+         {
+            throw new IllegalArgumentException ( "index size mismatch" );
+         }
+
+         /* resolve leading singletons */
+         Object theObj = obj;
+         int offset = 0;
+         while ( dims[offset] == 1 )
+         {
+            theObj = Array.get ( theObj, idx[offset][0] );
+            offset = offset + 1;
+            if ( offset >= dims.length )
+            {
+               return theObj;
+            }
+         }
+         if ( offset > 0 )
+         {
+            int[][] new_idx = new int[idx.length - offset][];
+            System.arraycopy ( idx, offset, new_idx, 0, idx.length - offset );
+            return arraySubsref ( theObj, new_idx );
+         }
+
+         /* chop trailing singletons */
+         int ndims = dims.length;
+         while ( ndims > 1 && dims[ndims - 1] == 1 )
+         {
+            ndims--;
+         }
+
+         /* create result array */
+         Class elemClass = theObj.getClass ();
+         for ( int i = 0; i <= ( dims.length - ndims ); i++ )
+         {
+            elemClass = elemClass.getComponentType ();
+         }
+         Object retval = Array.newInstance ( elemClass, dims[0] );
+
+         /* fill-in array */
+         for ( int i = 0; i < idx[0].length; i++ )
+         {
+            Object elem = getArrayElements ( Array.get ( theObj, idx[0][i] ),
+                                             idx, 1, ndims, elemClass );
+            Array.set ( retval, i, elem );
+         }
+
+         return retval;
+      }
+   }
+
+
+   private static Object setArrayElements ( Object array, int[][] idx,
+                                            int offset, int ndims, Object rhs )
+      throws Exception
+   {
+      if ( offset >= ndims )
+      {
+         if ( offset < idx.length - 1 )
+         {
+            setArrayElements ( Array.get ( array, idx[offset][0] ), idx,
+                               offset + 1, ndims, rhs );
+         }
+         else
+         {
+            Array.set ( array, idx[offset][0], rhs );
+         }
+         return array;
+      }
+      else
+      {
+         for ( int i = 0; i < idx[offset].length; i++ )
+         {
+            if ( offset < idx.length - 1 )
+            {
+               setArrayElements ( Array.get ( array, idx[offset][i] ), idx,
+                                  offset + 1, ndims, Array.get ( rhs, i ) );
+            }
+            else
+            {
+               Array.set ( array, idx[offset][i], Array.get ( rhs, i ) );
+            }
+         }
+         return array;
+      }
+   }
+
+
+   public static Object arraySubsasgn ( Object obj, int[][] idx, Object rhs )
+      throws Exception
+   {
+      if ( !obj.getClass ().isArray () )
+      {
+         throw new IllegalArgumentException ( "not a Java array" );
+      }
+
+      if ( idx.length == 1 )
+      {
+         if ( idx[0].length == 1 )
+         {
+            Array.set ( obj, idx[0][0], rhs );
+         }
+         else
+         {
+            for ( int i = 0; i < idx[0].length; i++ )
+            {
+               Array.set ( obj, idx[0][i], Array.get ( rhs, i ) );
+            }
+         }
+         return obj;
+      }
+      else
+      {
+         int[] dims = new int[idx.length];
+         for ( int i = 0; i < idx.length; i++ )
+         {
+            dims[i] = idx[i].length;
+         }
+
+         if ( dims.length != getArrayClassNDims ( obj.getClass () ) )
+         {
+            throw new IllegalArgumentException ( "index size mismatch" );
+         }
+
+         /* resolve leading singletons */
+         Object theObj = obj;
+         int offset = 0;
+         while ( dims[offset] == 1 && offset < ( dims.length - 1 ) )
+         {
+            theObj = Array.get ( theObj, idx[offset][0] );
+            offset = offset + 1;
+         }
+         if ( offset > 0 )
+         {
+            int[][] new_idx = new int[idx.length - offset][];
+            System.arraycopy ( idx, offset, new_idx, 0, idx.length - offset );
+            arraySubsasgn ( theObj, new_idx, rhs );
+            return obj;
+         }
+
+         /* chop trailing singletons */
+         int ndims = dims.length;
+         while ( ndims > 1 && dims[ndims - 1] == 1 )
+         {
+            ndims--;
+         }
+
+         for ( int i = 0; i < idx[0].length; i++ )
+         {
+            setArrayElements ( Array.get ( theObj, idx[0][i] ), idx, 1, ndims,
+                               Array.get ( rhs, i ) );
+         }
+
+         return obj;
+      }
+   }
+
+
+   public static Object createArray ( Object cls, int[] dims )
+      throws Exception
+   {
+      Class theClass;
+      if ( cls instanceof Class )
+      {
+         theClass = ( Class ) cls;
+      }
+      else if ( cls instanceof String )
+      {
+         theClass = Class.forName ( ( String ) cls, true, loader );
+      }
+      else
+      {
+         throw new IllegalArgumentException ( "invalid class specification " +
+                                              cls );
+      }
+
+      return Array.newInstance ( theClass, dims );
+   }
+
+
+   public static Object createArray ( Object cls, int length )
+      throws Exception
+   {
+      return createArray ( cls, new int[]
+                           {length} );
+   }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/org/octave/DlgListener.java	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,159 @@
+/*
+ ** Copyright (C) 2010 Martin Hepperle
+ **
+ ** 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/>.
+ */
+
+package org.octave;
+
+import java.awt.event.*;
+import javax.swing.*;
+
+/**
+ * <p>Implements button click actions for dialog box functions</p>
+ *
+ * <p>Copyright (c) 2010 Martin Hepperle</p>
+ *
+ * @author Martin Hepperle
+ * @version 1.0
+ */
+public class DlgListener
+   extends WindowAdapter implements ActionListener, KeyListener
+{
+   // the parent frame of the dialog
+   JDialogBox m_Parent;
+
+   public DlgListener ( JDialogBox d )
+   {
+      m_Parent = d;
+   }
+
+
+   //
+   // --- extension of the WindowAdapter class ---
+   //
+   /**
+    * Called when the user clicks the close button on the window frame.
+    *
+    * @param e WindowEvent
+    */
+   public void windowClosing ( WindowEvent e )
+   {
+      m_Parent.closeDialog ( JDialogBox.CLOSE_CANCEL );
+   }
+
+   public void windowOpened( WindowEvent e )
+   {
+      m_Parent.setFocus();
+   }
+
+
+   //
+   // --- implementation of the ActionListener interface ---
+   //
+   /**
+    * Called when the user clicks a button in the dialog.
+    * Closes the dialog when either a button with an
+    * action command OK, CANCEL or NO is pressed.
+    *
+    * @param e ActionEvent
+    */
+   public void actionPerformed ( ActionEvent e )
+   {
+      if ( e.getActionCommand ().equals ( "OK" ) )
+      {
+         m_Parent.closeDialog ( JDialogBox.CLOSE_OK );
+      }
+      else if ( e.getActionCommand ().equals ( "CANCEL" ) )
+      {
+         m_Parent.closeDialog ( JDialogBox.CLOSE_CANCEL );
+      }
+      else if ( e.getActionCommand ().equals ( "NO" ) )
+      {
+         m_Parent.closeDialog ( JDialogBox.CLOSE_NO );
+      }
+      else if ( e.getActionCommand ().equals ( "SELALL" ) )
+      {
+         m_Parent.SelectAll ();
+      }
+   }
+
+
+   //
+   // --- implementation of the KeyListener interface ---
+   //
+   /**
+    * Closes the dialog when the ENTER or ESCAPE keys are released.
+    *
+    * @param e KeyEvent
+    */
+   public void keyTyped ( KeyEvent e )
+   {
+      if ( e.getKeyCode () == KeyEvent.VK_ESCAPE )
+      {
+         m_Parent.closeDialog ( JDialogBox.CLOSE_CANCEL );
+      }
+   }
+
+
+   /**
+    * @param e KeyEvent
+    */
+   public void keyPressed ( KeyEvent e )
+   {
+      if ( e.getSource ().getClass ().equals ( JTextArea.class ) )
+      {
+         JTextArea ta = ( JTextArea ) e.getSource ();
+         if ( e.getKeyCode () == KeyEvent.VK_ENTER )
+         {
+            char c[] = ta.getText ().toCharArray ();
+            int nLines = 1;
+            for ( int i = 0; i < c.length; i++ )
+            {
+               if ( c[i] == '\n' )
+               {
+                  nLines++;
+               }
+            }
+
+            if ( nLines >= ta.getRows () )
+            {
+               e.consume ();
+            }
+         }
+         else if ( e.getKeyCode () == KeyEvent.VK_TAB )
+         {
+            e.consume ();
+
+            if ( ( e.getModifiersEx () & KeyEvent.SHIFT_DOWN_MASK ) ==
+                 KeyEvent.SHIFT_DOWN_MASK )
+            {
+               ta.transferFocusBackward();
+            }
+            else
+            {
+               ta.transferFocus ();
+            }
+         }
+      }
+   }
+
+
+   /**
+    * @param e KeyEvent
+    */
+   public void keyReleased ( KeyEvent e )
+   {
+   }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/org/octave/JDialogBox.java	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,986 @@
+ /*
+  ** Copyright (C) 2010 Martin Hepperle
+  **
+  ** 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/>.
+  */
+
+package org.octave;
+
+import java.net.*;
+import java.util.*;
+
+import java.awt.*;
+import javax.swing.*;
+
+/**
+ * <p>Implementation of various dialog box functions</p>
+ *
+ * <p>The following functions are provided for being called via
+ * Octave script files:</p>
+ * <ul>
+ * <li>errordlg</li>
+ * <li>helpdlg</li>
+ * <li>inputdlg</li>
+ * </ul>
+ *
+ * <p>Copyright (c) 2010 Martin Hepperle</p>
+ *
+ * @author Martin Hepperle
+ * @version 1.0
+ */
+public class JDialogBox
+{
+   public static final int CLOSE_OK = 1;
+   public static final int CLOSE_NO = 2;
+   public static final int CLOSE_CANCEL = 3;
+
+   // dialog type
+   public static int FLAG_LABEL = 1;
+   public static int FLAG_TEXT = 2;
+   public static int FLAG_INPUT = 4;
+   public static int FLAG_LIST = 8;
+   // icon selection
+   public static int FLAG_QUESTION = 32;
+   public static int FLAG_ERROR = 64;
+   public static int FLAG_WARNING = 128;
+   public static int FLAG_INFORMATION = 256;
+
+   public static int DLG_QUEST = FLAG_QUESTION | FLAG_TEXT;
+   public static int DLG_INPUT = FLAG_QUESTION | FLAG_INPUT;
+   public static int DLG_LIST = FLAG_QUESTION | FLAG_LIST;
+
+   private final static String m_OK = "OK";
+   private final static String m_Yes = "Yes";
+   private final static String m_No = "No";
+   private final static String m_Cancel = "Cancel";
+
+   private JButton m_ButtonNO;
+   private JButton m_ButtonOK;
+   private JButton m_ButtonCANCEL;
+   private JButton m_Focus;
+   private JTextArea m_TextField[];
+   private JList m_List;
+   private JFrame m_ParentFrame;
+   private int m_CloseMethod;
+
+   // ------------------------------------
+   // implementation of listdlg function
+   // ------------------------------------
+
+   /**
+    *
+    * @param listcell String[] - a array of strings, one for each list entry
+    * @param selmode String
+    * @param sizecell Object[]
+    * @param initialcell Object[]
+    * @param name String
+    * @param promptcell String[]
+    * @param okstring String
+    * @param cancelstring String
+    * @return String[]
+    */
+   public static int[] listdlg ( String[] listcell,
+                                 String selmode,
+                                 Object[] sizecell,
+                                 Object[] initialcell,
+                                 String name,
+                                 String[] promptcell,
+                                 String okstring,
+                                 String cancelstring )
+   {
+      JDialogBox d = new JDialogBox ();
+      d.genericdlg ( promptcell, listcell, name, selmode,
+                     DLG_LIST,
+                     sizecell, initialcell, okstring, null, cancelstring );
+      return ( d.getSelectedIndices () );
+   }
+
+
+   // ------------------------------------
+   // implementation of inputdlg function
+   // -------------------------------------
+
+   /**
+    * Implements a variation of the inputdlg function.
+    *
+    * @param prompt String[] - an array of text strings to be used as labels.
+    * @param title String - a text string to be used to label the dialog caption.
+    * @param RowsCols int - defines the width of the text fields in columns.
+    * @param defaults Object[] - an array of text strings or numbers to be
+    * placed into the text fields as default values.
+    * @return String[] - an array of text strings containing the content of the
+    * text fields.
+    */
+   public static String[] inputdlg ( String[] prompt,
+                                     String title,
+                                     Object[] RowsCols,
+                                     Object[] defaults )
+   {
+      JDialogBox d = new JDialogBox ();
+      d.genericdlg ( prompt, null, title, "on",
+                     FLAG_INPUT | FLAG_QUESTION,
+                     RowsCols, defaults, m_OK, null, m_Cancel );
+      return ( d.getInput () );
+   }
+
+
+   /**
+    * Extract the current content from the text fields of an inputdlg.
+    *
+    * @return String[] - the text contained in the fields of an inputdlg.
+    * null if the dialog was cancelled.
+    */
+   private String[] getInput ()
+   {
+      String s[] = null;
+
+      if ( m_CloseMethod == CLOSE_OK )
+      {
+         s = new String[m_TextField.length];
+
+         for ( int i = 0; i < s.length; i++ )
+         {
+            s[i] = new String ( m_TextField[i].getText () );
+         }
+      }
+
+      return ( s );
+   }
+
+
+   private String getResult ()
+   {
+      String s = null;
+
+      if ( m_CloseMethod == CLOSE_OK )
+      {
+         s = m_ButtonOK.getText ();
+      }
+      else if ( m_CloseMethod == CLOSE_CANCEL )
+      {
+         s = m_ButtonCANCEL.getText ();
+      }
+      else
+      {
+         s = m_ButtonNO.getText ();
+      }
+
+      return ( s );
+   }
+
+
+   /**
+    * Extract the current content from the text fields of an inputdlg.
+    *
+    * @return String[] - the text contained in the fields of an inputdlg.
+    * null if the dialog was cancelled.
+    */
+   private String[] getSelection ()
+   {
+      String s[] = null;
+
+      if ( m_CloseMethod == CLOSE_OK )
+      {
+         int selection[] = m_List.getSelectedIndices ();
+
+         s = new String[selection.length];
+
+         for ( int i = 0; i < s.length; i++ )
+         {
+
+            // s[i] = new String ( Integer.toString(selection[i]) );
+            s[i] = ( m_List.getSelectedValues ()[i] ).toString ();
+         }
+      }
+
+      return ( s );
+   }
+
+
+   private int[] getSelectedIndices ()
+   {
+      int s[] = null;
+
+      if ( m_CloseMethod == CLOSE_OK )
+      {
+         s = m_List.getSelectedIndices ();
+         for ( int i = 0; i < s.length; i++ )
+         {
+
+            // translate to 1 based indices
+            s[i] = s[i] + 1;
+         }
+      }
+
+      return ( s );
+   }
+
+
+   public void SelectAll ()
+   {
+      if ( null != m_List )
+      {
+         m_List.setSelectionInterval ( 0, m_List.getModel ().getSize () - 1 );
+      }
+   }
+
+
+   // -------------------------------------
+   // implementation of helpdlg function
+   // -------------------------------------
+
+   /**
+    * Implements a simple helpdlg with default text and caption. Not very useful.
+    *
+    * Octave > helpdlg('helpstring','title')
+    *
+    * Called via helpdlg.m.
+    *
+    * @param helpstring String - a message string to be presented to the user.
+    * The string can have embedded newline (\n) characters to break the message
+    * into multiple lines.
+    * @param title String - a text string to be used to label the dialog caption.
+    * @return int - always 1
+    */
+   public static int helpdlg ( String helpstring, String title )
+   {
+      JDialogBox d = new JDialogBox ();
+      String s[] = new String[1];
+      s[0] = helpstring;
+      return ( d.genericdlg ( s, null, title, "on",
+                              FLAG_TEXT | FLAG_INFORMATION, null, null,
+                              m_OK, null, m_Cancel ) );
+   }
+
+
+   // -------------------------------------
+   // implementation of emptydlg function
+   // -------------------------------------
+
+   /**
+    * Implements a simple helpdlg with default text and caption. Not very useful.
+    *
+    * Octave > emptydlg('messagestring','title')
+    *
+    * Called via dlgbox.m.
+    *
+    * @param messagestring String - a message string to be presented to the user.
+    * The string can have embedded newline (\n) characters to break the message
+    * into multiple lines.
+    * @param title String - a text string to be used to label the dialog caption.
+    * @return int - always 1
+    */
+   public static int emptydlg ( String helpstring, String title )
+   {
+      JDialogBox d = new JDialogBox ();
+      String s[] = new String[1];
+      s[0] = helpstring;
+      return ( d.genericdlg ( s, null, title, "on",
+                              FLAG_TEXT, null, null,
+                              m_OK, null, m_Cancel ) );
+   }
+
+
+   // -------------------------------------------
+   // implementation of questdlg related functions
+   // -------------------------------------------
+
+   /**
+    * Implements a simple questdlg with default text and caption. Not very useful.
+    *
+    * @param question String - the question to be presented
+    * @param title String - the caption
+    * @param options String[] - 'str1', 'str2', 'str3', 'default'
+    * @return String - the caption of the button pressed by the user
+    */
+   public static String questdlg ( String question,
+                                   String title,
+                                   String[] options )
+   {
+      JDialogBox d = new JDialogBox ();
+      String s[] = new String[1];
+      s[0] = question;
+      d.genericdlg ( s, options, title, "on",
+                     DLG_QUEST, null, null,
+                     options[0], options[1], options[2] );
+      return ( d.getResult () );
+   }
+
+
+   // -------------------------------------
+   // implementation of errordlg function
+   // -------------------------------------
+
+   /**
+    * Implements a simple errordlg with default text and caption. Not very useful.
+    *
+    * @param errorstring String - the error message to display.
+    * @param dlgname String - the caption of the dialog box.
+    * @return int - always 1
+    */
+   public static int errordlg ( String errorstring, String dlgname )
+   {
+      JDialogBox d = new JDialogBox ();
+      String s[] = new String[1];
+      s[0] = errorstring;
+      return ( d.genericdlg ( s, null, dlgname, "on", FLAG_TEXT | FLAG_ERROR,
+                              null, null,
+                              m_OK, null, m_Cancel ) );
+   }
+
+
+   // -------------------------------------------
+   // implementation of warndlg related functions
+   // -------------------------------------------
+
+   /**
+    * Implements a simple warndlg with default text and caption. Not very useful.
+    *
+    * Called via warndlg.m.
+    *
+    * @param errorstring String - the message to be presented to the user.
+    * @param dlgname String - the caption of the dialog box.
+    * @return int - always 1
+    */
+   public static int warndlg ( String errorstring, String dlgname )
+   {
+      JDialogBox d = new JDialogBox ();
+      String s[] = new String[1];
+      s[0] = errorstring;
+      return ( d.genericdlg ( s, null, dlgname, "on", FLAG_TEXT | FLAG_WARNING,
+                              null, null,
+                              m_OK, null, m_Cancel ) );
+   }
+
+
+   // -------------------------------------
+   // generic dlg function
+   // -------------------------------------
+   /**
+    * A generic dialog creation and display function.
+    *
+    * @param message String[]
+    * @param list String[]
+    * @param caption String
+    * @param on String
+    * @param flag int
+    * @param RowsCols Object[]
+    * @param defaults Object[]
+    * @param okstring String
+    * @param nostring String
+    * @param cancelstring String
+    * @return int
+    */
+   public int genericdlg ( String message[],
+                           String list[],
+                           String caption,
+                           String on,
+                           int flag,
+                           Object[] RowsCols,
+                           Object[] defaults,
+                           String okstring,
+                           String nostring,
+                           String cancelstring )
+   {
+      TeXtranslator theTranslator = new TeXtranslator ();
+      setSystemLnF ( true );
+
+      caption = theTranslator.replace ( caption );
+
+      m_ButtonNO = null;
+      m_ButtonOK = null;
+      m_ButtonCANCEL = null;
+
+      // create a modal dialog with an empty frame as its parent
+      m_ParentFrame = new JFrame ();
+
+      // --- trick to bring dialog to the front
+      // In Windows, the dialog is not brought to the foreground, but hidden
+      // behind the Octave window as long as the parent frame is not visible.
+      // To avoid that the frame is visible, we move it outside of the screen.
+      m_ParentFrame.setBounds ( Toolkit.getDefaultToolkit ().getScreenSize ().
+                                width + 100,
+                                Toolkit.getDefaultToolkit ().getScreenSize ().
+                                height + 100, 1, 1 );
+      m_ParentFrame.setVisible ( true );
+      //-- end of trick
+
+      JDialog dlg;
+      dlg = new JDialog ( m_ParentFrame );
+      dlg.setTitle ( caption );
+
+      dlg.setModal ( true );
+      dlg.setDefaultCloseOperation ( JDialog.DISPOSE_ON_CLOSE );
+
+      DlgListener theListener = new DlgListener ( this );
+
+      Container d = dlg.getContentPane ();
+      d.setLayout ( new BorderLayout ( 8, 8 ) );
+
+      // spacer
+      d.add ( new JLabel ( " " ), BorderLayout.NORTH );
+      d.add ( new JLabel ( "  " ), BorderLayout.EAST );
+
+      JPanel p = new JPanel ();
+
+      if ( FLAG_LABEL == ( FLAG_LABEL & flag ) )
+      {
+         // a single line label
+         JLabel l = new JLabel ( theTranslator.replace ( message[0] ) );
+         p.add ( l );
+      }
+      else if ( FLAG_TEXT == ( FLAG_TEXT & flag ) )
+      {
+         String msg = theTranslator.replace ( message[0] );
+         // a multi-line text display for helpdlg
+         StringTokenizer st = new StringTokenizer ( msg, "\n" );
+
+         int nRows = ( null == RowsCols ) ? 1 :
+                     Integer.parseInt ( RowsCols[0].toString () );
+         nRows = Math.max ( nRows, st.countTokens () );
+         int nCols = Math.max ( 1, msg.length () / nRows );
+
+         p.setLayout ( new GridLayout ( message.length, 1 ) );
+         JTextArea ta = new JTextArea ( msg, nRows, nCols );
+         ta.setEditable ( false );
+         ta.setFocusable ( false );
+         ta.setOpaque ( false );
+         // replace ugly monospaced font
+         ta.setFont ( p.getFont () );
+         p.add ( ta );
+      }
+      else if ( FLAG_INPUT == ( FLAG_INPUT & flag ) )
+      {
+         // a multi label/textfield entry dialog for inputdlg
+         GridBagConstraints gbc = new GridBagConstraints ();
+         gbc.insets.top = 4;
+         gbc.insets.left = 8;
+         gbc.gridx = 0;
+         gbc.anchor = GridBagConstraints.NORTHWEST;
+
+         p.setLayout ( new GridBagLayout () );
+         m_TextField = new JTextArea[message.length];
+
+         // default values
+         int nRows = 1;
+         int nCols = 10;
+
+         for ( int i = 0; i < message.length; i++ )
+         {
+            String msg = theTranslator.replace ( message[i] );
+            JLabel l = new JLabel ( msg );
+            l.setHorizontalAlignment ( Label.LEFT );
+            gbc.gridy = 2 * i;
+            p.add ( l, gbc );
+            /**
+             * @todo CHECK handling of RowsCols for inputdlg
+             */
+            if ( RowsCols != null )
+            {
+               if ( RowsCols.length == 2 * message.length )
+               {
+                  nRows = Integer.parseInt ( RowsCols[i].toString () );
+                  nCols = Integer.parseInt ( RowsCols[RowsCols.length / 2 +
+                                             i].toString () );
+               }
+            }
+
+            m_TextField[i] = new JTextArea ( "", Math.max ( nRows, 1 ), nCols );
+            // avoid resizing
+            m_TextField[i].setPreferredSize ( new Dimension ( Math.max ( nRows,
+               1 ), nCols ) );
+            m_TextField[i].setAutoscrolls ( false );
+            m_TextField[i].setFont ( p.getFont () );
+            m_TextField[i].setBorder ( new javax.swing.border.EtchedBorder () );
+            m_TextField[i].addKeyListener ( theListener );
+
+            gbc.gridy = 2 * i + 1;
+            p.add ( m_TextField[i], gbc );
+         }
+
+         if ( defaults != null )
+         {
+            if ( defaults.length == message.length )
+            {
+               for ( int i = 0; i < message.length; i++ )
+               {
+                  String def = theTranslator.replace ( defaults[i].toString () );
+                  m_TextField[i].setText ( def );
+               }
+            }
+         }
+      }
+      else if ( DLG_LIST == ( DLG_LIST & flag ) )
+      {
+         GridBagConstraints gbc = new GridBagConstraints ();
+         gbc.insets.top = 4;
+         gbc.insets.left = 8;
+         gbc.gridx = 0;
+         gbc.anchor = GridBagConstraints.NORTHWEST;
+
+         p.setLayout ( new GridBagLayout () );
+
+         for ( int i = 0; i < message.length; i++ )
+         {
+            // a single line label
+            String msg = theTranslator.replace ( message[i] );
+            JLabel l = new JLabel ( msg );
+            gbc.gridy = i;
+            p.add ( l, gbc );
+         }
+
+         String lst[] = new String[list.length];
+
+         for ( int i = 0; i < list.length; i++ )
+         {
+            lst[i] = theTranslator.replace ( list[i] );
+         }
+         m_List = new JList ( lst );
+
+         // replace ugly monospaced font
+         m_List.setFont ( p.getFont () );
+
+         m_List.setMinimumSize ( new Dimension ( Math.max ( 1,
+            Integer.parseInt ( RowsCols[0].toString () ) ),
+                                                 Math.max ( 1,
+            Integer.parseInt ( RowsCols[1].toString () ) ) ) );
+         m_List.setPreferredSize ( new Dimension ( Math.max ( 1,
+            Integer.parseInt ( RowsCols[1].toString () ) ),
+            Math.max ( 1,
+                       Integer.parseInt ( RowsCols[0].toString () ) ) ) );
+         m_List.setBorder ( new javax.swing.border.EtchedBorder () );
+
+         gbc.gridy = message.length;
+         gbc.fill = GridBagConstraints.HORIZONTAL;
+         p.add ( m_List, gbc );
+
+         if ( on.toLowerCase ().equals ( "single" ) )
+         {
+            // single selection list
+            m_List.setSelectionMode ( ListSelectionModel.SINGLE_SELECTION );
+
+            m_List.setSelectedIndex ( Integer.parseInt (
+               defaults[0].toString () ) - 1 );
+         }
+         else
+         {
+            // multiple selection possible
+            m_List.setSelectionMode ( ListSelectionModel.
+                                      MULTIPLE_INTERVAL_SELECTION );
+
+            int selection[] = new int[defaults.length];
+            for ( int i = 0; i < defaults.length; i++ )
+            {
+               selection[i] = Integer.parseInt ( defaults[i].toString () ) - 1;
+            }
+            m_List.setSelectedIndices ( selection );
+
+            JButton b = new JButton ( "Select All" );
+            b.setActionCommand ( "SELALL" );
+            b.addActionListener ( theListener );
+            gbc.gridy = message.length + 1;
+            gbc.fill = GridBagConstraints.HORIZONTAL;
+            p.add ( b, gbc );
+         }
+
+      }
+
+      // prepare icon, if any
+      String sIconFile = null;
+      String sIconResource = null;
+      Icon theIcon = null;
+
+      if ( FLAG_ERROR == ( FLAG_ERROR & flag ) )
+      {
+         sIconFile = "images/error.png";
+         // Java for Windows
+         sIconResource = "OptionPane.errorIcon";
+         // Java for Linux does not offer these standard icons...
+      }
+      else if ( FLAG_WARNING == ( FLAG_WARNING & flag ) )
+      {
+         sIconFile = "images/warning.png";
+         // Java for Windows
+         sIconResource = "OptionPane.warningIcon";
+         // Java for Linux does not offer these standard icons...
+      }
+      else if ( FLAG_QUESTION == ( FLAG_QUESTION & flag ) )
+      {
+         sIconFile = "images/question.png";
+         // Java for Windows
+         sIconResource = "OptionPane.questionIcon";
+         // Java for Linux does not offer these standard icons...
+      }
+      else if ( FLAG_INFORMATION == ( FLAG_INFORMATION & flag ) )
+      {
+         sIconFile = "images/information.png";
+         // Java for Windows
+         sIconResource = "OptionPane.informationIcon";
+         // Java for Linux does not offer these standard icons...
+      }
+
+      // first try to find the UIManager specific icon to fit look and feel
+      // Note: the Windows XP look and feel offers 50 icons.
+      if ( sIconResource != null )
+      {
+         UIDefaults df = UIManager.getLookAndFeelDefaults ();
+         theIcon = df.getIcon ( sIconResource );
+      }
+
+      // fallback on bitmap image resource if icon was not found
+      if ( theIcon == null &&
+           sIconFile != null )
+      {
+         URL theResource = JDialogBox.class.getResource ( sIconFile );
+         if ( theResource != null )
+         {
+            theIcon = new ImageIcon ( theResource );
+         }
+      }
+
+      if ( theIcon != null )
+      {
+         // dummy panel to provide space around icon
+         JPanel pi = new JPanel ( new GridLayout ( 1, 3 ) );
+         pi.add ( new JLabel () );
+         pi.add ( new JLabel ( theIcon ) );
+         pi.add ( new JLabel () );
+         d.add ( pi, BorderLayout.WEST );
+
+         // use Octave icon if available. otherwise use dialog icon
+         Icon theOctaveIcon = getOctaveIcon ();
+         prepareFrameIcon ( m_ParentFrame,
+                            theOctaveIcon == null ? theIcon : theOctaveIcon );
+      }
+
+      d.add ( p, BorderLayout.CENTER );
+
+      // button bar (2 rows of 3 columns each
+
+      p = new JPanel ();
+      p.setLayout ( new java.awt.GridLayout ( 2, 3 ) );
+
+      // spacer row
+      p.add ( new JLabel () );
+      p.add ( new JLabel () );
+      p.add ( new JLabel () );
+
+      if ( DLG_QUEST == ( DLG_QUEST & flag ) )
+      {
+         // questdlg with empty option[2]: only two buttons
+         if ( nostring.length () < 1 )
+         {
+            // spacer: left
+            p.add ( new JLabel () );
+         }
+      }
+      else
+      {
+         // spacer: left
+         p.add ( new JLabel () );
+      }
+
+      m_ButtonOK = new JButton ( theTranslator.replace ( okstring ) );
+      m_ButtonOK.setActionCommand ( "OK" );
+      m_ButtonOK.addActionListener ( theListener );
+      m_Focus = m_ButtonOK;
+      p.add ( m_ButtonOK );
+
+      if ( DLG_QUEST == ( DLG_QUEST & flag ) )
+      {
+         // questdlg with empty option[2]: only two buttons
+         if ( nostring.length () > 01 )
+         {
+            // questdlg has three buttons
+            m_ButtonNO = new JButton ( theTranslator.replace ( nostring ) );
+            m_ButtonNO.setActionCommand ( "NO" );
+            m_ButtonNO.addActionListener ( theListener );
+            p.add ( m_ButtonNO );
+            if ( DLG_QUEST == ( DLG_QUEST & flag ) )
+            {
+               // select default button
+               if ( list[3].equals ( nostring ) )
+               {
+                  m_Focus = m_ButtonNO;
+               }
+            }
+         }
+      }
+
+      if ( DLG_INPUT == ( DLG_INPUT & flag ) ||
+           DLG_LIST == ( DLG_LIST & flag ) ||
+           DLG_QUEST == ( DLG_QUEST & flag ) )
+      {
+         m_ButtonCANCEL = new JButton ( theTranslator.replace ( cancelstring ) );
+         m_ButtonCANCEL.setActionCommand ( "CANCEL" );
+         m_ButtonCANCEL.addActionListener ( theListener );
+         p.add ( m_ButtonCANCEL );
+         if ( DLG_QUEST == ( DLG_QUEST & flag ) )
+         {
+            // select default button
+            if ( list[3].equals ( cancelstring ) )
+            {
+               m_Focus = m_ButtonCANCEL;
+            }
+         }
+      }
+      else
+      {
+         // spacer: right
+         p.add ( new JLabel () );
+      }
+
+      d.add ( p, BorderLayout.SOUTH );
+      dlg.pack ();
+
+      dlg.addWindowListener ( theListener );
+
+      if ( on.equals ( "on" ) )
+      {
+         m_ParentFrame.setAlwaysOnTop ( true );
+      }
+
+      // center dialog on screen
+      Dimension dlgSize = dlg.getSize ();
+      Dimension screenSize = Toolkit.getDefaultToolkit ().getScreenSize ();
+
+      dlg.setLocation ( ( screenSize.width - dlgSize.width ) / 2,
+                        ( screenSize.height - dlgSize.height ) / 2 );
+
+      dlg.setVisible ( true );
+      dlg.requestFocus ();
+
+      m_ParentFrame.setVisible ( false );
+
+      return ( 1 );
+   }
+
+
+   /**
+    *
+    * @return Icon - null if icon was not found
+    */
+   private Icon getOctaveIcon ()
+   {
+      Icon theIcon = null;
+      URL theResource = JDialogBox.class.getResource ( "images/octave.png" );
+      if ( theResource != null )
+      {
+         theIcon = new ImageIcon ( theResource );
+      }
+      return theIcon;
+   }
+
+
+   /**
+    * Replace the standard Java frame icon with an Octave Icon.
+    *
+    * @param theFrame Frame - the Frame to decorate
+    * @param theIcon Icon - the icon to use if octave icon is not found.
+    */
+   private void prepareFrameIcon ( Frame theFrame, Icon theIcon )
+   {
+      // prepare icon for upper left corner of Frame window
+      // maybe there is a simpler way to achieve this
+      int w = theIcon.getIconWidth ();
+      int h = theIcon.getIconHeight ();
+      // Frame must be made displayable by packing it for createImage() to succeed
+      theFrame.pack ();
+      Image theImage = theFrame.createImage ( w, h );
+      theIcon.paintIcon ( theFrame, theImage.getGraphics (), 0, 0 );
+      theFrame.setIconImage ( theImage );
+   }
+
+
+   /**
+    * Select Look and Feel
+    *
+    * @param bSystemLnF boolean - if true, the current systesm Look&Feel is used,
+    * otherwise the Swing/Metal cross platform Look&Feel is used.
+    */
+   private void setSystemLnF ( boolean bSystemLnF )
+   {
+      try
+      {
+         if ( bSystemLnF )
+         {
+            // switch from Swing LnF to local system LnF
+            UIManager.setLookAndFeel ( UIManager.
+                                       getSystemLookAndFeelClassName () );
+         }
+         else
+         {
+            // use Swing LnF
+            UIManager.setLookAndFeel ( UIManager.
+                                       getCrossPlatformLookAndFeelClassName () );
+         }
+      }
+      catch ( Exception exception )
+      {
+         exception.printStackTrace ();
+      }
+   }
+
+
+   /**
+    * Called when the dialog is closed. Allows for specific cleanup actions.
+    *
+    * @param closeMethod int - OctaveDialog.CLOSE_OK, OctaveDialog.CLOSE_CANCEL
+    */
+   public void closeDialog ( int closeMethod )
+   {
+      m_CloseMethod = closeMethod;
+      m_ParentFrame.dispose ();
+   }
+
+
+   public void setFocus ()
+   {
+      if ( null != m_Focus )
+      {
+         m_Focus.requestFocus ();
+         m_ParentFrame.getRootPane ().setDefaultButton ( m_Focus );
+         m_ParentFrame.setAlwaysOnTop ( true );
+      }
+   }
+
+
+   /**
+    * Tests the dialogs
+    *
+    * @param args String[] - not used.
+    */
+   public static void main ( String[] args )
+   {
+      TeXtranslator t = new TeXtranslator();
+
+      if(false)
+      {
+         // find out key names of icon UI resources
+         UIDefaults df = UIManager.getLookAndFeelDefaults ();
+
+         for ( Enumeration e = df.keys (); e.hasMoreElements (); )
+         {
+            String s = e.nextElement ().toString ();
+
+            if ( s.toLowerCase ().contains ( "icon" ) )
+            {
+               System.out.println ( s );
+            }
+         }
+      }
+
+      try
+      {
+         Class[] argTypes = new Class[1];
+         argTypes[0] = String.class;
+
+         java.lang.reflect.Constructor c = ClassHelper.findConstructor ( java.lang.StringBuffer.class,
+                                                       argTypes );
+         Object argValues[] = new Object[1];
+         argValues[0] = new String("initial value");
+         Object sb = c.newInstance(argValues);
+         System.out.println(sb.toString());
+
+         ClassHelper.invokeMethod(sb,"append",argValues,argTypes);
+         System.out.println(sb.toString());
+
+         argValues = new Object[2];
+         argTypes = new Class[2];
+         argTypes[0] =  Integer.class;
+         argTypes[1] = String.class;
+         argValues[0] = new Integer(0);
+         argValues[1] = new String("inserted");
+
+         ClassHelper.invokeMethod(sb,"insert",argValues,argTypes);
+         System.out.println(sb.toString());
+      }
+      catch ( Throwable e )
+      {}
+
+      if ( true )
+      {
+         return;
+      }
+
+      helpdlg ( "If you need help\nyou should ask for help\nif someone is around\notherwise you are on your own.",
+                "Information" );
+
+      String[] options = new String[4];
+      options[0] = "Yeah \\vartheta is too low";
+      options[1] = "Maybe";
+      options[2] = "Nay \\vartheta is too high";
+      options[3] = "Maybe";
+
+      System.out.println ( questdlg ( "Is it too cold?", "Temperature", options ) );
+
+      // test variants of errordlg
+      // does not affect layering of dialog
+      errordlg ( "Background error!", "Error" );
+
+      // test variants of helpdlg
+
+      // test variants of inputdlg
+      String prompt[] = new String[2];
+      prompt[0] = "Question 1";
+      prompt[1] = "Question 2";
+      String defaults[] = new String[2];
+      defaults[0] = "1.1";
+      defaults[1] = "2.2";
+      String title = "Enter values";
+
+      Integer rc[] = new Integer[2 * 2];
+      rc[0] = new Integer ( 1 );
+      rc[1] = new Integer ( 2 );
+      rc[2] = new Integer ( 10 );
+      rc[3] = new Integer ( 20 );
+
+      inputdlg ( prompt, title, rc, defaults );
+
+      String listcell[] = new String[4];
+      listcell[0] = "a \\alpha";
+      listcell[1] = "b \\beta";
+      listcell[2] = "c \\gamma";
+      listcell[3] = "d \\delta";
+
+      Integer size[] = new Integer[2];
+      size[0] = new Integer ( 80 );
+      size[1] = new Integer ( 100 );
+
+      Integer initial[] = new Integer[2];
+      initial[0] = new Integer ( 4 );
+      initial[1] = new Integer ( 2 );
+
+      String promptcell[] = new String[2];
+      promptcell[0] = "Select something";
+      promptcell[1] = "(or even more than one thing)";
+
+      int idx[] = listdlg ( listcell,
+                            "Multiple",
+                            size,
+                            initial,
+                            "name",
+                            promptcell,
+                            "okstring",
+                            "cancelstring" );
+
+      if ( idx != null )
+      {
+         for ( int i = 0; i < idx.length; i++ )
+         {
+            System.out.println ( idx[i] );
+         }
+      }
+   }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/org/octave/Matrix.java	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,355 @@
+/* Copyright (C) 2007 Michael Goffioul
+**
+** 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/>.
+*/
+
+package org.octave;
+
+import java.nio.*;
+import java.text.DecimalFormat;
+
+public class Matrix
+{
+	private int[] dims;
+	private Buffer data;
+	private Object cache = null;
+
+	public Matrix()
+	{
+		this(new double[0], new int[] {0, 0});
+	}
+
+	public Matrix(double[] data)
+	{
+		this(data, new int[] {1, data.length});
+	}
+
+	public Matrix(double[][] data)
+	{
+		int m = data.length;
+		int n = (m > 0 ? data[0].length : 0);
+		int idx = 0;
+		double[] buf = new double[m*n];
+		
+		for (int j=0; j<n; j++)
+			for (int i=0; i<m; i++)
+				buf[idx++] = data[i][j];
+		this.data = DoubleBuffer.wrap(buf);
+		this.dims = new int[] {m, n};
+		this.cache = data;
+	}
+
+	public Matrix(double[][][] data)
+	{
+		int m = data.length;
+		int n = (m > 0 ? data[0].length : 0);
+		int p = (n > 0 ? data[0][0].length : 0);
+		int idx = 0;
+		double[] buf = new double[m*n*p];
+
+		for (int k=0; k<p; k++)
+			for (int j=0; j<n; j++)
+				for (int i=0; i<m; i++)
+					buf[idx++] = data[i][j][k];
+		this.data = DoubleBuffer.wrap(buf);
+		this.dims = new int[] {m, n, p};
+		this.cache = data;
+	}
+
+	public Matrix(double[] data, int[] dims)
+	{
+		this.dims = dims;
+		this.data = DoubleBuffer.wrap(data);
+	}
+
+	public Matrix(byte[] data, int[] dims)
+	{
+		this.dims = dims;
+		this.data = ByteBuffer.wrap(data);
+	}
+
+	public Matrix(int[] data, int[] dims)
+	{
+		this.dims = dims;
+		this.data = IntBuffer.wrap(data);
+	}
+
+	public double[] toDouble()
+	{
+		if (data instanceof DoubleBuffer)
+			return ((DoubleBuffer)data).array();
+		else
+			throw new ClassCastException("matrix is not of type `double'");
+	}
+
+	public byte[] toByte()
+	{
+		if (data instanceof ByteBuffer)
+			return ((ByteBuffer)data).array();
+		else
+			throw new ClassCastException("matrix is not of type `byte'");
+	}
+
+	public int[] toInt()
+	{
+		if (data instanceof IntBuffer)
+			return ((IntBuffer)data).array();
+		else
+			throw new ClassCastException("matrix is not of type `integer'");
+	}
+
+	public int getNDims()
+	{
+		return (dims == null ? 0 : dims.length);
+	}
+
+	public int getDim(int index)
+	{
+		return (dims == null || index < 0 || index >= dims.length ? -1 : dims[index]);
+	}
+
+	public int[] getDims()
+	{
+		return dims;
+	}
+
+	public String getClassName()
+	{
+		if (data instanceof DoubleBuffer)
+			return "double";
+		else if (data instanceof IntBuffer)
+			return "integer";
+		else if (data instanceof ByteBuffer)
+			return "byte";
+		else
+			return "unknown";
+	}
+
+	public String toString()
+	{
+		if (dims == null || data == null)
+			return "null";
+
+		String s = "";
+
+		if (dims.length == 2 && dims[0] == 1 && dims[1] <= 5)
+		{
+			if (data instanceof DoubleBuffer)
+			{
+				DoubleBuffer b = (DoubleBuffer)data;
+				DecimalFormat fmt = new DecimalFormat("0.0000 ");
+				for (int i=0; i<b.capacity(); i++)
+					s += fmt.format(b.get(i));
+			}
+			else if (data instanceof IntBuffer)
+			{
+				IntBuffer b = (IntBuffer)data;
+				for (int i=0; i<b.capacity(); i++)
+					s += (Integer.toString(b.get(i)) + " ");
+			}
+			else if (data instanceof ByteBuffer)
+			{
+				ByteBuffer b = (ByteBuffer)data;
+				for (int i=0; i<b.capacity(); i++)
+					s += (Byte.toString(b.get(i)) + " ");
+			}
+			s = ("[ " + s + "]");
+		}
+		else if (dims.length == 2 && dims[0] == 0 && dims[1] == 0)
+			s = "[ ]";
+		else
+		{
+			for (int i=0; i<dims.length; i++)
+				if (i == 0)
+					s = Integer.toString(dims[i]);
+				else
+					s += (" by " + Integer.toString(dims[i]));
+			s = ("[ (" + s + ") array of " + getClassName() + " ]");
+		}
+
+		return s;
+	}
+
+	public static Object ident(Object o)
+	{
+		System.out.println(o);
+		return o;
+	}
+
+	public boolean equals(Object value)
+	{
+		if (value instanceof Matrix)
+		{
+			Matrix m = (Matrix)value;
+			if (!java.util.Arrays.equals(dims, m.dims))
+				return false;
+			return data.equals(m.data);
+		}
+		else
+			return false;
+	}
+
+	public boolean isEmpty()
+	{
+		return (data == null || dims == null || data.capacity() == 0);
+	}
+
+	public boolean isVector()
+	{
+		return (dims.length == 1 ||
+			(dims.length == 2 && (dims[0] == 1 || dims[1] == 1 ||
+					      (dims[0] == 0 && dims[1] == 0))));
+	}
+
+	public int getLength()
+	{
+		return data.capacity();
+	}
+
+	public double[] asDoubleVector()
+	{
+		if (data instanceof DoubleBuffer)
+			return toDouble();
+		else
+			System.out.println("Warning: invalid conversion to double vector");
+		return null;
+	}
+
+	public double[][] asDoubleMatrix()
+	{
+		if (cache != null)
+		{
+			try { return (double[][])cache; }
+			catch (ClassCastException e) { }
+		}
+
+		if (data instanceof DoubleBuffer && dims.length == 2)
+		{
+			double[][] m = new double[dims[0]][dims[1]];
+			double[] data = ((DoubleBuffer)this.data).array();
+			int idx = 0;
+			if (data.length > 0)
+				for (int j=0; j<m[0].length; j++)
+					for (int i=0; i<m.length; i++)
+						m[i][j] = data[idx++];
+			cache = m;
+			return m;
+		}
+		else
+			System.out.println("Warning: invalid conversion to double matrix");
+
+		return null;
+	}
+	
+	public double[][][] asDoubleMatrix3()
+	{
+		if (cache != null)
+		{
+			try { return (double[][][])cache; }
+			catch (ClassCastException e) { }
+		}
+
+		if (data instanceof DoubleBuffer && dims.length == 3)
+		{
+			double[][][] m = new double[dims[0]][dims[1]][dims[2]];
+			double[] data = ((DoubleBuffer)this.data).array();
+			int idx = 0;
+			if (data.length > 0)
+				for (int k=0; k<dims[2]; k++)
+					for (int j=0; j<dims[1]; j++)
+						for (int i=0; i<dims[0]; i++)
+							m[i][j][k] = data[idx++];
+			cache = m;
+			return m;
+		}
+		else
+			System.out.println("Warning: invalid conversion to double array");
+
+		return null;
+	}
+
+	public int[][] asIntMatrix()
+	{
+		if (cache != null)
+		{
+			try { return (int[][])cache; }
+			catch (ClassCastException e) { }
+		}
+
+		if (data instanceof IntBuffer && dims.length == 2)
+		{
+			int[][] m = new int[dims[0]][dims[1]];
+			int[] data = ((IntBuffer)this.data).array();
+			int idx = 0;
+			if (data.length > 0)
+				for (int j=0; j<m[0].length; j++)
+					for (int i=0; i<m.length; i++)
+						m[i][j] = data[idx++];
+			cache = m;
+			return m;
+		}
+		else
+			System.out.println("Warning: invalid conversion to integer matrix");
+
+		return null;
+	}
+
+	public double minValue()
+	{
+		double val = Double.POSITIVE_INFINITY;
+
+		if (data instanceof DoubleBuffer)
+		{
+			double[] buf = ((DoubleBuffer)data).array();
+			for (int i=0; i<buf.length; i++)
+				if (buf[i] < val)
+					val = buf[i];
+		}
+		else if (data instanceof ByteBuffer)
+		{
+			byte[] buf = ((ByteBuffer)data).array();
+			for (int i=0; i<buf.length; i++)
+				if (buf[i] < val)
+					val = buf[i];
+		}
+		else
+			System.out.println("Warning: cannot compute min value for array of type `" + getClassName() + "'");
+
+		return val;
+	}
+
+	public double maxValue()
+	{
+		double val = Double.NEGATIVE_INFINITY;
+
+		if (data instanceof DoubleBuffer)
+		{
+			double[] buf = ((DoubleBuffer)data).array();
+			for (int i=0; i<buf.length; i++)
+				if (buf[i] > val)
+					val = buf[i];
+		}
+		else if (data instanceof ByteBuffer)
+		{
+			byte[] buf = ((ByteBuffer)data).array();
+			for (int i=0; i<buf.length; i++)
+				if (buf[i] > val)
+					val = buf[i];
+		}
+		else
+			System.out.println("Warning: cannot compute max value for array of type `" + getClassName() + "'");
+
+		return val;
+	}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/org/octave/OctClassLoader.java	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,68 @@
+/* Copyright (C) 2007 Michael Goffioul
+**
+** 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/>.
+*/
+
+package org.octave;
+
+import java.io.File;
+
+public class OctClassLoader extends java.net.URLClassLoader
+{
+  public OctClassLoader ()
+    {
+      super (new java.net.URL[0]);
+    }
+
+  public OctClassLoader (ClassLoader parent)
+    {
+      super (new java.net.URL[0], parent);
+    }
+
+  protected Class findClass (String name) throws ClassNotFoundException
+    {
+      //System.out.println ("Looking for class " + name);
+      return super.findClass (name);
+    }
+
+  protected String findLibrary (String libname)
+    {
+      // Look dynamically into java.library.path, because Sun VM does
+      // not do it (seems to cache initial java.library.path instead)
+
+      String[] paths = System.getProperty ("java.library.path").split (File.pathSeparator);
+
+      libname = System.mapLibraryName (libname);
+      for (int i=0; i<paths.length; i++)
+        {
+          File f = new File (paths[i], libname);
+          if (f.exists ())
+            return f.getAbsolutePath();
+        }
+
+      return null;
+    }
+
+  public void addClassPath (String name) throws Exception
+    {
+      java.io.File f = new java.io.File (name);
+      addURL (f.toURI ().toURL ());
+    }
+
+  // new -MH-
+  public void addURL (java.net.URL url)
+    {
+      super.addURL (url);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/org/octave/Octave.java	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,219 @@
+/* Copyright (C) 2007 Michael Goffioul
+**
+** 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/>.
+*/
+
+package org.octave;
+
+import java.util.*;
+
+public class Octave
+{
+  static
+  {
+    System.load (System.getProperty ("octave.java.path") + java.io.File.separator + "__java__.oct");
+  }
+
+  private static Object notifyObject = null;
+  private static Object[] args = null;
+  private static LinkedList invokeList = new LinkedList();
+  private static LinkedList waitList = new LinkedList();
+
+  public native static boolean call (String name, Object[] argin, Object[] argout);
+  public native static void doInvoke(int ID, Object[] args);
+  public native static void doEvalString(String cmd);
+  public native static boolean needThreadedInvokation();
+
+  public static void checkPendingAction()
+    {
+      if (notifyObject != null)
+        {
+          synchronized(notifyObject)
+            {
+              if (notifyObject instanceof OctaveReference)
+                doInvoke(((OctaveReference)notifyObject).getID(), args);
+              else if (notifyObject instanceof String)
+                doEvalString((String)notifyObject);
+              notifyObject.notifyAll();
+            }
+          notifyObject = null;
+          args = null;
+        }
+
+      Object obj;
+      Object[] objArgs;
+
+      while (true)
+        {
+          obj = null;
+          objArgs = null;
+
+          synchronized (invokeList)
+            {
+              if (invokeList.size() > 0)
+                {
+                  obj = invokeList.remove();
+                  if (obj instanceof OctaveReference)
+                    objArgs = (Object[])invokeList.remove();
+                }
+            }
+
+          if (obj != null)
+            {
+              if (obj instanceof Runnable)
+                ((Runnable)obj).run();
+              else if (obj instanceof OctaveReference)
+                doInvoke(((OctaveReference)obj).getID(), objArgs);
+              else if (obj instanceof String)
+                doEvalString((String)obj);
+            }
+          else
+            break;
+        }
+      /*
+      synchronized(invokeList)
+        {
+          while (invokeList.size() > 0)
+            {
+              Object obj = invokeList.remove();
+	      if (obj instanceof Runnable)
+                ((Runnable)obj).run();
+              if (obj instanceof OctaveReference)
+                {
+                  Object[] objArgs = (Object[])invokeList.remove();
+                  doInvoke(((OctaveReference)obj).getID(), objArgs);
+                }
+              else if (obj instanceof String)
+                doEvalString((String)obj);
+            }
+        }
+        */
+    }
+
+  private static void checkWaitState()
+    {
+      if (waitList.size() > 0)
+        {
+          Object wObj = waitList.getFirst();
+          synchronized (wObj)
+            {
+              wObj.notifyAll();
+            }
+        }
+    }
+
+  public static void invokeAndWait(OctaveReference ref, Object[] invokeArgs)
+    {
+      if (needThreadedInvokation())
+        {
+          synchronized(ref)
+            {
+              notifyObject = ref;
+              args = invokeArgs;
+              try { checkWaitState(); ref.wait(); }
+              catch (InterruptedException e) {}
+            }
+        }
+      else
+        doInvoke(ref.getID(), invokeArgs);
+    }
+
+  public static void evalAndWait(String cmd)
+    {
+      if (needThreadedInvokation())
+        {
+          synchronized(cmd)
+            {
+              notifyObject = cmd;
+              args = null;
+              try { checkWaitState(); cmd.wait(); }
+              catch (InterruptedException e) {}
+            }
+        }
+      else
+        doEvalString(cmd);
+    }
+
+  public static void invokeLater(Runnable r)
+    {
+      if (needThreadedInvokation())
+        synchronized(invokeList)
+          {
+            invokeList.add(r);
+            checkWaitState();
+          }
+      else
+        r.run();
+    }
+
+  public static void invokeLater(OctaveReference ref, Object[] invokeArgs)
+    {
+      if (needThreadedInvokation())
+        synchronized(invokeList)
+          {
+            invokeList.add(ref);
+            invokeList.add(invokeArgs);
+            checkWaitState();
+          }
+      else
+        doInvoke(ref.getID(), invokeArgs);
+    }
+
+  public static void evalLater(String cmd)
+    {
+      if (needThreadedInvokation())
+        synchronized(invokeList)
+          {
+            invokeList.add(cmd);
+            checkWaitState();
+          }
+      else
+        doEvalString(cmd);
+    }
+
+  public static void waitFor(Object wObj)
+    {
+      waitList.add(0, wObj);
+      synchronized (wObj)
+        {
+          while (waitList.size() > 0 && waitList.getFirst() == wObj)
+            {
+              try { wObj.wait(); }
+              catch (InterruptedException e) {}
+              checkPendingAction();
+            }
+        }
+    }
+
+  public static void endWaitFor(Object obj)
+    {
+      boolean isCurrentWaitObject = (waitList.size() > 0 && waitList.getFirst() == obj);
+
+      waitList.remove(obj);
+	  if (needThreadedInvokation() && isCurrentWaitObject)
+        synchronized (obj)
+          {
+            obj.notifyAll();
+          }
+    }
+
+  public static Object do_test (String name, Object arg0) throws Exception
+    {
+      Object[] argin = new Object[] { arg0 };
+	  Object[] argout = new Object[1];
+      if (call (name, argin, argout))
+        return argout[0];
+      throw new Exception ("octave call failed");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/org/octave/OctaveReference.java	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,63 @@
+/* Copyright (C) 2007 Michael Goffioul
+**
+** 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/>.
+*/
+
+package org.octave;
+
+public class OctaveReference
+{
+	static
+	{
+		System.load (System.getProperty ("octave.java.path") + java.io.File.separator + "__java__.oct");
+	}
+  
+	private int ID;
+
+	public OctaveReference(int ID)
+	{
+		this.ID = ID;
+	}
+
+	private native static void doFinalize(int ID);
+
+	protected void finalize() throws Throwable
+	{
+		doFinalize(this.ID);
+	}
+
+	public String toString()
+	{
+		return ("<octave reference " + this.ID + ">");
+	}
+
+	public int getID()
+	{
+		return this.ID;
+	}
+
+	public Object invoke(Object[] args)
+	{
+		//System.out.println("OctaveReference::invoke");
+		Octave.doInvoke(this.ID, args);
+		return null;
+	}
+
+	public synchronized Object invokeAndWait(Object[] args)
+	{
+		//System.out.println("OctaveReference::invokeandWait");
+		Octave.invokeAndWait(this, args);
+		return null;
+	}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/org/octave/TeXcode.java	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,35 @@
+/**
+ *
+ * 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/>.
+ *
+ * A class to hold a TeX character code -> Unicode translation pair.
+ *
+ * <p>Copyright (c) 2010 Martin Hepperle</p>
+ *
+ * @author Martin Hepperle
+ * @version 1.0
+ */
+package org.octave;
+
+public class TeXcode
+{
+   protected String tex;
+   protected char ucode;
+
+   public TeXcode ( String t, char u )
+   {
+      tex = t;
+      ucode = u;
+   }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/org/octave/TeXtranslator.java	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,264 @@
+/**
+ *
+ * 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/>.
+ *
+ *
+ * A primitive TeX character translator.
+ * Provides methods to translate a subset of TeX symbol strings
+ * into their aequivalent Unicode representation.
+ *
+ * Note that not all Unicode character sets contain all these characters.
+ * Suitable Windows fonts are e.g.:<br>
+ * - Lucida Sans Unicode<br>
+ * - Arial Unicode MS<br>
+ * - MS Mincho<br>
+ *
+ * <p>Copyright (c) 2010 Martin Hepperle</p>
+ *
+ * @author Martin Hepperle
+ * @version 1.0
+ */
+package org.octave;
+
+public class TeXtranslator
+{
+   private TeXcode m_texTable[] =
+      {
+      // lower case
+      new TeXcode ( "alpha", '\u03B1' ),
+      new TeXcode ( "beta", '\u03B2' ),
+      new TeXcode ( "gamma", '\u03B3' ),
+      new TeXcode ( "delta", '\u03B4' ),
+      new TeXcode ( "epsilon", '\u03B5' ),
+      new TeXcode ( "zeta", '\u03B6' ),
+      new TeXcode ( "eta", '\u03B7' ),
+      new TeXcode ( "theta", '\u03B8' ),
+      new TeXcode ( "vartheta", '\u03D1' ),
+      new TeXcode ( "iota", '\u03B9' ),
+      new TeXcode ( "kappa", '\u03BA' ),
+      new TeXcode ( "lambda", '\u03BB' ),
+      new TeXcode ( "mu", '\u03BC' ),
+      new TeXcode ( "nu", '\u03BD' ),
+      new TeXcode ( "xi", '\u03BE' ),
+      new TeXcode ( "pi", '\u03C0' ),
+      new TeXcode ( "rho", '\u03C1' ),
+      new TeXcode ( "sigma", '\u03C3' ),
+      new TeXcode ( "varsigma", '\u03C2' ),
+      new TeXcode ( "tau", '\u03C4' ),
+      new TeXcode ( "phi", '\u03C6' ),
+      new TeXcode ( "chi", '\u03C7' ),
+      new TeXcode ( "psi", '\u03C8' ),
+      new TeXcode ( "omega", '\u03C9' ),
+      new TeXcode ( "upsilon", '\u03C5' ),
+      // upper case
+      new TeXcode ( "Gamma", '\u0393' ),
+      new TeXcode ( "Delta", '\u0394' ),
+      new TeXcode ( "Theta", '\u0398' ),
+      new TeXcode ( "Lambda", '\u039B' ),
+      new TeXcode ( "Pi", '\u03A0' ),
+      new TeXcode ( "Xi", '\u039E' ),
+      new TeXcode ( "Sigma", '\u03A3' ),
+      new TeXcode ( "Upsilon", '\u03A5' ),
+      new TeXcode ( "Phi", '\u03A6' ),
+      new TeXcode ( "Psi", '\u03A8' ),
+      new TeXcode ( "Omega", '\u03A9' ),
+      // complex
+      new TeXcode ( "Im", '\u2111' ),
+      new TeXcode ( "Re", '\u211c' ),
+      // special
+      new TeXcode ( "leq", '\u2264' ),
+      new TeXcode ( "geq", '\u2265' ),
+      new TeXcode ( "neq", '\u2260' ),
+      new TeXcode ( "pm", '\u00B1' ),
+      new TeXcode ( "infty", '\u221E' ),
+      new TeXcode ( "partial", '\u2202' ),
+      new TeXcode ( "approx", '\u2248' ),
+      new TeXcode ( "circ", '\u2218' ),
+      new TeXcode ( "bullet", '\u2022' ),
+      new TeXcode ( "times", '\u00D7' ),
+      new TeXcode ( "sim", '\u007E' ),
+      new TeXcode ( "nabla", '\u2207' ),
+      new TeXcode ( "ldots", '\u2026' ),
+      new TeXcode ( "exists", '\u2203' ),
+      new TeXcode ( "neg", '\u00AC' ),
+      new TeXcode ( "aleph", '\u2135' ),
+      new TeXcode ( "forall", '\u2200' ),
+      new TeXcode ( "cong", '\u2245' ),
+      new TeXcode ( "wp", '\u2118' ),
+      new TeXcode ( "propto", '\u221D' ),
+      new TeXcode ( "otimes", '\u2297' ),
+      new TeXcode ( "oplus", '\u2295' ),
+      new TeXcode ( "oslash", '\u2298' ),
+      new TeXcode ( "cap", '\u2229' ),
+      new TeXcode ( "cup", '\u222A' ),
+      new TeXcode ( "ni", '\u220B' ),
+      new TeXcode ( "in", '\u2208' ),
+      new TeXcode ( "div", '\u00F7' ),
+      new TeXcode ( "equiv", '\u2261' ),
+      new TeXcode ( "int", '\u222B' ),
+      new TeXcode ( "perp", '\u22A5' ),
+      new TeXcode ( "wedge", '\u2227' ),
+      new TeXcode ( "vee", '\u2228' ),
+      // sets
+      new TeXcode ( "supseteq", '\u2287' ),
+      new TeXcode ( "supset", '\u2283' ),
+      new TeXcode ( "subseteq", '\u2286' ),
+      new TeXcode ( "subset", '\u2282' ),
+      // cards
+      new TeXcode ( "clubsuit", '\u2663' ),
+      new TeXcode ( "spadesuit", '\u2660' ),
+      new TeXcode ( "heartsuit", '\u2665' ),
+      new TeXcode ( "diamondsuit", '\u2666' ),
+      new TeXcode ( "copyright", '\u00A9' ),
+      // arrows
+      new TeXcode ( "leftarrow", '\u2190' ),
+      new TeXcode ( "uparrow", '\u2191' ),
+      new TeXcode ( "rightarrow", '\u2192' ),
+      new TeXcode ( "downarrow", '\u2193' ),
+      new TeXcode ( "leftrightarrow", '\u2194' ),
+      new TeXcode ( "updownarrow", '\u2195' ),
+   };
+
+   public TeXtranslator ()
+   {
+      /* DEBUG: output table to file
+      try
+      {
+         java.io.PrintWriter pwTeX = new java.io.PrintWriter ( "z:/tex.txt",
+            "UTF-8" );
+         java.io.PrintWriter pwHTML = new java.io.PrintWriter ( "z:/html.txt",
+            "UTF-8" );
+         java.io.PrintWriter pwOctave = new java.io.PrintWriter ( "z:/octave.txt",
+            "UTF-8" );
+         pwOctave.print ( "msgbox ( [" );
+         int i = 0;
+         for ( int k = 0; k < m_texTable.length; k++ )
+         {
+            if ( i++ == 0 )
+            {
+               pwTeX.print ( "@item " );
+               pwHTML.print ( "@item " );
+               pwOctave.print ( "          '" );
+            }
+            else
+            {
+               pwTeX.print ( "@tab " );
+               pwHTML.print ( "@tab " );
+               pwOctave.print ( "   " );
+            }
+            pwTeX.println ( "\\" + m_texTable[k].tex );
+            pwTeX.println ( "@tab '@math{\\" + m_texTable[k].tex + "}'" );
+            pwHTML.println ( "\\" + m_texTable[k].tex );
+            pwHTML.println ( "@tab '" + m_texTable[k].ucode + "'" );
+            pwOctave.print ( "\\\\" + m_texTable[k].tex+" " );
+            pwOctave.print ( " = ''\\" + m_texTable[k].tex + " ''" );
+            if ( i == 3 )
+            {
+               pwTeX.println ( "@c ----------" );
+               pwHTML.println ( "@c ----------" );
+               pwOctave.println ( "', 10, ..." );
+               i=0;
+            }
+            else
+            {
+               pwTeX.println ( "@tab" );
+               pwHTML.println ( "@tab" );
+               pwOctave.print ( "   " );
+            }
+         }
+         pwOctave.print ( "']);" );
+         pwTeX.close ();
+         pwHTML.close ();
+         pwOctave.close ();
+      }
+      catch ( Exception e )
+      {
+         ;
+      }
+      /* */
+   }
+
+
+   /*
+      NOT YET TRANSLATED
+     o
+     rfloor
+     lceil
+     lfloor
+     cdot
+     prime
+     0
+     rceil
+     surd
+     mid
+     varpi
+     langle
+     rangle
+    */
+
+   public String replace ( String s )
+   {
+      StringBuffer sb = new StringBuffer ( s );
+      // append trailing blank
+      sb.append ( ' ' );
+
+      int i = 0;
+      do
+      {
+         /* 26 08 2010 MH szatt search at index i */
+         i = sb.indexOf ( "\\", i );
+         if ( i > -1 )
+         {
+            int j = sb.indexOf ( " ", i );
+            if ( j > i )
+            {
+               String token = sb.substring ( i + 1, j );
+
+               for ( int k = 0; k < m_texTable.length; k++ )
+               {
+                  if ( m_texTable[k].tex.equals ( token ) )
+                  {
+                     sb.replace ( i, j + 1,
+                                  Character.toString ( m_texTable[k].ucode ) );
+                     break;
+                  }
+               }
+               if ( sb.charAt ( i ) == '\\' )
+               {
+                  // backslash sztill there: not found
+                  if ( sb.charAt ( i + 1 ) == 'n' )
+                  {
+                     // newline
+                     sb.replace ( i, i + 2, "\n" );
+                  }
+                  else if ( sb.charAt ( i + 1 ) == '\\' )
+                  {
+                     // backslash
+                     sb.replace ( i, i + 2, "\\" );
+                  }
+               }
+               /* 26 08 2010 MH
+                advance i to avoid deadlock in case of incorrect escape
+                sequences like \\\\alpha (double backslash) or
+                \\bogus (unknown escape sequence)
+                */
+               i++;
+            }
+         }
+      }
+      while ( i > -1 );
+      // finall: remove trailing blank
+      return ( sb.substring ( 0, sb.length () - 1 ).toString () );
+   }
+}
Binary file scripts/java/org/octave/images/error.png has changed
Binary file scripts/java/org/octave/images/information.png has changed
Binary file scripts/java/org/octave/images/octave.png has changed
Binary file scripts/java/org/octave/images/question.png has changed
Binary file scripts/java/org/octave/images/warning.png has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/questdlg.m	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,81 @@
+## Copyright (C) 2010 Martin Hepperle
+##
+## 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/>.
+
+## -*- texinfo -*-
+## @deftypefn  {Function file} {@var{P} =} questdlg (@var{MESSAGE}, @var{TITLE})
+## @deftypefnx {Function file} @var{P} = questdlg (@var{MESSAGE}, @var{TITLE}, @var{DEFAULT})
+## @deftypefnx {Function file} @var{P} = questdlg (@var{MESSAGE}, @var{TITLE}, @var{BTN1}, @var{BTN2}, @var{DEFAULT})
+## @deftypefnx {Function file} @var{P} = questdlg (@var{MESSAGE}, @var{TITLE}, @var{BTN1}, @var{BTN2}, @var{BTN3}, @var{DEFAULT})
+##
+## Displays the @var{MESSAGE} using a question dialog box. 
+## The dialog contains two or three buttons which all close the dialog. 
+## It returns the caption of the activated button.
+##
+## The @var{TITLE} can be used optionally to decorate the dialog caption.
+## The string @var{DEFAULT} identifies the default button, 
+## which is activated by pressing the ENTER key.
+## It must match one of the strings given in @var{BTN1}, @var{BTN2} or @var{BTN3}.
+##
+## If only @var{MESSAGE} and @var{TITLE} are specified, three buttons with
+## the default captions "Yes", "No", "Cancel" are used.
+##
+## If only two button captions @var{BTN1} and @var{BTN2} are specified, 
+## the dialog will have only these two buttons.
+##
+## @end deftypefn
+## @seealso{errordlg, helpdlg, inputdlg, listdlg, warndlg}
+
+function ret = questdlg(question,varargin)
+
+  if length(varargin) < 1
+    print_usage();
+  end
+  
+  options{1} = 'Yes';      % button1
+  options{2} = 'No';       % button2
+  options{3} = 'Cancel';   % button3
+  options{4} = 'Yes';      % default
+
+
+  switch length(varargin)
+  case 1
+     % title was given
+     title = varargin{1};
+  case 2
+     % title and default button string
+     title      = varargin{1};
+     options{4} = varargin{2}; % default
+  case 4
+     % title, two buttons and default button string
+     title      = varargin{1};
+     options{1} = varargin{2}; % button1
+     options{2} = '';          % not used, no middle button
+     options{3} = varargin{3}; % button3
+     options{4} = varargin{4}; % default
+  case 5
+     % title, three buttons and default button string
+     title      = varargin{1};
+     options{1} = varargin{2}; % button1
+     options{2} = varargin{3}; % button2
+     options{3} = varargin{4}; % button3
+     options{4} = varargin{5}; % default
+  otherwise
+     print_usage();
+  end
+
+
+  ret = java_invoke ('org.octave.JDialogBox', 'questdlg', question, title, options);
+
+end
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/warndlg.m	Fri Nov 23 15:29:13 2012 -0500
@@ -0,0 +1,36 @@
+## Copyright (C) 2010 Martin Hepperle
+##
+## 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/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function file} {@var{P} =} warndlg (@var{MESSAGE} [,@var{TITLE}])
+##
+## Displays the @var{MESSAGE} using a warning dialog box. 
+## The @var{TITLE} can be used optionally to decorate the dialog caption.
+##
+## @end deftypefn
+## @seealso{helpdlg, inputdlg, listdlg, questiondlg}
+
+function ret = warndlg(message,varargin)
+  
+  switch length (varargin)
+  case 0
+     title = 'Warning Dialog';
+  otherwise
+     title = varargin{1};
+  endswitch
+
+  ret = java_invoke ('org.octave.JDialogBox', 'warndlg', message, title);
+
+endfunction