changeset 15838:009984ecf419 classdef

maint: periodic merge of default to classdef
author Michael Goffioul <michael.goffioul@gmail.com>
date Sun, 23 Dec 2012 13:00:02 -0500
parents 6ea536cb7360 (current diff) fe2cefaa772b (diff)
children af9e2ad52943
files libgnu/Makefile.am libinterp/Makefile.am libinterp/octave-value/module.mk libinterp/octave-value/ov.cc libinterp/octave.cc libinterp/parse-tree/pt-eval.cc libinterp/parse-tree/pt-eval.h scripts/miscellaneous/usejava.m
diffstat 294 files changed, 33094 insertions(+), 4727 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/.gitignore	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,8 @@
+*~
+*.user
+*.o
+*.a
+Makefile*
+*.pdb
+debug/
+release/
--- a/.hgignore	Thu Nov 01 15:01:20 2012 -0400
+++ b/.hgignore	Sun Dec 23 13:00:02 2012 -0500
@@ -8,12 +8,11 @@
 
 # This directory gets created by gnulib during the build. 
 # It contains no Octave files.
-^gnulib/
+^libgnu/*
 
-# These directories mostly contain cruft during build time, but they
-# do contain some Octave code, so we gotta be a bit more careful about
+# This directory mostly contains cruft during build time, but it does
+# contain some Octave code, so we gotta be a bit more careful about
 # what we ignore here
-^libgnu/.*\.([hc]$|sin$|valgrind$|charset$|mk$)
 ^m4/(?!ax_).+\.m4$
 
 # Emacs tools create these
--- a/.hgsub	Thu Nov 01 15:01:20 2012 -0400
+++ b/.hgsub	Sun Dec 23 13:00:02 2012 -0500
@@ -1,2 +1,1 @@
 gnulib = [git]git://git.sv.gnu.org/gnulib
-libgui/qterminal = [git]https://code.google.com/p/qterminal/
--- a/.hgsubstate	Thu Nov 01 15:01:20 2012 -0400
+++ b/.hgsubstate	Sun Dec 23 13:00:02 2012 -0500
@@ -1,2 +1,1 @@
-1af55d85d9762a679b4302d5995f05ccd883e956 gnulib
-0820083f7fe95d0088971b1233540c7827218e7c libgui/qterminal
+e657573866e8aded3b3b1461c346cf9ad02a5148 gnulib
--- a/Makefile.am	Thu Nov 01 15:01:20 2012 -0400
+++ b/Makefile.am	Sun Dec 23 13:00:02 2012 -0500
@@ -43,6 +43,7 @@
   build-aux/mk-opts.pl \
   build-aux/mkinstalldirs \
   build-aux/move-if-change \
+  build-aux/OctJavaQry.class \
   etc/NEWS.1 \
   etc/NEWS.2 \
   etc/NEWS.3 \
--- a/NEWS	Thu Nov 01 15:01:20 2012 -0400
+++ b/NEWS	Sun Dec 23 13:00:02 2012 -0500
@@ -88,6 +88,18 @@
     functions.  Packages that implement extra colormaps should use these
     commands with PKG_ADD and PKG_DEL statements.
 
+ ** The m-files in the image directory have been overhauled.
+
+    The principal benefit is that Octave will now no longer automatically
+    convert images stored with integers to doubles.  Storing images as uint8
+    or uint16 requires only 1/8 or 1/4 the memory of an image stored using
+    doubles.  For certain operations, such as fft2, the image must still be
+    converted to double in order to work.
+
+    Other changes include fixes to the way indexed images are read from a
+    colormap depending on the image class (integer images have a -1 offset to
+    the colormap row number).
+
  ** The datevec function has been extended for better Matlab compatibility.
     It now accepts string inputs in the following numerical formats: 12, 21,
     22, 26, 29, 31.  This is undocumented, but verifiable, Matlab behavior.
@@ -95,15 +107,45 @@
     January 1st of the current year.  The previous default was the current day,
     month, and year.  This may produce changes in existing scripts.
 
+ ** The error function and its derivatives has been extended to accept complex
+    arguments.  The following functions now accept complex inputs:
+
+    erf  erfc  erfcx   
+
+    In addition two new error functions erfi (imaginary error function) and
+    dawson (scaled imaginary error function) have been added.
+
  ** 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 core 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
-      cmpermute    findfigs     polyeig    shrinkfaces
-      cmunique     fminsearch   splinefit
-      colorcube    iscolormap   tetramesh
+      betaincinv   dawson     fminsearch   rgbplot    
+      cmpermute    erfcinv    iscolormap   shrinkfaces
+      cmunique     erfi       lines        splinefit             
+      colorcube    findfigs   polyeig      tetramesh             
 
  ** Deprecated functions.
 
Binary file build-aux/OctJavaQry.class has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/build-aux/OctJavaQry.java	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,23 @@
+// Code used by configure script to locate Java installation variables.
+// Only compiled code, OctJavaQry.class, is distributed.
+public class OctJavaQry
+{
+  public static void main (String[] args)
+  {
+    if (args.length > 0)
+    {
+      if (args[0].equals ("JAVA_HOME"))
+      {
+        System.out.println (System.getProperty ("java.home"));
+      }
+      else if (args[0].equals ("JAVA_LDPATH"))
+      {
+        System.out.println (System.getProperty ("java.library.path"));
+      }
+      else if (args[0].equals ("JAVA_BOOTPATH"))
+      {
+        System.out.println (System.getProperty ("sun.boot.library.path"));
+      }
+    }
+  }
+}
--- a/build-aux/common.mk	Thu Nov 01 15:01:20 2012 -0400
+++ b/build-aux/common.mk	Sun Dec 23 13:00:02 2012 -0500
@@ -51,6 +51,7 @@
 RANLIB = @RANLIB@
 
 LN_S = @LN_S@
+MKDIR_P = @MKDIR_P@
 
 MAKEINFO = @MAKEINFO@
 TEXI2DVI = @TEXI2DVI@
@@ -224,6 +225,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@
@@ -576,8 +580,9 @@
   -e "s|%OCTAVE_CONF_QRUPDATE_CPPFLAGS%|\"${QRUPDATE_CPPFLAGS}\"|" \
   -e "s|%OCTAVE_CONF_QRUPDATE_LDFLAGS%|\"${QRUPDATE_LDFLAGS}\"|" \
   -e "s|%OCTAVE_CONF_QRUPDATE_LIBS%|\"${QRUPDATE_LIBS}\"|" \
-  -e "s|%OCTAVE_CONF_QT_INCDIR%|\"${QT_INCDIR}\"|" \
-  -e "s|%OCTAVE_CONF_QT_LIBDIR%|\"${QT_LIBDIR}\"|" \
+  -e "s|%OCTAVE_CONF_QT_CPPFLAGS%|\"${QT_CPPFLAGS}\"|" \
+  -e "s|%OCTAVE_CONF_QT_LDFLAGS%|\"${QT_LDFLAGS}\"|" \
+  -e "s|%OCTAVE_CONF_QT_LIBS%|\"${QT_LIBS}\"|" \
   -e "s|%OCTAVE_CONF_RANLIB%|\"${RANLIB}\"|" \
   -e "s|%OCTAVE_CONF_RDYNAMIC_FLAG%|\"${RDYNAMIC_FLAG}\"|" \
   -e "s|%OCTAVE_CONF_READLINE_LIBS%|\"${READLINE_LIBS}\"|" \
--- a/configure.ac	Thu Nov 01 15:01:20 2012 -0400
+++ b/configure.ac	Sun Dec 23 13:00:02 2012 -0500
@@ -124,6 +124,27 @@
 config_opts=$ac_configure_args
 AC_SUBST(config_opts)
 
+### Define the path to the shell on the host system.  Most systems will
+### ensure /bin/sh is the default shell so this can be safely ignored by
+### almost everyone.  However, when building for Android, for example,
+### this will need to be set.
+SHELL_PATH=/bin/sh
+AC_ARG_WITH([shell],
+  [AS_HELP_STRING([--with-shell=SHELL],
+    [use SHELL as the shell interpreter (default: /bin/sh)])])
+case $with_shell in
+  no)
+    AC_MSG_ERROR([A shell interpreter is required])
+  ;;
+  yes | "")
+  ;;
+  *)
+    SHELL_PATH=$with_shell
+  ;;
+esac
+AC_DEFINE_UNQUOTED([SHELL_PATH], ["$SHELL_PATH"],
+  [Define this to be the path to the shell command interpreter.])
+
 ### Enable bounds checking on element references within Octave's array and
 ### matrix classes.  This slows down some operations a bit, so it is turned off
 ### by default.
@@ -954,10 +975,19 @@
 
   ## Check for FreeType 2 library
 
-  AC_CHECK_FT2([9.0.3],
-    [AC_DEFINE(HAVE_FREETYPE, 1, [Define to 1 if you have FreeType library.])
-     XTRA_CXXFLAGS="$XTRA_CXXFLAGS $FT2_CFLAGS"],
-    [warn_freetype="FreeType library not found.  Native graphics will be disabled."])
+  PKG_CHECK_MODULES([FT2], [freetype2], [
+    min_ft2_version=9.03
+    AC_MSG_CHECKING([for FreeType -- version >= $min_ft2_version])
+    $PKG_CONFIG freetype2 --atleast-version=$min_ft2_version
+    ac_status=$?
+    if test $ac_status = 0; then
+      AC_MSG_RESULT(yes)
+      AC_DEFINE(HAVE_FREETYPE, 1, [Define to 1 if you have Freetype library.])
+      XTRA_CXXFLAGS="$XTRA_CXXFLAGS $FT2_CFLAGS"
+    else
+      AC_MSG_RESULT(no)
+      warn_freetype="FreeType library not found.  Native graphics will be disabled."
+    fi])
 
   if test -n "$warn_freetype"; then
     OCTAVE_CONFIGURE_WARNING([warn_freetype])
@@ -1099,7 +1129,7 @@
 XTRA_CRUFT_SH_LDFLAGS=
 if test $have_msvc = yes; then
   FLIBS="$FLIBS -lkernel32"
-  XTRA_CRUFT_SH_LDFLAGS="-Wl,-def:cruft.def"
+  XTRA_CRUFT_SH_LDFLAGS="-Wl,-def:cruft/cruft.def"
 fi
 AC_SUBST(XTRA_CRUFT_SH_LDFLAGS)
 
@@ -2076,6 +2106,7 @@
 OCTAVE_PROG_BISON
 
 AC_PROG_LN_S
+AC_PROG_MKDIR_P
 
 AC_PROG_INSTALL
 INSTALL_SCRIPT='${INSTALL}'
@@ -2102,20 +2133,6 @@
 fi
 AM_CONDITIONAL([AMCOND_BUILD_DOCS], [test -n "$DOCDIR"])
 
-### Even though we include config.h, we need to have the preprocessor
-### defines available in a variable for the testif feature of the
-### scripts/testfun/test.m function.  Use UGLY_DEFS to hold all the -D
-### options.  These are ultimately placed in the DEFS field of the
-### struct returned by octave_config_info, which is used by test.m.
-
-AC_OUTPUT_MAKE_DEFS
-
-### We have to insert extra levels of backslash quoting here so that
-### the right thing ends up in oct-conf.h.
-UGLY_DEFS=`echo $DEFS | $SED 's,\\",\\\\\\\\\\\\\\\\\\",g'`
-AC_MSG_NOTICE([defining UGLY_DEFS to be $UGLY_DEFS])
-AC_SUBST(UGLY_DEFS)
-
 ### Maybe add -Wall, -W, and -Wshadow to compiler flags now that we're
 ### done feature testing. 
 
@@ -2176,11 +2193,283 @@
 AC_SUBST(WARN_CFLAGS)
 AC_SUBST(WARN_CXXFLAGS)
 
+### Check for Java.
+
+build_java=true
+AC_ARG_ENABLE([java],
+  [AS_HELP_STRING([--disable-java],
+    [disable Java interface])],
+  [if test "$enableval" = no; then
+     build_java=false
+   fi],
+  [])
+
+AC_ARG_WITH([java-homedir],
+  [AS_HELP_STRING([--with-java-homedir=DIR],
+    [Java JDK directory in DIR])],
+  [JAVA_HOMEDIR="$withval"])
+
+AC_ARG_WITH([java-includedir],
+  [AS_HELP_STRING([--with-java-includedir=DIR],
+    [look for java include file <jni.h> in DIR])],
+  [JAVA_CPPFLAGS="$withval"], [JAVA_CPPFLAGS=""])
+
+AC_ARG_WITH([java-libdir],
+  [AS_HELP_STRING([--with-java-libdir=DIR],
+    [look for java library libjvm in DIR])],
+  [JAVA_LDPATH="$withval"], [JAVA_LDPATH=""])
+
+## Grab JAVA_HOME from environment variable if it exists
+AC_ARG_VAR([JAVA_HOME], [path to Java JDK installation])
+## But --with-java-homedir option overrides environment variable
+if test -n "$JAVA_HOMEDIR"; then
+  JAVA_HOME=$JAVA_HOMEDIR
+fi
+JAVA=
+JAVAC=
+JAR=
+JAVA_LIBS=
+
+## Fake loop so that "break" can be used to skip code blocks.
+while test $build_java = true
+do
+  ## Unset build_java.  Variable is set only if all configuration tests pass.
+  build_java=false
+
+  ## Warn if JAVA_HOME is unset.  It is *strongly* advised to specify JAVA_HOME.
+  if test -z "$JAVA_HOME"; then
+    AC_MSG_WARN([JAVA_HOME environment variable not initialized.])
+    AC_MSG_WARN([Auto-detection will proceed but is unreliable.])
+  fi
+
+  ## Search for a viable Java executable.
+  if test -z "$JAVA_HOME"; then
+    JAVA_PATH="$PATH"
+  else
+    JAVA_PATH="${JAVA_HOME}$PATH_SEPARATOR${JAVA_HOME}/jre/bin$PATH_SEPARATOR${JAVA_HOME}/bin$PATH_SEPARATOR${JAVA_HOME}/../bin$PATH_SEPARATOR${PATH}"
+  fi
+  AC_PATH_PROG(JAVA, java, [], [$JAVA_PATH])
+
+  if test -z "$JAVA"; then
+    AC_MSG_WARN([No Java executable found.  Octave will not be able to call Java methods.])   
+    break
+  fi
+
+  if test -z "$JAVA_HOME"; then
+    ## Find JAVA_HOME for JRE by running java and querying properties.
+    JAVA_TMP_HOME="`\"$JAVA\" -classpath ${srcdir}/build-aux OctJavaQry JAVA_HOME`"
+    ## Strip directory back to top-level installation dir (JAVA_HOME for JDK).
+    JAVA_HOME="`echo $JAVA_TMP_HOME | sed -e 's|[[/\\]]bin[[/\\]]\?$||' | sed -e 's|[[/\\]]jre[[/\\]]\?$||'`"
+  fi
+
+  case $canonical_host_type in
+    *-mingw* | *-msdosmsvc*)
+      ## Under Win32 platform, we want JAVA_HOME to be in MSYS format, that is without
+      ## colon and backslashes, as it is also used as path separator. Use quoted paths
+      ## as Java may be installed in a path with whitespaces (e.g. C:\Program Files\Java\...).
+      if test -n "$JAVA_HOME"; then
+        JAVA_HOME="`cd \"$JAVA_HOME\" && pwd`"
+	## Maybe this will be useful in the future, as native Java won't probably
+	## understand MSYS paths.
+	JAVA_HOME_NATIVE="`cd \"$JAVA_HOME\" && pwd -W`"
+      fi
+    ;;
+    *)
+      JAVA_HOME_NATIVE="$JAVA_HOME"
+    ;;
+  esac
+
+  ## Amend search path for JAVAC and JAR.
+  if test -z "$JAVA_HOME"; then
+    JAVA_PATH="$PATH"
+  else
+    JAVA_PATH="${JAVA_HOME}$PATH_SEPARATOR${JAVA_HOME}/bin$PATH_SEPARATOR${JAVA_HOME}/../bin$PATH_SEPARATOR${PATH}"
+  fi
+
+  AC_PATH_PROG(JAVAC, javac, [], [$JAVA_PATH])
+  AC_PATH_PROG(JAR, jar, [], [$JAVA_PATH])
+
+  if test -z "$JAVAC" || test -z "$JAR"; then
+    AC_MSG_WARN([No javac compiler or jar executable found.  Octave will not be able to call Java methods.])
+    break
+  fi
+
+  ## Check Java version is recent enough.
+  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 $java_version | sed -e 's/^\([0-9][0-9]*\)\.\([0-9][0-9]*\)\..*$/\1/'`]
+  java_minor=[`echo $java_version | sed -e 's/^\([0-9][0-9]*\)\.\([0-9][0-9]*\)\..*$/\2/'`]
+  if test $java_major -ge 1 && test $java_minor -ge 5; then
+    :  # Version is ok.  Do nothing.
+  else
+    AC_MSG_WARN([Java version is too old (< 1.5).  Octave will not be able to call Java methods.])
+    break
+  fi
+
+  ## At this point Win32/MSVC systems have enough configuration data. We assume
+  ## that all appropriate variables (e.g. INCLUDE and LIB) have already the required
+  ## paths to compile and link against JDK.
+  case $canonical_host_type in
+    *-msdosmsvc*)
+      build_java=true
+      JAVA_LIBS=-ladvapi32
+      AC_DEFINE(HAVE_JAVA, 1,
+        [Define to 1 if Java is available and is at least version 1.5])
+      break
+    ;;
+    *-mingw*)
+      if test "$have_msvc" = "yes"; then
+        build_java=true
+        JAVA_LIBS=-ladvapi32
+        AC_DEFINE(HAVE_JAVA, 1,
+          [Define to 1 if Java is available and is at least version 1.5])
+        break
+      fi
+    ;;
+  esac
+
+  ## Determine which library file name to search for.
+  case $canonical_host_type in
+    *-darwin*)
+      jvmlib=libjvm.dylib
+    ;;
+    *-mingw* | *-cygwin*)
+      jvmlib=jvm.dll
+    ;;
+    *)
+      jvmlib=libjvm.so
+    ;;
+  esac
+
+  AC_MSG_CHECKING([for $jvmlib])
+
+  if test -z "$JAVA_LDPATH"; then
+    ## Run Java to try and determine library path to libjvm.so.
+    JAVA_TMP_LDPATH=`$JAVA -classpath ${srcdir}/build-aux OctJavaQry JAVA_LDPATH`
+    JAVA_TMP_LDPATH=`echo $JAVA_TMP_LDPATH | sed -e "s/${PATH_SEPARATOR}/ /g"`
+    for dir in $JAVA_TMP_LDPATH; do
+      if test -f "$dir/$jvmlib"; then
+        JAVA_LDPATH=$dir
+        break
+      fi
+    done
+  fi
+
+  if test -z "$JAVA_LDPATH"; then
+    ## Nothing found.  Try Java again using bootpath argument. 
+    JAVA_TMP_LDPATH=`$JAVA -classpath ${srcdir}/build-aux OctJavaQry JAVA_BOOTPATH`
+    JAVA_TMP_LDPATH="${JAVA_TMP_LDPATH} ${JAVA_TMP_LDPATH}/client ${JAVA_TMP_LDPATH}/server"
+    for dir in $JAVA_TMP_LDPATH; do
+      if test -f "$dir/$jvmlib"; then
+        JAVA_LDPATH=$dir
+        break
+      fi
+    done
+  fi
+
+  if test -z "$JAVA_LDPATH"; then
+    ## Java failed to find it's own library path.  Guess wildly.
+    JAVA_TMP_LDPATH=`ls -d $JAVA_HOME/jre/lib/*/client`
+    JAVA_TMP_LDPATH="${JAVA_TMP_LDPATH} `ls -d $JAVA_HOME/jre/lib/*/server`"
+    ## Add some paths that might work on Macs.
+    JAVA_TMP_LDPATH="${JAVA_TMP_LDPATH} ${JAVA_HOME}/../Libraries ${JAVA_HOME}/Libraries"
+    ## Add some paths that might work on MinGW
+    JAVA_TMP_LDPATH="${JAVA_TMP_LDPATH} ${JAVA_HOME}/bin/client ${JAVA_HOME}/bin/server"
+    for dir in $JAVA_TMP_LDPATH; do
+      if test -f "$dir/$jvmlib"; then
+        JAVA_LDPATH=$dir
+        break
+      fi
+    done
+  fi
+
+  ## Verify value passed in option --with-java-libdir
+  if test -n "$JAVA_LDPATH"; then
+    if test -f "${JAVA_LDPATH}/$jvmlib"; then
+      :  # libjvm found
+    else
+      JAVA_LDPATH=""
+    fi 
+  fi
+
+  if test -z "$JAVA_LDPATH"; then
+    AC_MSG_RESULT([not found])
+    AC_MSG_WARN([Library $jvmlib not found.  Octave will not be able to call Java methods.])
+    break
+  else
+    AC_MSG_RESULT([$JAVA_LDPATH])
+  fi
+
+  AC_MSG_CHECKING([for include file <jni.h>])
+
+  ## Java and JVM found.  Set up flags.
+  case $canonical_host_type in
+    *-darwin*)
+      ## Sneak the -framework flag into mkoctfile via LFLAGS
+      LFLAGS="$LFLAGS -framework JavaVM"
+      ## According to: http://developer.apple.com/unix/crossplatform.html
+      ## one must explicitly set the include path.
+      ## Unfortunately, the include path keeps moving around.
+      if test -n "$JAVA_CPPFLAGS"; then
+        JAVA_CPPFLAGS="-I${JAVA_CPPFLAGS}"
+      else
+        JAVA_CPPFLAGS="-I${JAVA_HOME}/include -I/System/Library/Frameworks/JavaVM.framework/Home/include -I/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Headers -I/System/Library/Frameworks/JavaVM.framework/Versions/Current/Headers"
+      fi
+      JAVA_LIBS="-framework JavaVM"
+    ;;
+    *-mingw* | *-cygwin*)
+      if test -n "$JAVA_CPPFLAGS"; then
+        JAVA_CPPFLAGS="-I${JAVA_CPPFLAGS}/include -I${JAVA_CPPFLAGS}/include/win32"
+      else
+        JAVA_CPPFLAGS="-I${JAVA_HOME}/include -I${JAVA_HOME}/include/win32"
+      fi
+      JAVA_LIBS=-ladvapi32
+    ;;
+    *)
+      if test -n "$JAVA_CPPFLAGS"; then
+        JAVA_CPPFLAGS="-I${JAVA_CPPFLAGS}/include -I${JAVA_CPPFLAGS}/include/linux"
+      else
+        JAVA_CPPFLAGS="-I${JAVA_HOME}/include -I${JAVA_HOME}/include/linux"
+      fi
+    ;;
+  esac
+
+  ## Verify jni.h include file exists.
+	JNI_PATH=`echo $JAVA_CPPFLAGS | sed -e 's/-I//g'`
+  have_jni=false
+	for dir in $JNI_PATH; do 
+	  if test -f "${dir}/jni.h"; then have_jni=true; break; fi
+	done
+  if test $have_jni = true; then
+    AC_MSG_RESULT([$dir])
+  else
+    AC_MSG_RESULT([not found])
+    AC_MSG_WARN([Include file <jni.h> not found.  Octave will not be able to call Java methods.])
+    break
+  fi
+
+  ## Passed all configuration tests.  A workable Java installation was found.
+  build_java=true
+  AC_DEFINE(HAVE_JAVA, 1,
+    [Define to 1 if Java is available and is at least version 1.5])
+  break
+done
+
+AM_CONDITIONAL([AMCOND_HAVE_JAVA], [test $build_java = true])
+AC_SUBST(JAVA)
+AC_SUBST(JAVAC)
+AC_SUBST(JAR)
+AC_SUBST(JAVA_CPPFLAGS)
+AC_SUBST(JAVA_LIBS)
+AC_DEFINE_UNQUOTED([JAVA_HOME], ["$JAVA_HOME"], [Java home (top-level installation dir)])
+AC_DEFINE_UNQUOTED([JAVA_LDPATH], ["$JAVA_LDPATH"], [Java library path (libjvm)])
+
 ### GUI/Qt related tests.
 
-HAVE_QT=false
-QT_INCDIR=
-QT_LIBDIR=
+QT_CPPFLAGS=
+QT_LDFLAGS=
+QT_LIBS=
 win32_terminal=no
 build_gui=true
 GUIDIR=libgui
@@ -2194,17 +2483,14 @@
     [],
     [AC_MSG_ERROR([Qt libraries are required to build the GUI])])
 
-  ## Check for Qt utility programs
-  AC_CHECK_PROGS(QMAKE, [qmake-qt5 qmake-qt4 qmake])
-  if test -z "$QMAKE"; then
-    AC_MSG_ERROR([qmake is required to build the GUI])
-  fi
-
-  QT_INCDIR=`$QMAKE -query QT_INSTALL_HEADERS | sed -e 's,\\\\,/,g'`
-  QT_LIBDIR=`$QMAKE -query QT_INSTALL_LIBS | sed -e 's,\\\\,/,g'`
-
-  if test "$QT_INCDIR" = "**Unknown**"; then
-    AC_MSG_ERROR([qmake >= Qt4 is required to build the GUI])
+  ## Retrieve Qt compilation and linker flags
+  QT_CPPFLAGS="`$PKG_CONFIG --cflags-only-I QtCore QtGui QtNetwork`"
+  QT_LDFLAGS="`$PKG_CONFIG --libs-only-L QtCore QtGui QtNetwork`"
+  QT_LIBS="`$PKG_CONFIG --libs-only-l QtCore QtGui QtNetwork`"
+
+  ## Check for Qt4
+  if ! `$PKG_CONFIG --atleast-version=4.0.0 QtCore`; then
+    AC_MSG_ERROR([Qt >= 4.0.0 is required to build the GUI])
   fi
 
   AC_CHECK_PROGS(MOC, [moc-qt5 moc-qt4 moc])
@@ -2214,9 +2500,8 @@
     AC_MSG_ERROR([Qt utility programs moc, uic, and rcc are required to build the GUI])
   fi 
 
-  HAVE_QT=true
   AC_DEFINE(HAVE_QT, 1, 
-    [Define to 1 if Qt is available (libraries, developer header files, utility programs (qmake, moc, uic, and rcc))])
+    [Define to 1 if Qt is available (libraries, developer header files, utility programs (moc, uic, and rcc))])
 
   ## Check for Qscintilla library which is used in the GUI editor. 
   AC_CACHE_CHECK([whether Qscintilla library is installed],
@@ -2224,9 +2509,9 @@
     [save_CPPFLAGS="$CPPFLAGS"
     save_LDFLAGS="$LDFLAGS"
     save_LIBS="$LIBS"
-    CPPFLAGS="-I$QT_INCDIR -I$QT_INCDIR/Qt $CPPFLAGS"
-    LDFLAGS="-L$QT_LIBDIR $LDFLAGS"
-    LIBS="-lqscintilla2"
+    CPPFLAGS="$QT_CPPFLAGS $CPPFLAGS"
+    LDFLAGS="$QT_LDFLAGS $LDFLAGS"
+    LIBS="$QT_LIBS -lqscintilla2"
     AC_LANG_PUSH(C++)
     AC_LINK_IFELSE([AC_LANG_PROGRAM([[
       #include <Qsci/qscilexersql.h>
@@ -2243,6 +2528,9 @@
   if test $octave_cv_lib_qscintilla = no; then
     AC_MSG_ERROR([Qscintilla library is required to build the GUI])
   fi
+  ## Let's assume Qscintilla library is at the same location as
+  ## other regular Qt libraries.
+  QT_LIBS="$QT_LIBS -lqscintilla2"
 
   ## Check for Qt functions which have changed their API over time
   OCTAVE_CHECK_FUNC_FINDFIRST_MODERN
@@ -2271,8 +2559,9 @@
 fi
 AM_CONDITIONAL([AMCOND_BUILD_GUI], [test $build_gui = true])
 AM_CONDITIONAL([WIN32_TERMINAL], [test $win32_terminal = yes])
-AC_SUBST(QT_INCDIR)
-AC_SUBST(QT_LIBDIR)
+AC_SUBST(QT_CPPFLAGS)
+AC_SUBST(QT_LDFLAGS)
+AC_SUBST(QT_LIBS)
 AC_SUBST(GUIDIR)
 
 ### Run configure in subdirectories.
@@ -2448,6 +2737,21 @@
 dnl end of AH_BOTTOM
 dnl ------------------------------------------------------------
 
+### Make all AC_DEFINES available to testif feature of test.m function.
+### This must reside at the bottom of configure.ac after all AC_DEFINES
+### have been made.
+### Use UGLY_DEFS to hold all the -D options.  These are ultimately placed
+### in the DEFS field of the struct returned by octave_config_info, which
+### is used by test.m.
+
+AC_OUTPUT_MAKE_DEFS
+
+## We have to insert extra levels of backslash quoting here so that
+## the right thing ends up in oct-conf.h.
+UGLY_DEFS=`echo $DEFS | $SED 's,\\",\\\\\\\\\\\\\\\\\\",g'`
+AC_MSG_NOTICE([defining UGLY_DEFS to be $UGLY_DEFS])
+AC_SUBST(UGLY_DEFS)
+
 ### Do the substitutions in all the Makefiles.
 
 AC_SUBST(ac_config_files)
@@ -2533,6 +2837,10 @@
   HDF5 CPPFLAGS:               $HDF5_CPPFLAGS
   HDF5 LDFLAGS:                $HDF5_LDFLAGS
   HDF5 libraries:              $HDF5_LIBS
+  Java home:                   $JAVA_HOME
+  Java JVM path:               $JAVA_LDPATH
+  Java CPPFLAGS:               $JAVA_CPPFLAGS
+  Java libraries:              $JAVA_LIBS
   LAPACK libraries:            $LAPACK_LIBS
   LLVM CPPFLAGS:               $LLVM_CPPFLAGS
   LLVM LDFLAGS:                $LLVM_LDFLAGS
@@ -2549,8 +2857,9 @@
   QRUPDATE CPPFLAGS:           $QRUPDATE_CPPFLAGS
   QRUPDATE LDFLAGS:            $QRUPDATE_LDFLAGS
   QRUPDATE libraries:          $QRUPDATE_LIBS
-  Qt headers:                  $QT_INCDIR
-  Qt libraries:                $QT_LIBDIR
+  Qt CPPFLAGS:                 $QT_CPPFLAGS
+  Qt LDFLAGS:                  $QT_LDFLAGS
+  Qt libraries:                $QT_LIBS
   READLINE libraries:          $READLINE_LIBS
   REGEX libraries:             $REGEX_LIBS
   TERM libraries:              $TERM_LIBS
@@ -2568,6 +2877,7 @@
 
   Build Octave GUI:                   $build_gui
   JIT compiler for loops:             $build_jit
+  Build Java interface:               $build_java
   Do internal array bounds checking:  $BOUNDS_CHECKING
   Use octave_allocator:               $USE_OCTAVE_ALLOCATOR
   Build static libraries:             $STATIC_LIBS
--- a/doc/interpreter/Makefile.am	Thu Nov 01 15:01:20 2012 -0400
+++ b/doc/interpreter/Makefile.am	Sun Dec 23 13:00:02 2012 -0500
@@ -83,12 +83,30 @@
 $(srcdir)/images.mk: $(srcdir)/config-images.sh $(srcdir)/images.awk $(srcdir)/images
 	$(srcdir)/config-images.sh $(top_srcdir)
 
-IMAGES = \
+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
+
+BUILT_IMAGES = \
   $(IMAGES_EPS) \
   $(IMAGES_PDF) \
   $(IMAGES_PNG) \
   $(IMAGES_TXT)
 
+IMAGES = \
+  $(BUILT_IMAGES) \
+  $(JAVA_IMAGES)
+
+## FIXME: JAVA_IMAGES will eventually need to be added to the HTML build.
+##        It will require a different Makefile rule later because 
+##        JAVA_IMAGES live in a subdir rather than in the current directory.
 HTMLDIR_IMAGES = $(addprefix octave.html/, $(IMAGES_PNG))
 
 LOGOS = \
@@ -123,6 +141,7 @@
   interp.texi \
   intro.texi \
   io.texi \
+  java.texi \
   linalg.texi \
   matrix.texi \
   nonlin.texi \
@@ -270,7 +289,7 @@
 clean-local:
 	rm -rf t2d_cache
 
-DISTCLEANFILES = $(BUILT_TEXINFOS) doc-cache
+DISTCLEANFILES = $(BUILT_TEXINFOS)
 
-MAINTAINERCLEANFILES = $(IMAGES)
+MAINTAINERCLEANFILES = $(BUILT_IMAGES) doc-cache
 
--- a/doc/interpreter/arith.txi	Thu Nov 01 15:01:20 2012 -0400
+++ b/doc/interpreter/arith.txi	Sun Dec 23 13:00:02 2012 -0500
@@ -285,12 +285,16 @@
 
 @DOCSTRING(duplication_matrix)
 
+@DOCSTRING(dawson)
+
 @DOCSTRING(erf)
 
 @DOCSTRING(erfc)
 
 @DOCSTRING(erfcx)
 
+@DOCSTRING(erfi)
+
 @DOCSTRING(erfinv)
 
 @DOCSTRING(erfcinv)
--- a/doc/interpreter/basics.txi	Thu Nov 01 15:01:20 2012 -0400
+++ b/doc/interpreter/basics.txi	Sun Dec 23 13:00:02 2012 -0500
@@ -261,6 +261,12 @@
 @end group
 @end example
 
+@noindent
+Note that this does not enable the @code{Octave:matlab-incompatible}
+warning, which you might want if you want to be told about writing code
+that works in Octave but not Matlab (@pxref{doc-warning},
+@pxref{doc-warning_ids}).
+
 @item  --verbose
 @itemx -V
 @cindex @code{--verbose}
--- a/doc/interpreter/container.txi	Thu Nov 01 15:01:20 2012 -0400
+++ b/doc/interpreter/container.txi	Sun Dec 23 13:00:02 2012 -0500
@@ -38,9 +38,9 @@
 @cindex structures
 @cindex data structures
 
-Octave includes support for organizing data in structures.  The current
+Octave includes support for organizing data in structures. The current
 implementation uses an associative array with indices limited to
-strings, but the syntax is more like C-style structures.  
+strings, but the syntax is more like C-style structures.
 
 @menu
 * Basic Usage and Examples::
@@ -390,6 +390,28 @@
 @end group
 @end example
 
+@noindent
+Dynamic indexing also allows you to use arbitrary strings, not merely
+valid Octave identifiers (note that this does not work on @sc{Matlab}):
+
+@example
+@group
+a = "long field with spaces (and funny char$)";
+x.a = 1;
+x.(a) = 2;
+x
+     @result{} x =
+        @{
+          a =  1
+          long field with spaces (and funny char$) =  2
+        @}
+@end group
+@end example
+
+@noindent
+The warning id @code{Octave:matlab-incompatible} can be enabled to warn
+about this usage. @xref{doc-warning_ids}.
+
 More realistically, all of the functions that operate on strings can be used
 to build the correct field name before it is entered into the data structure.
 
@@ -471,7 +493,7 @@
           field2 =  2
         @}
 @end group
- @end example       
+@end example
 
 @DOCSTRING(struct)
 
@@ -491,9 +513,9 @@
 
 @DOCSTRING(isfield)
 
-@DOCSTRING(getfield)
+@DOCSTRING(setfield)
 
-@DOCSTRING(setfield)
+@DOCSTRING(getfield)
 
 @DOCSTRING(rmfield)
 
--- a/doc/interpreter/contributors.in	Thu Nov 01 15:01:20 2012 -0400
+++ b/doc/interpreter/contributors.in	Sun Dec 23 13:00:02 2012 -0500
@@ -93,6 +93,7 @@
 Daniel Heiserer
 Martin Helm
 Stefan Hepp
+Martin Hepperle
 Jordi Gutiérrez Hermoso
 Yozo Hida
 Ryan Hinton
@@ -169,6 +170,7 @@
 Alexander Mamonov
 Christoph Mayer
 Júlio Hoffimann Mendes
+Ronald van der Meer
 Thorsten Meyer
 Petr Mikulik
 Mike Miller
--- a/doc/interpreter/dynamic.txi	Thu Nov 01 15:01:20 2012 -0400
+++ b/doc/interpreter/dynamic.txi	Sun Dec 23 13:00:02 2012 -0500
@@ -1119,7 +1119,7 @@
 allocate any memory that is needed by the foreign code, with either the
 @nospell{fortran_vec} method or the @w{@code{OCTAVE_LOCAL_BUFFER}} macro.
 
-The Octave unwind_protect mechanism (@ref{The @code{unwind_protect} Statement})
+The Octave unwind_protect mechanism (@ref{The unwind_protect Statement})
 can also be used in oct-files.  In conjunction with the exception
 handling of Octave, it is important to enforce that certain code is run
 to allow variables, etc. to be restored even if an exception occurs.  An
--- a/doc/interpreter/errors.txi	Thu Nov 01 15:01:20 2012 -0400
+++ b/doc/interpreter/errors.txi	Sun Dec 23 13:00:02 2012 -0500
@@ -44,7 +44,7 @@
 Since an error can occur during the evaluation of a program, it is
 very convenient to be able to detect that an error occurred, so that
 the error can be fixed.  This is possible with the @code{try} statement
-described in @ref{The @code{try} Statement}.
+described in @ref{The try Statement}.
 
 @menu
 * Raising Errors::
@@ -136,7 +136,7 @@
 @subsection Catching Errors
 
 When an error occurs, it can be detected and handled using the
-@code{try} statement as described in @ref{The @code{try} Statement}.
+@code{try} statement as described in @ref{The try Statement}.
 As an example, the following piece of code counts the number of errors
 that occurs during a @code{for} loop.
 
@@ -180,6 +180,39 @@
 
 @DOCSTRING(lasterr)
 
+It is also possible to assign an identification string to an error.
+If an error has such an ID the user can catch this error
+as will be shown in the next example.  To assign an ID to an error,
+simply call @code{error} with two string arguments, where the first
+is the identification string, and the second is the actual error.  Note
+that error IDs are in the format "NAMESPACE:ERROR-NAME".  The namespace
+"Octave" is used for Octave's own errors.  Any other string is available
+as a namespace for user's own errors.
+
+The next example counts indexing errors. The errors are catched using the
+field identifier of the structure returned by the function @code{lasterror}.
+
+@example
+@group
+number_of_errors = 0;
+for n = 1:100
+  try
+    @dots{}
+  catch
+    id = lasterror.identifier;
+    if (strcmp (id, "Octave:invalid-indexing"))
+      number_of_errors++;
+    endif
+  end_try_catch
+endfor
+@end group
+@end example
+
+The functions distributed with Octave can issue one of the following
+errors.
+
+@DOCSTRING(error_ids)
+
 When an error has been handled it is possible to raise it again.  This
 can be useful when an error needs to be detected, but the program should
 still abort.  This is possible using the @code{rethrow} function.  The
@@ -305,6 +338,11 @@
 
 @DOCSTRING(lastwarn)
 
+The functions distributed with Octave can issue one of the following
+warnings.
+
+@DOCSTRING(warning_ids)
+
 @node Enabling and Disabling Warnings
 @subsection Enabling and Disabling Warnings
 
@@ -334,9 +372,4 @@
 @end group
 @end example
 
-The functions distributed with Octave can issue one of the following
-warnings.
 
-@DOCSTRING(warning_ids)
-
-
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	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,1156 @@
+@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 Java Interface is designed for calling Java functions from within Octave.
+If you want to do the reverse, and call Octave from within Java, try
+a library like 
+@code{javaOctave} (@url{http://kenai.com/projects/javaOctave}) or
+@code{joPas} (@url{http://jopas.sourceforge.net}). 
+
+@menu
+* Java Interface Functions::         
+* Dialog Box Functions::         
+* FAQ - Frequently asked Questions::  
+@end menu
+
+@node Java Interface Functions
+@section Java Interface Functions
+
+The following functions are the core of the Java Interface.  They provide
+a way to create a Java object, get and set its data fields, and call Java
+methods which return results to Octave. 
+
+@cindex object, creating a Java object
+@DOCSTRING(javaObject)
+
+@cindex fields, displaying available fields of a Java object
+FIXME: Need documentation on how fieldnames() is overloaded to return
+the methods of a Java object.
+
+@cindex field, returning value of Java object field
+FIXME: Need documentation on how to use structure-like indexing
+to get fields from Java object.
+
+@cindex field, setting value of Java object field
+FIXME: Need documentation on how to use structure-like indexing
+to set fields from Java object.
+
+@DOCSTRING(isjava)
+
+@cindex array, creating a Java array
+@DOCSTRING(javaArray)
+
+@cindex method, invoking a method of a Java object
+@DOCSTRING(javaMethod)
+
+@cindex methods, displaying available methods of a Java object
+FIXME: Need documentation on how methods() is overloaded to return
+the methods of a Java object.
+
+The following three functions are used to display and modify the
+class path used by the Java Virtual Machine.  This is entirely separate
+from Octave's PATH variable and is used by the JVM to find the correct
+code to execute.
+
+@cindex classpath, displaying
+@cindex classpath, dynamic
+@cindex dynamic classpath
+@cindex classpath, static
+@cindex static classpath
+@DOCSTRING(javaclasspath)
+
+@findex javaaddpath
+@cindex classpath, adding new path
+@cindex path, adding to classpath
+@cindex classpath, dynamic
+@cindex dynamic classpath, adding new path
+@DOCSTRING(javaaddpath)
+
+@cindex classpath, removing path
+@cindex path, removing from classpath
+@DOCSTRING(javarmpath)
+
+The following four functions provide information and control over the interface
+between Octave and the Java Virtual Machine.
+
+@DOCSTRING(usejava)
+
+@cindex memory, displaying Java memory status
+@DOCSTRING(javamem)
+
+@DOCSTRING(java_matrix_autoconversion)
+
+@DOCSTRING(java_unsigned_autoconversion)
+
+@DOCSTRING(debug_java)
+
+@node Dialog Box Functions
+@section Dialog Box Functions
+
+The following functions all use the Java Interface to provide some form
+of dialog box.
+
+@cindex dialog, displaying a warning dialog
+@DOCSTRING(msgbox)
+
+@cindex dialog, displaying an error dialog
+@DOCSTRING(errordlg)
+
+@cindex dialog, displaying a help dialog
+@DOCSTRING(helpdlg)
+
+@cindex dialog, displaying an input dialog
+@DOCSTRING(inputdlg)
+
+@cindex dialog, displaying a list dialog
+@DOCSTRING(listdlg)
+
+@cindex dialog, displaying a question dialog
+@DOCSTRING(questdlg)
+
+@cindex dialog, displaying a warning dialog
+@DOCSTRING(warndlg)
+
+@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 @sc{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
+@group
+%% 
+%% 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 group
+@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 @file{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
+@sc{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 @file{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 @file{classpath.txt} are:
+
+@itemize
+@item First, Octave searches for the file @file{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 @file{classpath.txt} in the package
+installation directory.  This is where @file{javaclasspath.m} resides, usually
+something like @file{@dots{}\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 @file{.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 @file{octave}
+to Octave's search path and the archive @file{myclasses.jar} in this directory
+to the Java search path. 
+
+@example
+@group
+% content of .octaverc:
+addpath('~/octave');
+javaaddpath('~/octave/myclasses.jar');
+@end group
+@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 @sc{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 @sc{matlab}
+environment.
+
+Example 1, suitable for Octave but not for @sc{matlab}: 
+
+@example
+   Passenger = java_new('package.FirstClass', row, seat);
+@end example
+
+Example 2, which works in Octave as well as in @sc{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 @sc{matlab}, you can specify options for the creation
+of the JVM inside a file named @file{java.opts}.  This is a text file where you
+can enter lines containing @option{-X} and @option{-D} options handed to the
+JVM during initialization. 
+
+In Octave, the Java options file must be located in the directory where
+@file{javaclasspath.m} resides, i.e., the package installation directory,
+usually something like @file{@dots{}\share\Octave\packages\java-1.2.8}.  You can
+find this directory by executing 
+
+@example
+pkg list
+@end example
+
+In @sc{matlab}, the options file goes into the @file{MATLABROOT/bin/ARCH}
+directory or in your personal @sc{matlab} startup directory (can be determined
+by a @samp{pwd} command).  @var{MATLABROOT} is the @sc{matlab} root directory
+and @var{ARCH} is your system architecture, which you find by issuing the
+commands @samp{matlabroot} respectively @samp{computer('arch')}.
+
+The @option{-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
+@file{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 @file{java.opts} file starts the JVM with 64
+Megabytes of initial memory: 
+
+@example
+-Xms64m 
+@end example
+
+For more details on the available @option{-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 @option{-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
+@group
+octave> javaMethod('java.lang.System', 'getProperty', 'MyProperty');
+ans = 12.34
+@end group
+@end example
+
+@seealso{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
+@group
+octave> pkg list
+Package Name  | Version | Installation directory
+--------------+---------+-----------------------
+        java *|   1.2.8 | /home/octavio/octave/java-1.2.8
+octave> 
+@end group
+@end example
+
+@noindent
+If the @var{java} package appears in the list you must uninstall it first by
+issuing the command 
+
+@example
+@group
+octave> pkg uninstall java
+octave> pkg list
+@end group
+@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
+@w{@env{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 @w{@env{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 @file{z:} drive the
+command would be: 
+
+@example
+Octave> pkg install -verbose z:/java-1.2.8.tar.gz
+@end example
+
+@noindent
+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 @option{-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
+@group
+octave> pkg list
+Package Name  | Version | Installation directory
+--------------+---------+-----------------------
+        java *|   1.2.8 | /home/octavio/octave/java-1.2.8
+octave> 
+@end group
+@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
+@group
+octave> s = javaObject('java.lang.String', 'Hello OctaveString') 
+s = Hello OctaveString 
+@end group
+@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
+@group
+octave> v = javaObject('java.util.Vector') 
+v = 
+<Java object: java.util.Vector> 
+octave> v.add(12); 
+octave> v.get(0) 
+ans = 12 
+@end group
+@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
+@group
+% 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 group
+@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{errordlg, helpdlg, inputdlg, listdlg, msgbox, questdlg, 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	Thu Nov 01 15:01:20 2012 -0400
+++ b/doc/interpreter/octave.texi	Sun Dec 23 13:00:02 2012 -0500
@@ -177,6 +177,7 @@
 * Object Oriented Programming::            
 * GUI Development::            
 * System Utilities::            
+* Java Interface:: 
 * Packages:: 
 * Dynamically Linked Functions::
 * Test and Demo Functions::
@@ -366,15 +367,15 @@
 
 Statements
 
-* The @code{if} Statement::            
-* The @code{switch} Statement::        
-* The @code{while} Statement::         
-* The @code{do-until} Statement::      
-* The @code{for} Statement::           
-* The @code{break} Statement::         
-* The @code{continue} Statement::      
-* The @code{unwind_protect} Statement::  
-* The @code{try} Statement::           
+* The if Statement::            
+* The switch Statement::        
+* The while Statement::         
+* The do-until Statement::      
+* The for Statement::           
+* The break Statement::         
+* The continue Statement::      
+* The unwind_protect Statement::  
+* The try Statement::           
 * Continuation Lines::          
 
 The @code{switch} Statement
@@ -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
--- a/doc/interpreter/stmt.txi	Thu Nov 01 15:01:20 2012 -0400
+++ b/doc/interpreter/stmt.txi	Sun Dec 23 13:00:02 2012 -0500
@@ -46,20 +46,20 @@
 @dfn{body} of a control statement.
 
 @menu
-* The @code{if} Statement::            
-* The @code{switch} Statement::        
-* The @code{while} Statement::         
-* The @code{do-until} Statement::      
-* The @code{for} Statement::           
-* The @code{break} Statement::         
-* The @code{continue} Statement::      
-* The @code{unwind_protect} Statement::  
-* The @code{try} Statement::           
+* The if Statement::            
+* The switch Statement::        
+* The while Statement::         
+* The do-until Statement::      
+* The for Statement::           
+* The break Statement::         
+* The continue Statement::      
+* The unwind_protect Statement::  
+* The try Statement::           
 * Continuation Lines::          
 @end menu
 
-@node The @code{if} Statement
-@section The @code{if} Statement
+@node The if Statement
+@section The if Statement
 @cindex @code{if} statement
 @cindex @code{else} statement
 @cindex @code{elseif} statement
@@ -207,8 +207,8 @@
 using the indentation to show how Octave groups the statements.
 @xref{Functions and Scripts}.
 
-@node The @code{switch} Statement
-@section The @code{switch} Statement
+@node The switch Statement
+@section The switch Statement
 @cindex @code{switch} statement
 @cindex @code{case} statement
 @cindex @code{otherwise} statement
@@ -385,8 +385,8 @@
 
 @end itemize
 
-@node The @code{while} Statement
-@section The @code{while} Statement
+@node The while Statement
+@section The while Statement
 @cindex @code{while} statement
 @cindex @code{endwhile} statement
 @cindex loop
@@ -454,8 +454,8 @@
 body; but using one makes the program clearer unless the body is very
 simple.
 
-@node The @code{do-until} Statement
-@section The @code{do-until} Statement
+@node The do-until Statement
+@section The do-until Statement
 @cindex @code{do-until} statement
 
 The @code{do-until} statement is similar to the @code{while} statement,
@@ -501,8 +501,8 @@
 body; but using one makes the program clearer unless the body is very
 simple.
 
-@node The @code{for} Statement
-@section The @code{for} Statement
+@node The for Statement
+@section The for Statement
 @cindex @code{for} statement
 @cindex @code{endfor} statement
 
@@ -658,8 +658,8 @@
 structure elements when the names of the elements do not need to be
 known.
 
-@node The @code{break} Statement
-@section The @code{break} Statement
+@node The break Statement
+@section The break Statement
 @cindex @code{break} statement
 
 The @code{break} statement jumps out of the innermost @code{for} or
@@ -713,8 +713,8 @@
 @end group
 @end example
 
-@node The @code{continue} Statement
-@section The @code{continue} Statement
+@node The continue Statement
+@section The continue Statement
 @cindex @code{continue} statement
 
 The @code{continue} statement, like @code{break}, is used only inside
@@ -762,8 +762,8 @@
 @end group
 @end example
 
-@node The @code{unwind_protect} Statement
-@section The @code{unwind_protect} Statement
+@node The unwind_protect Statement
+@section The unwind_protect Statement
 @cindex @code{unwind_protect} statement
 @cindex @code{unwind_protect_cleanup}
 @cindex @code{end_unwind_protect}
@@ -813,8 +813,8 @@
 point of the error and the statement to restore the value would not be
 executed.
 
-@node The @code{try} Statement
-@section The @code{try} Statement
+@node The try Statement
+@section The try Statement
 @cindex @code{try} statement
 @cindex @code{catch}
 @cindex @code{end_try_catch}
--- a/doc/interpreter/system.txi	Thu Nov 01 15:01:20 2012 -0400
+++ b/doc/interpreter/system.txi	Sun Dec 23 13:00:02 2012 -0500
@@ -521,8 +521,6 @@
 
 @DOCSTRING(octave_config_info)
 
-@DOCSTRING(usejava)
-
 @DOCSTRING(getrusage)
 
 @node Hashing Functions
--- a/doc/interpreter/vectorize.txi	Thu Nov 01 15:01:20 2012 -0400
+++ b/doc/interpreter/vectorize.txi	Sun Dec 23 13:00:02 2012 -0500
@@ -635,7 +635,7 @@
 
 If you are using @code{eval} merely as an exception handling mechanism, and not
 because you need to execute some arbitrary text, use the @code{try}
-statement instead.  @xref{The @code{try} Statement}.
+statement instead.  @xref{The try Statement}.
 
 @item Use @code{ignore_function_time_stamp} when appropriate.
 If you are calling lots of functions, and none of them will need to change
--- a/libgnu/Makefile.am	Thu Nov 01 15:01:20 2012 -0400
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,3131 +0,0 @@
-## DO NOT EDIT! GENERATED AUTOMATICALLY!
-## Process this file with automake to produce Makefile.in.
-# Copyright (C) 2002-2012 Free Software Foundation, Inc.
-#
-# This file is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 3 of the License, or
-# (at your option) any later version.
-#
-# This file 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 file.  If not, see <http://www.gnu.org/licenses/>.
-#
-# As a special exception to the GNU General Public License,
-# this file may be distributed as part of a program that
-# contains a configuration script generated by Autoconf, under
-# the same distribution terms as the rest of that program.
-#
-# Generated by gnulib-tool.
-# Reproduce by: gnulib-tool --import --dir=. --local-dir=gl --lib=libgnu --source-base=libgnu --m4-base=m4 --doc-base=doc --tests-base=tests --aux-dir=build-aux --no-conditional-dependencies --libtool --macro-prefix=gl base64 canonicalize chdir close closedir copysign copysignf crypto/md5 dup2 fclose fcntl fflush filemode float floor floorf fnmatch fopen fseek ftell getcwd gethostname getopt-gnu gettimeofday glob isatty link lstat malloc-gnu mkdir mkfifo mkostemp mktime nanosleep nproc open opendir pathmax progname putenv readdir readlink realloc-gnu rename rmdir round roundf select sigaction signal sigprocmask sleep stat stddef stdint stdio strerror strftime strptime symlink sys_stat sys_time sys_times time times tmpfile trunc truncf unistd unlink vasprintf
-
-AUTOMAKE_OPTIONS = 1.5 gnits
-
-SUBDIRS =
-noinst_HEADERS =
-noinst_LIBRARIES =
-noinst_LTLIBRARIES =
-EXTRA_DIST =
-BUILT_SOURCES =
-SUFFIXES =
-MOSTLYCLEANFILES = core *.stackdump
-MOSTLYCLEANDIRS =
-CLEANFILES =
-DISTCLEANFILES =
-MAINTAINERCLEANFILES =
-
-AM_CPPFLAGS =
-AM_CFLAGS =
-
-noinst_LTLIBRARIES += libgnu.la
-
-libgnu_la_SOURCES =
-libgnu_la_LIBADD = $(gl_LTLIBOBJS)
-libgnu_la_DEPENDENCIES = $(gl_LTLIBOBJS)
-EXTRA_libgnu_la_SOURCES =
-libgnu_la_LDFLAGS = $(AM_LDFLAGS)
-libgnu_la_LDFLAGS += -no-undefined
-libgnu_la_LDFLAGS += $(COPYSIGNF_LIBM)
-libgnu_la_LDFLAGS += $(COPYSIGN_LIBM)
-libgnu_la_LDFLAGS += $(FLOORF_LIBM)
-libgnu_la_LDFLAGS += $(FLOOR_LIBM)
-libgnu_la_LDFLAGS += $(GETHOSTNAME_LIB)
-libgnu_la_LDFLAGS += $(LIBSOCKET)
-libgnu_la_LDFLAGS += $(LIB_NANOSLEEP)
-libgnu_la_LDFLAGS += $(LIB_SELECT)
-libgnu_la_LDFLAGS += $(LTLIBINTL)
-libgnu_la_LDFLAGS += $(ROUNDF_LIBM)
-libgnu_la_LDFLAGS += $(ROUND_LIBM)
-libgnu_la_LDFLAGS += $(TRUNCF_LIBM)
-libgnu_la_LDFLAGS += $(TRUNC_LIBM)
-
-## begin gnulib module alloca
-
-
-libgnu_la_LIBADD += @LTALLOCA@
-libgnu_la_DEPENDENCIES += @LTALLOCA@
-EXTRA_DIST += alloca.c
-
-EXTRA_libgnu_la_SOURCES += alloca.c
-
-## end   gnulib module alloca
-
-## begin gnulib module alloca-opt
-
-BUILT_SOURCES += $(ALLOCA_H)
-
-# We need the following in order to create <alloca.h> when the system
-# doesn't have one that works with the given compiler.
-if GL_GENERATE_ALLOCA_H
-alloca.h: alloca.in.h $(top_builddir)/config.status
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
-	  cat $(srcdir)/alloca.in.h; \
-	} > $@-t && \
-	mv -f $@-t $@
-else
-alloca.h: $(top_builddir)/config.status
-	rm -f $@
-endif
-MOSTLYCLEANFILES += alloca.h alloca.h-t
-
-EXTRA_DIST += alloca.in.h
-
-## end   gnulib module alloca-opt
-
-## begin gnulib module areadlink-with-size
-
-libgnu_la_SOURCES += areadlink-with-size.c
-
-EXTRA_DIST += areadlink.h
-
-## end   gnulib module areadlink-with-size
-
-## begin gnulib module at-internal
-
-
-EXTRA_DIST += openat-priv.h openat-proc.c
-
-EXTRA_libgnu_la_SOURCES += openat-proc.c
-
-## end   gnulib module at-internal
-
-## begin gnulib module base64
-
-libgnu_la_SOURCES += base64.h base64.c
-
-## end   gnulib module base64
-
-## begin gnulib module bitrotate
-
-libgnu_la_SOURCES += bitrotate.h
-
-## end   gnulib module bitrotate
-
-## begin gnulib module c-ctype
-
-libgnu_la_SOURCES += c-ctype.h c-ctype.c
-
-## end   gnulib module c-ctype
-
-## begin gnulib module canonicalize
-
-libgnu_la_SOURCES += canonicalize.c
-
-EXTRA_DIST += canonicalize.h
-
-## end   gnulib module canonicalize
-
-## begin gnulib module canonicalize-lgpl
-
-
-EXTRA_DIST += canonicalize-lgpl.c
-
-EXTRA_libgnu_la_SOURCES += canonicalize-lgpl.c
-
-## end   gnulib module canonicalize-lgpl
-
-## begin gnulib module chdir-long
-
-
-EXTRA_DIST += chdir-long.c chdir-long.h
-
-EXTRA_libgnu_la_SOURCES += chdir-long.c
-
-## end   gnulib module chdir-long
-
-## begin gnulib module cloexec
-
-libgnu_la_SOURCES += cloexec.c
-
-EXTRA_DIST += cloexec.h
-
-## end   gnulib module cloexec
-
-## begin gnulib module close
-
-
-EXTRA_DIST += close.c
-
-EXTRA_libgnu_la_SOURCES += close.c
-
-## end   gnulib module close
-
-## begin gnulib module closedir
-
-
-EXTRA_DIST += closedir.c dirent-private.h
-
-EXTRA_libgnu_la_SOURCES += closedir.c
-
-## end   gnulib module closedir
-
-## begin gnulib module configmake
-
-# Listed in the same order as the GNU makefile conventions, and
-# provided by autoconf 2.59c+.
-# The Automake-defined pkg* macros are appended, in the order
-# listed in the Automake 1.10a+ documentation.
-configmake.h: Makefile
-	$(AM_V_GEN)rm -f $@-t && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
-	  echo '#define PREFIX "$(prefix)"'; \
-	  echo '#define EXEC_PREFIX "$(exec_prefix)"'; \
-	  echo '#define BINDIR "$(bindir)"'; \
-	  echo '#define SBINDIR "$(sbindir)"'; \
-	  echo '#define LIBEXECDIR "$(libexecdir)"'; \
-	  echo '#define DATAROOTDIR "$(datarootdir)"'; \
-	  echo '#define DATADIR "$(datadir)"'; \
-	  echo '#define SYSCONFDIR "$(sysconfdir)"'; \
-	  echo '#define SHAREDSTATEDIR "$(sharedstatedir)"'; \
-	  echo '#define LOCALSTATEDIR "$(localstatedir)"'; \
-	  echo '#define INCLUDEDIR "$(includedir)"'; \
-	  echo '#define OLDINCLUDEDIR "$(oldincludedir)"'; \
-	  echo '#define DOCDIR "$(docdir)"'; \
-	  echo '#define INFODIR "$(infodir)"'; \
-	  echo '#define HTMLDIR "$(htmldir)"'; \
-	  echo '#define DVIDIR "$(dvidir)"'; \
-	  echo '#define PDFDIR "$(pdfdir)"'; \
-	  echo '#define PSDIR "$(psdir)"'; \
-	  echo '#define LIBDIR "$(libdir)"'; \
-	  echo '#define LISPDIR "$(lispdir)"'; \
-	  echo '#define LOCALEDIR "$(localedir)"'; \
-	  echo '#define MANDIR "$(mandir)"'; \
-	  echo '#define MANEXT "$(manext)"'; \
-	  echo '#define PKGDATADIR "$(pkgdatadir)"'; \
-	  echo '#define PKGINCLUDEDIR "$(pkgincludedir)"'; \
-	  echo '#define PKGLIBDIR "$(pkglibdir)"'; \
-	  echo '#define PKGLIBEXECDIR "$(pkglibexecdir)"'; \
-	} | sed '/""/d' > $@-t && \
-	mv -f $@-t $@
-
-BUILT_SOURCES += configmake.h
-CLEANFILES += configmake.h configmake.h-t
-
-## end   gnulib module configmake
-
-## begin gnulib module copysign
-
-
-EXTRA_DIST += copysign.c
-
-EXTRA_libgnu_la_SOURCES += copysign.c
-
-## end   gnulib module copysign
-
-## begin gnulib module copysignf
-
-
-EXTRA_DIST += copysignf.c
-
-EXTRA_libgnu_la_SOURCES += copysignf.c
-
-## end   gnulib module copysignf
-
-## begin gnulib module crypto/md5
-
-libgnu_la_SOURCES += md5.c
-
-EXTRA_DIST += md5.h
-
-## end   gnulib module crypto/md5
-
-## begin gnulib module dirent
-
-BUILT_SOURCES += dirent.h
-
-# We need the following in order to create <dirent.h> when the system
-# doesn't have one that works with the given compiler.
-dirent.h: dirent.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's|@''HAVE_DIRENT_H''@|$(HAVE_DIRENT_H)|g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_DIRENT_H''@|$(NEXT_DIRENT_H)|g' \
-	      -e 's/@''GNULIB_OPENDIR''@/$(GNULIB_OPENDIR)/g' \
-	      -e 's/@''GNULIB_READDIR''@/$(GNULIB_READDIR)/g' \
-	      -e 's/@''GNULIB_REWINDDIR''@/$(GNULIB_REWINDDIR)/g' \
-	      -e 's/@''GNULIB_CLOSEDIR''@/$(GNULIB_CLOSEDIR)/g' \
-	      -e 's/@''GNULIB_DIRFD''@/$(GNULIB_DIRFD)/g' \
-	      -e 's/@''GNULIB_FDOPENDIR''@/$(GNULIB_FDOPENDIR)/g' \
-	      -e 's/@''GNULIB_SCANDIR''@/$(GNULIB_SCANDIR)/g' \
-	      -e 's/@''GNULIB_ALPHASORT''@/$(GNULIB_ALPHASORT)/g' \
-	      -e 's/@''HAVE_OPENDIR''@/$(HAVE_OPENDIR)/g' \
-	      -e 's/@''HAVE_READDIR''@/$(HAVE_READDIR)/g' \
-	      -e 's/@''HAVE_REWINDDIR''@/$(HAVE_REWINDDIR)/g' \
-	      -e 's/@''HAVE_CLOSEDIR''@/$(HAVE_CLOSEDIR)/g' \
-	      -e 's|@''HAVE_DECL_DIRFD''@|$(HAVE_DECL_DIRFD)|g' \
-	      -e 's|@''HAVE_DECL_FDOPENDIR''@|$(HAVE_DECL_FDOPENDIR)|g' \
-	      -e 's|@''HAVE_FDOPENDIR''@|$(HAVE_FDOPENDIR)|g' \
-	      -e 's|@''HAVE_SCANDIR''@|$(HAVE_SCANDIR)|g' \
-	      -e 's|@''HAVE_ALPHASORT''@|$(HAVE_ALPHASORT)|g' \
-	      -e 's|@''REPLACE_OPENDIR''@|$(REPLACE_OPENDIR)|g' \
-	      -e 's|@''REPLACE_CLOSEDIR''@|$(REPLACE_CLOSEDIR)|g' \
-	      -e 's|@''REPLACE_DIRFD''@|$(REPLACE_DIRFD)|g' \
-	      -e 's|@''REPLACE_FDOPENDIR''@|$(REPLACE_FDOPENDIR)|g' \
-	      -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
-	      -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
-	      -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
-	      < $(srcdir)/dirent.in.h; \
-	} > $@-t && \
-	mv $@-t $@
-MOSTLYCLEANFILES += dirent.h dirent.h-t
-
-EXTRA_DIST += dirent.in.h
-
-## end   gnulib module dirent
-
-## begin gnulib module dirfd
-
-
-EXTRA_DIST += dirfd.c
-
-EXTRA_libgnu_la_SOURCES += dirfd.c
-
-## end   gnulib module dirfd
-
-## begin gnulib module dirname
-
-libgnu_la_SOURCES += dirname.c basename.c
-
-EXTRA_DIST += stripslash.c
-
-EXTRA_libgnu_la_SOURCES += stripslash.c
-
-## end   gnulib module dirname
-
-## begin gnulib module dirname-lgpl
-
-libgnu_la_SOURCES += dirname-lgpl.c basename-lgpl.c stripslash.c
-
-EXTRA_DIST += dirname.h
-
-## end   gnulib module dirname-lgpl
-
-## begin gnulib module dosname
-
-
-EXTRA_DIST += dosname.h
-
-## end   gnulib module dosname
-
-## begin gnulib module dup
-
-
-EXTRA_DIST += dup.c
-
-EXTRA_libgnu_la_SOURCES += dup.c
-
-## end   gnulib module dup
-
-## begin gnulib module dup2
-
-
-EXTRA_DIST += dup2.c
-
-EXTRA_libgnu_la_SOURCES += dup2.c
-
-## end   gnulib module dup2
-
-## begin gnulib module errno
-
-BUILT_SOURCES += $(ERRNO_H)
-
-# We need the following in order to create <errno.h> when the system
-# doesn't have one that is POSIX compliant.
-if GL_GENERATE_ERRNO_H
-errno.h: errno.in.h $(top_builddir)/config.status
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_ERRNO_H''@|$(NEXT_ERRNO_H)|g' \
-	      -e 's|@''EMULTIHOP_HIDDEN''@|$(EMULTIHOP_HIDDEN)|g' \
-	      -e 's|@''EMULTIHOP_VALUE''@|$(EMULTIHOP_VALUE)|g' \
-	      -e 's|@''ENOLINK_HIDDEN''@|$(ENOLINK_HIDDEN)|g' \
-	      -e 's|@''ENOLINK_VALUE''@|$(ENOLINK_VALUE)|g' \
-	      -e 's|@''EOVERFLOW_HIDDEN''@|$(EOVERFLOW_HIDDEN)|g' \
-	      -e 's|@''EOVERFLOW_VALUE''@|$(EOVERFLOW_VALUE)|g' \
-	      < $(srcdir)/errno.in.h; \
-	} > $@-t && \
-	mv $@-t $@
-else
-errno.h: $(top_builddir)/config.status
-	rm -f $@
-endif
-MOSTLYCLEANFILES += errno.h errno.h-t
-
-EXTRA_DIST += errno.in.h
-
-## end   gnulib module errno
-
-## begin gnulib module error
-
-
-EXTRA_DIST += error.c error.h
-
-EXTRA_libgnu_la_SOURCES += error.c
-
-## end   gnulib module error
-
-## begin gnulib module exitfail
-
-libgnu_la_SOURCES += exitfail.c
-
-EXTRA_DIST += exitfail.h
-
-## end   gnulib module exitfail
-
-## begin gnulib module fchdir
-
-
-EXTRA_DIST += fchdir.c
-
-EXTRA_libgnu_la_SOURCES += fchdir.c
-
-## end   gnulib module fchdir
-
-## begin gnulib module fclose
-
-
-EXTRA_DIST += fclose.c
-
-EXTRA_libgnu_la_SOURCES += fclose.c
-
-## end   gnulib module fclose
-
-## begin gnulib module fcntl
-
-
-EXTRA_DIST += fcntl.c
-
-EXTRA_libgnu_la_SOURCES += fcntl.c
-
-## end   gnulib module fcntl
-
-## begin gnulib module fcntl-h
-
-BUILT_SOURCES += fcntl.h
-
-# We need the following in order to create <fcntl.h> when the system
-# doesn't have one that works with the given compiler.
-fcntl.h: fcntl.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_FCNTL_H''@|$(NEXT_FCNTL_H)|g' \
-	      -e 's/@''GNULIB_FCNTL''@/$(GNULIB_FCNTL)/g' \
-	      -e 's/@''GNULIB_NONBLOCKING''@/$(GNULIB_NONBLOCKING)/g' \
-	      -e 's/@''GNULIB_OPEN''@/$(GNULIB_OPEN)/g' \
-	      -e 's/@''GNULIB_OPENAT''@/$(GNULIB_OPENAT)/g' \
-	      -e 's|@''HAVE_FCNTL''@|$(HAVE_FCNTL)|g' \
-	      -e 's|@''HAVE_OPENAT''@|$(HAVE_OPENAT)|g' \
-	      -e 's|@''REPLACE_FCNTL''@|$(REPLACE_FCNTL)|g' \
-	      -e 's|@''REPLACE_OPEN''@|$(REPLACE_OPEN)|g' \
-	      -e 's|@''REPLACE_OPENAT''@|$(REPLACE_OPENAT)|g' \
-	      -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
-	      -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
-	      -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
-	      < $(srcdir)/fcntl.in.h; \
-	} > $@-t && \
-	mv $@-t $@
-MOSTLYCLEANFILES += fcntl.h fcntl.h-t
-
-EXTRA_DIST += fcntl.in.h
-
-## end   gnulib module fcntl-h
-
-## begin gnulib module fd-hook
-
-libgnu_la_SOURCES += fd-hook.c
-
-EXTRA_DIST += fd-hook.h
-
-## end   gnulib module fd-hook
-
-## begin gnulib module fdopendir
-
-
-EXTRA_DIST += fdopendir.c
-
-EXTRA_libgnu_la_SOURCES += fdopendir.c
-
-## end   gnulib module fdopendir
-
-## begin gnulib module fflush
-
-
-EXTRA_DIST += fflush.c stdio-impl.h
-
-EXTRA_libgnu_la_SOURCES += fflush.c
-
-## end   gnulib module fflush
-
-## begin gnulib module file-set
-
-libgnu_la_SOURCES += file-set.c
-
-EXTRA_DIST += file-set.h
-
-## end   gnulib module file-set
-
-## begin gnulib module filemode
-
-libgnu_la_SOURCES += filemode.c
-
-EXTRA_DIST += filemode.h
-
-## end   gnulib module filemode
-
-## begin gnulib module filename
-
-
-EXTRA_DIST += filename.h
-
-## end   gnulib module filename
-
-## begin gnulib module filenamecat-lgpl
-
-libgnu_la_SOURCES += filenamecat-lgpl.c
-
-EXTRA_DIST += filenamecat.h
-
-## end   gnulib module filenamecat-lgpl
-
-## begin gnulib module float
-
-BUILT_SOURCES += $(FLOAT_H)
-
-# We need the following in order to create <float.h> when the system
-# doesn't have one that works with the given compiler.
-if GL_GENERATE_FLOAT_H
-float.h: float.in.h $(top_builddir)/config.status
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_FLOAT_H''@|$(NEXT_FLOAT_H)|g' \
-	      -e 's|@''REPLACE_ITOLD''@|$(REPLACE_ITOLD)|g' \
-	      < $(srcdir)/float.in.h; \
-	} > $@-t && \
-	mv $@-t $@
-else
-float.h: $(top_builddir)/config.status
-	rm -f $@
-endif
-MOSTLYCLEANFILES += float.h float.h-t
-
-EXTRA_DIST += float.c float.in.h itold.c
-
-EXTRA_libgnu_la_SOURCES += float.c itold.c
-
-## end   gnulib module float
-
-## begin gnulib module floor
-
-
-EXTRA_DIST += floor.c
-
-EXTRA_libgnu_la_SOURCES += floor.c
-
-## end   gnulib module floor
-
-## begin gnulib module floorf
-
-
-EXTRA_DIST += floor.c floorf.c
-
-EXTRA_libgnu_la_SOURCES += floor.c floorf.c
-
-## end   gnulib module floorf
-
-## begin gnulib module fnmatch
-
-BUILT_SOURCES += $(FNMATCH_H)
-
-# We need the following in order to create <fnmatch.h> when the system
-# doesn't have one that supports the required API.
-if GL_GENERATE_FNMATCH_H
-fnmatch.h: fnmatch.in.h $(top_builddir)/config.status $(ARG_NONNULL_H)
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
-	  sed -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
-	      < $(srcdir)/fnmatch.in.h; \
-	} > $@-t && \
-	mv -f $@-t $@
-else
-fnmatch.h: $(top_builddir)/config.status
-	rm -f $@
-endif
-MOSTLYCLEANFILES += fnmatch.h fnmatch.h-t
-
-EXTRA_DIST += fnmatch.c fnmatch.in.h fnmatch_loop.c
-
-EXTRA_libgnu_la_SOURCES += fnmatch.c fnmatch_loop.c
-
-## end   gnulib module fnmatch
-
-## begin gnulib module fopen
-
-
-EXTRA_DIST += fopen.c
-
-EXTRA_libgnu_la_SOURCES += fopen.c
-
-## end   gnulib module fopen
-
-## begin gnulib module fpurge
-
-
-EXTRA_DIST += fpurge.c stdio-impl.h
-
-EXTRA_libgnu_la_SOURCES += fpurge.c
-
-## end   gnulib module fpurge
-
-## begin gnulib module freading
-
-libgnu_la_SOURCES += freading.c
-
-EXTRA_DIST += freading.h stdio-impl.h
-
-## end   gnulib module freading
-
-## begin gnulib module fseek
-
-
-EXTRA_DIST += fseek.c
-
-EXTRA_libgnu_la_SOURCES += fseek.c
-
-## end   gnulib module fseek
-
-## begin gnulib module fseeko
-
-
-EXTRA_DIST += fseeko.c stdio-impl.h
-
-EXTRA_libgnu_la_SOURCES += fseeko.c
-
-## end   gnulib module fseeko
-
-## begin gnulib module fstat
-
-
-EXTRA_DIST += fstat.c
-
-EXTRA_libgnu_la_SOURCES += fstat.c
-
-## end   gnulib module fstat
-
-## begin gnulib module fstatat
-
-
-EXTRA_DIST += at-func.c fstatat.c openat-priv.h
-
-EXTRA_libgnu_la_SOURCES += at-func.c fstatat.c
-
-## end   gnulib module fstatat
-
-## begin gnulib module ftell
-
-
-EXTRA_DIST += ftell.c
-
-EXTRA_libgnu_la_SOURCES += ftell.c
-
-## end   gnulib module ftell
-
-## begin gnulib module ftello
-
-
-EXTRA_DIST += ftello.c stdio-impl.h
-
-EXTRA_libgnu_la_SOURCES += ftello.c
-
-## end   gnulib module ftello
-
-## begin gnulib module getcwd
-
-
-EXTRA_DIST += getcwd.c
-
-EXTRA_libgnu_la_SOURCES += getcwd.c
-
-## end   gnulib module getcwd
-
-## begin gnulib module getcwd-lgpl
-
-
-EXTRA_DIST += getcwd-lgpl.c
-
-EXTRA_libgnu_la_SOURCES += getcwd-lgpl.c
-
-## end   gnulib module getcwd-lgpl
-
-## begin gnulib module getdtablesize
-
-
-EXTRA_DIST += getdtablesize.c
-
-EXTRA_libgnu_la_SOURCES += getdtablesize.c
-
-## end   gnulib module getdtablesize
-
-## begin gnulib module gethostname
-
-
-EXTRA_DIST += gethostname.c w32sock.h
-
-EXTRA_libgnu_la_SOURCES += gethostname.c
-
-## end   gnulib module gethostname
-
-## begin gnulib module getlogin_r
-
-
-EXTRA_DIST += getlogin_r.c
-
-EXTRA_libgnu_la_SOURCES += getlogin_r.c
-
-## end   gnulib module getlogin_r
-
-## begin gnulib module getopt-posix
-
-BUILT_SOURCES += $(GETOPT_H)
-
-# We need the following in order to create <getopt.h> when the system
-# doesn't have one that works with the given compiler.
-getopt.h: getopt.in.h $(top_builddir)/config.status $(ARG_NONNULL_H)
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's|@''HAVE_GETOPT_H''@|$(HAVE_GETOPT_H)|g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_GETOPT_H''@|$(NEXT_GETOPT_H)|g' \
-	      -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
-	      < $(srcdir)/getopt.in.h; \
-	} > $@-t && \
-	mv -f $@-t $@
-MOSTLYCLEANFILES += getopt.h getopt.h-t
-
-EXTRA_DIST += getopt.c getopt.in.h getopt1.c getopt_int.h
-
-EXTRA_libgnu_la_SOURCES += getopt.c getopt1.c
-
-## end   gnulib module getopt-posix
-
-## begin gnulib module gettext-h
-
-libgnu_la_SOURCES += gettext.h
-
-## end   gnulib module gettext-h
-
-## begin gnulib module gettimeofday
-
-
-EXTRA_DIST += gettimeofday.c
-
-EXTRA_libgnu_la_SOURCES += gettimeofday.c
-
-## end   gnulib module gettimeofday
-
-## begin gnulib module glob
-
-BUILT_SOURCES += $(GLOB_H)
-
-# We need the following in order to create <glob.h> when the system
-# doesn't have one that works with the given compiler.
-if GL_GENERATE_GLOB_H
-glob.h: glob.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
-	  sed -e 's|@''HAVE_SYS_CDEFS_H''@|$(HAVE_SYS_CDEFS_H)|g' \
-	      -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
-	      -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
-	      -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
-	      < $(srcdir)/glob.in.h; \
-	} > $@-t && \
-	mv -f $@-t $@
-else
-glob.h: $(top_builddir)/config.status
-	rm -f $@
-endif
-MOSTLYCLEANFILES += glob.h glob.h-t
-
-EXTRA_DIST += glob-libc.h glob.c glob.in.h
-
-EXTRA_libgnu_la_SOURCES += glob.c
-
-## end   gnulib module glob
-
-## begin gnulib module hash
-
-libgnu_la_SOURCES += hash.c
-
-EXTRA_DIST += hash.h
-
-## end   gnulib module hash
-
-## begin gnulib module hash-pjw
-
-libgnu_la_SOURCES += hash-pjw.h hash-pjw.c
-
-## end   gnulib module hash-pjw
-
-## begin gnulib module hash-triple
-
-libgnu_la_SOURCES += hash-triple.c
-
-EXTRA_DIST += hash-triple.h
-
-## end   gnulib module hash-triple
-
-## begin gnulib module intprops
-
-
-EXTRA_DIST += intprops.h
-
-## end   gnulib module intprops
-
-## begin gnulib module isatty
-
-
-EXTRA_DIST += isatty.c
-
-EXTRA_libgnu_la_SOURCES += isatty.c
-
-## end   gnulib module isatty
-
-## begin gnulib module isnand-nolibm
-
-
-EXTRA_DIST += float+.h isnan.c isnand-nolibm.h isnand.c
-
-EXTRA_libgnu_la_SOURCES += isnan.c isnand.c
-
-## end   gnulib module isnand-nolibm
-
-## begin gnulib module isnanf-nolibm
-
-
-EXTRA_DIST += float+.h isnan.c isnanf-nolibm.h isnanf.c
-
-EXTRA_libgnu_la_SOURCES += isnan.c isnanf.c
-
-## end   gnulib module isnanf-nolibm
-
-## begin gnulib module isnanl-nolibm
-
-
-EXTRA_DIST += float+.h isnan.c isnanl-nolibm.h isnanl.c
-
-EXTRA_libgnu_la_SOURCES += isnan.c isnanl.c
-
-## end   gnulib module isnanl-nolibm
-
-## begin gnulib module link
-
-
-EXTRA_DIST += link.c
-
-EXTRA_libgnu_la_SOURCES += link.c
-
-## end   gnulib module link
-
-## begin gnulib module localcharset
-
-libgnu_la_SOURCES += localcharset.h localcharset.c
-
-# We need the following in order to install a simple file in $(libdir)
-# which is shared with other installed packages. We use a list of referencing
-# packages so that "make uninstall" will remove the file if and only if it
-# is not used by another installed package.
-# On systems with glibc-2.1 or newer, the file is redundant, therefore we
-# avoid installing it.
-
-all-local: charset.alias ref-add.sed ref-del.sed
-
-charset_alias = $(DESTDIR)$(libdir)/charset.alias
-charset_tmp = $(DESTDIR)$(libdir)/charset.tmp
-install-exec-local: install-exec-localcharset
-install-exec-localcharset: all-local
-	if test $(GLIBC21) = no; then \
-	  case '$(host_os)' in \
-	    darwin[56]*) \
-	      need_charset_alias=true ;; \
-	    darwin* | cygwin* | mingw* | pw32* | cegcc*) \
-	      need_charset_alias=false ;; \
-	    *) \
-	      need_charset_alias=true ;; \
-	  esac ; \
-	else \
-	  need_charset_alias=false ; \
-	fi ; \
-	if $$need_charset_alias; then \
-	  $(mkinstalldirs) $(DESTDIR)$(libdir) ; \
-	fi ; \
-	if test -f $(charset_alias); then \
-	  sed -f ref-add.sed $(charset_alias) > $(charset_tmp) ; \
-	  $(INSTALL_DATA) $(charset_tmp) $(charset_alias) ; \
-	  rm -f $(charset_tmp) ; \
-	else \
-	  if $$need_charset_alias; then \
-	    sed -f ref-add.sed charset.alias > $(charset_tmp) ; \
-	    $(INSTALL_DATA) $(charset_tmp) $(charset_alias) ; \
-	    rm -f $(charset_tmp) ; \
-	  fi ; \
-	fi
-
-uninstall-local: uninstall-localcharset
-uninstall-localcharset: all-local
-	if test -f $(charset_alias); then \
-	  sed -f ref-del.sed $(charset_alias) > $(charset_tmp); \
-	  if grep '^# Packages using this file: $$' $(charset_tmp) \
-	      > /dev/null; then \
-	    rm -f $(charset_alias); \
-	  else \
-	    $(INSTALL_DATA) $(charset_tmp) $(charset_alias); \
-	  fi; \
-	  rm -f $(charset_tmp); \
-	fi
-
-charset.alias: config.charset
-	$(AM_V_GEN)rm -f t-$@ $@ && \
-	$(SHELL) $(srcdir)/config.charset '$(host)' > t-$@ && \
-	mv t-$@ $@
-
-SUFFIXES += .sed .sin
-.sin.sed:
-	$(AM_V_GEN)rm -f t-$@ $@ && \
-	sed -e '/^#/d' -e 's/@''PACKAGE''@/$(PACKAGE)/g' $< > t-$@ && \
-	mv t-$@ $@
-
-CLEANFILES += charset.alias ref-add.sed ref-del.sed
-
-EXTRA_DIST += config.charset ref-add.sin ref-del.sin
-
-## end   gnulib module localcharset
-
-## begin gnulib module lseek
-
-
-EXTRA_DIST += lseek.c
-
-EXTRA_libgnu_la_SOURCES += lseek.c
-
-## end   gnulib module lseek
-
-## begin gnulib module lstat
-
-
-EXTRA_DIST += lstat.c
-
-EXTRA_libgnu_la_SOURCES += lstat.c
-
-## end   gnulib module lstat
-
-## begin gnulib module malloc-gnu
-
-
-EXTRA_DIST += malloc.c
-
-EXTRA_libgnu_la_SOURCES += malloc.c
-
-## end   gnulib module malloc-gnu
-
-## begin gnulib module malloc-posix
-
-
-EXTRA_DIST += malloc.c
-
-EXTRA_libgnu_la_SOURCES += malloc.c
-
-## end   gnulib module malloc-posix
-
-## begin gnulib module malloca
-
-libgnu_la_SOURCES += malloca.c
-
-EXTRA_DIST += malloca.h malloca.valgrind
-
-## end   gnulib module malloca
-
-## begin gnulib module math
-
-BUILT_SOURCES += math.h
-
-# We need the following in order to create <math.h> when the system
-# doesn't have one that works with the given compiler.
-math.h: math.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's|@''INCLUDE_NEXT_AS_FIRST_DIRECTIVE''@|$(INCLUDE_NEXT_AS_FIRST_DIRECTIVE)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_AS_FIRST_DIRECTIVE_MATH_H''@|$(NEXT_AS_FIRST_DIRECTIVE_MATH_H)|g' \
-	      -e 's/@''GNULIB_ACOSF''@/$(GNULIB_ACOSF)/g' \
-	      -e 's/@''GNULIB_ACOSL''@/$(GNULIB_ACOSL)/g' \
-	      -e 's/@''GNULIB_ASINF''@/$(GNULIB_ASINF)/g' \
-	      -e 's/@''GNULIB_ASINL''@/$(GNULIB_ASINL)/g' \
-	      -e 's/@''GNULIB_ATANF''@/$(GNULIB_ATANF)/g' \
-	      -e 's/@''GNULIB_ATANL''@/$(GNULIB_ATANL)/g' \
-	      -e 's/@''GNULIB_ATAN2F''@/$(GNULIB_ATAN2F)/g' \
-	      -e 's/@''GNULIB_CBRT''@/$(GNULIB_CBRT)/g' \
-	      -e 's/@''GNULIB_CBRTF''@/$(GNULIB_CBRTF)/g' \
-	      -e 's/@''GNULIB_CBRTL''@/$(GNULIB_CBRTL)/g' \
-	      -e 's/@''GNULIB_CEIL''@/$(GNULIB_CEIL)/g' \
-	      -e 's/@''GNULIB_CEILF''@/$(GNULIB_CEILF)/g' \
-	      -e 's/@''GNULIB_CEILL''@/$(GNULIB_CEILL)/g' \
-	      -e 's/@''GNULIB_COPYSIGN''@/$(GNULIB_COPYSIGN)/g' \
-	      -e 's/@''GNULIB_COPYSIGNF''@/$(GNULIB_COPYSIGNF)/g' \
-	      -e 's/@''GNULIB_COPYSIGNL''@/$(GNULIB_COPYSIGNL)/g' \
-	      -e 's/@''GNULIB_COSF''@/$(GNULIB_COSF)/g' \
-	      -e 's/@''GNULIB_COSL''@/$(GNULIB_COSL)/g' \
-	      -e 's/@''GNULIB_COSHF''@/$(GNULIB_COSHF)/g' \
-	      -e 's/@''GNULIB_EXPF''@/$(GNULIB_EXPF)/g' \
-	      -e 's/@''GNULIB_EXPL''@/$(GNULIB_EXPL)/g' \
-	      -e 's/@''GNULIB_EXP2''@/$(GNULIB_EXP2)/g' \
-	      -e 's/@''GNULIB_EXP2F''@/$(GNULIB_EXP2F)/g' \
-	      -e 's/@''GNULIB_EXP2L''@/$(GNULIB_EXP2L)/g' \
-	      -e 's/@''GNULIB_EXPM1''@/$(GNULIB_EXPM1)/g' \
-	      -e 's/@''GNULIB_EXPM1F''@/$(GNULIB_EXPM1F)/g' \
-	      -e 's/@''GNULIB_EXPM1L''@/$(GNULIB_EXPM1L)/g' \
-	      -e 's/@''GNULIB_FABSF''@/$(GNULIB_FABSF)/g' \
-	      -e 's/@''GNULIB_FABSL''@/$(GNULIB_FABSL)/g' \
-	      -e 's/@''GNULIB_FLOOR''@/$(GNULIB_FLOOR)/g' \
-	      -e 's/@''GNULIB_FLOORF''@/$(GNULIB_FLOORF)/g' \
-	      -e 's/@''GNULIB_FLOORL''@/$(GNULIB_FLOORL)/g' \
-	      -e 's/@''GNULIB_FMA''@/$(GNULIB_FMA)/g' \
-	      -e 's/@''GNULIB_FMAF''@/$(GNULIB_FMAF)/g' \
-	      -e 's/@''GNULIB_FMAL''@/$(GNULIB_FMAL)/g' \
-	      -e 's/@''GNULIB_FMOD''@/$(GNULIB_FMOD)/g' \
-	      -e 's/@''GNULIB_FMODF''@/$(GNULIB_FMODF)/g' \
-	      -e 's/@''GNULIB_FMODL''@/$(GNULIB_FMODL)/g' \
-	      -e 's/@''GNULIB_FREXPF''@/$(GNULIB_FREXPF)/g' \
-	      -e 's/@''GNULIB_FREXP''@/$(GNULIB_FREXP)/g' \
-	      -e 's/@''GNULIB_FREXPL''@/$(GNULIB_FREXPL)/g' \
-	      -e 's/@''GNULIB_HYPOT''@/$(GNULIB_HYPOT)/g' \
-	      -e 's/@''GNULIB_HYPOTF''@/$(GNULIB_HYPOTF)/g' \
-	      -e 's/@''GNULIB_HYPOTL''@/$(GNULIB_HYPOTL)/g' \
-	      < $(srcdir)/math.in.h | \
-	  sed -e 's/@''GNULIB_ILOGB''@/$(GNULIB_ILOGB)/g' \
-	      -e 's/@''GNULIB_ILOGBF''@/$(GNULIB_ILOGBF)/g' \
-	      -e 's/@''GNULIB_ILOGBL''@/$(GNULIB_ILOGBL)/g' \
-	      -e 's/@''GNULIB_ISFINITE''@/$(GNULIB_ISFINITE)/g' \
-	      -e 's/@''GNULIB_ISINF''@/$(GNULIB_ISINF)/g' \
-	      -e 's/@''GNULIB_ISNAN''@/$(GNULIB_ISNAN)/g' \
-	      -e 's/@''GNULIB_ISNANF''@/$(GNULIB_ISNANF)/g' \
-	      -e 's/@''GNULIB_ISNAND''@/$(GNULIB_ISNAND)/g' \
-	      -e 's/@''GNULIB_ISNANL''@/$(GNULIB_ISNANL)/g' \
-	      -e 's/@''GNULIB_LDEXPF''@/$(GNULIB_LDEXPF)/g' \
-	      -e 's/@''GNULIB_LDEXPL''@/$(GNULIB_LDEXPL)/g' \
-	      -e 's/@''GNULIB_LOG''@/$(GNULIB_LOG)/g' \
-	      -e 's/@''GNULIB_LOGF''@/$(GNULIB_LOGF)/g' \
-	      -e 's/@''GNULIB_LOGL''@/$(GNULIB_LOGL)/g' \
-	      -e 's/@''GNULIB_LOG10''@/$(GNULIB_LOG10)/g' \
-	      -e 's/@''GNULIB_LOG10F''@/$(GNULIB_LOG10F)/g' \
-	      -e 's/@''GNULIB_LOG10L''@/$(GNULIB_LOG10L)/g' \
-	      -e 's/@''GNULIB_LOG1P''@/$(GNULIB_LOG1P)/g' \
-	      -e 's/@''GNULIB_LOG1PF''@/$(GNULIB_LOG1PF)/g' \
-	      -e 's/@''GNULIB_LOG1PL''@/$(GNULIB_LOG1PL)/g' \
-	      -e 's/@''GNULIB_LOG2''@/$(GNULIB_LOG2)/g' \
-	      -e 's/@''GNULIB_LOG2F''@/$(GNULIB_LOG2F)/g' \
-	      -e 's/@''GNULIB_LOG2L''@/$(GNULIB_LOG2L)/g' \
-	      -e 's/@''GNULIB_LOGB''@/$(GNULIB_LOGB)/g' \
-	      -e 's/@''GNULIB_LOGBF''@/$(GNULIB_LOGBF)/g' \
-	      -e 's/@''GNULIB_LOGBL''@/$(GNULIB_LOGBL)/g' \
-	      -e 's/@''GNULIB_MODF''@/$(GNULIB_MODF)/g' \
-	      -e 's/@''GNULIB_MODFF''@/$(GNULIB_MODFF)/g' \
-	      -e 's/@''GNULIB_MODFL''@/$(GNULIB_MODFL)/g' \
-	      -e 's/@''GNULIB_POWF''@/$(GNULIB_POWF)/g' \
-	      -e 's/@''GNULIB_REMAINDER''@/$(GNULIB_REMAINDER)/g' \
-	      -e 's/@''GNULIB_REMAINDERF''@/$(GNULIB_REMAINDERF)/g' \
-	      -e 's/@''GNULIB_REMAINDERL''@/$(GNULIB_REMAINDERL)/g' \
-	      -e 's/@''GNULIB_RINT''@/$(GNULIB_RINT)/g' \
-	      -e 's/@''GNULIB_RINTF''@/$(GNULIB_RINTF)/g' \
-	      -e 's/@''GNULIB_RINTL''@/$(GNULIB_RINTL)/g' \
-	      -e 's/@''GNULIB_ROUND''@/$(GNULIB_ROUND)/g' \
-	      -e 's/@''GNULIB_ROUNDF''@/$(GNULIB_ROUNDF)/g' \
-	      -e 's/@''GNULIB_ROUNDL''@/$(GNULIB_ROUNDL)/g' \
-	      -e 's/@''GNULIB_SIGNBIT''@/$(GNULIB_SIGNBIT)/g' \
-	      -e 's/@''GNULIB_SINF''@/$(GNULIB_SINF)/g' \
-	      -e 's/@''GNULIB_SINL''@/$(GNULIB_SINL)/g' \
-	      -e 's/@''GNULIB_SINHF''@/$(GNULIB_SINHF)/g' \
-	      -e 's/@''GNULIB_SQRTF''@/$(GNULIB_SQRTF)/g' \
-	      -e 's/@''GNULIB_SQRTL''@/$(GNULIB_SQRTL)/g' \
-	      -e 's/@''GNULIB_TANF''@/$(GNULIB_TANF)/g' \
-	      -e 's/@''GNULIB_TANL''@/$(GNULIB_TANL)/g' \
-	      -e 's/@''GNULIB_TANHF''@/$(GNULIB_TANHF)/g' \
-	      -e 's/@''GNULIB_TRUNC''@/$(GNULIB_TRUNC)/g' \
-	      -e 's/@''GNULIB_TRUNCF''@/$(GNULIB_TRUNCF)/g' \
-	      -e 's/@''GNULIB_TRUNCL''@/$(GNULIB_TRUNCL)/g' \
-	  | \
-	  sed -e 's|@''HAVE_ACOSF''@|$(HAVE_ACOSF)|g' \
-	      -e 's|@''HAVE_ACOSL''@|$(HAVE_ACOSL)|g' \
-	      -e 's|@''HAVE_ASINF''@|$(HAVE_ASINF)|g' \
-	      -e 's|@''HAVE_ASINL''@|$(HAVE_ASINL)|g' \
-	      -e 's|@''HAVE_ATANF''@|$(HAVE_ATANF)|g' \
-	      -e 's|@''HAVE_ATANL''@|$(HAVE_ATANL)|g' \
-	      -e 's|@''HAVE_ATAN2F''@|$(HAVE_ATAN2F)|g' \
-	      -e 's|@''HAVE_CBRT''@|$(HAVE_CBRT)|g' \
-	      -e 's|@''HAVE_CBRTF''@|$(HAVE_CBRTF)|g' \
-	      -e 's|@''HAVE_CBRTL''@|$(HAVE_CBRTL)|g' \
-	      -e 's|@''HAVE_COPYSIGN''@|$(HAVE_COPYSIGN)|g' \
-	      -e 's|@''HAVE_COPYSIGNL''@|$(HAVE_COPYSIGNL)|g' \
-	      -e 's|@''HAVE_COSF''@|$(HAVE_COSF)|g' \
-	      -e 's|@''HAVE_COSL''@|$(HAVE_COSL)|g' \
-	      -e 's|@''HAVE_COSHF''@|$(HAVE_COSHF)|g' \
-	      -e 's|@''HAVE_EXPF''@|$(HAVE_EXPF)|g' \
-	      -e 's|@''HAVE_EXPL''@|$(HAVE_EXPL)|g' \
-	      -e 's|@''HAVE_EXPM1''@|$(HAVE_EXPM1)|g' \
-	      -e 's|@''HAVE_EXPM1F''@|$(HAVE_EXPM1F)|g' \
-	      -e 's|@''HAVE_FABSF''@|$(HAVE_FABSF)|g' \
-	      -e 's|@''HAVE_FABSL''@|$(HAVE_FABSL)|g' \
-	      -e 's|@''HAVE_FMA''@|$(HAVE_FMA)|g' \
-	      -e 's|@''HAVE_FMAF''@|$(HAVE_FMAF)|g' \
-	      -e 's|@''HAVE_FMAL''@|$(HAVE_FMAL)|g' \
-	      -e 's|@''HAVE_FMODF''@|$(HAVE_FMODF)|g' \
-	      -e 's|@''HAVE_FMODL''@|$(HAVE_FMODL)|g' \
-	      -e 's|@''HAVE_FREXPF''@|$(HAVE_FREXPF)|g' \
-	      -e 's|@''HAVE_HYPOTF''@|$(HAVE_HYPOTF)|g' \
-	      -e 's|@''HAVE_HYPOTL''@|$(HAVE_HYPOTL)|g' \
-	      -e 's|@''HAVE_ILOGB''@|$(HAVE_ILOGB)|g' \
-	      -e 's|@''HAVE_ILOGBF''@|$(HAVE_ILOGBF)|g' \
-	      -e 's|@''HAVE_ILOGBL''@|$(HAVE_ILOGBL)|g' \
-	      -e 's|@''HAVE_ISNANF''@|$(HAVE_ISNANF)|g' \
-	      -e 's|@''HAVE_ISNAND''@|$(HAVE_ISNAND)|g' \
-	      -e 's|@''HAVE_ISNANL''@|$(HAVE_ISNANL)|g' \
-	      -e 's|@''HAVE_LDEXPF''@|$(HAVE_LDEXPF)|g' \
-	      -e 's|@''HAVE_LOGF''@|$(HAVE_LOGF)|g' \
-	      -e 's|@''HAVE_LOGL''@|$(HAVE_LOGL)|g' \
-	      -e 's|@''HAVE_LOG10F''@|$(HAVE_LOG10F)|g' \
-	      -e 's|@''HAVE_LOG10L''@|$(HAVE_LOG10L)|g' \
-	      -e 's|@''HAVE_LOG1P''@|$(HAVE_LOG1P)|g' \
-	      -e 's|@''HAVE_LOG1PF''@|$(HAVE_LOG1PF)|g' \
-	      -e 's|@''HAVE_LOG1PL''@|$(HAVE_LOG1PL)|g' \
-	      -e 's|@''HAVE_LOGBF''@|$(HAVE_LOGBF)|g' \
-	      -e 's|@''HAVE_LOGBL''@|$(HAVE_LOGBL)|g' \
-	      -e 's|@''HAVE_MODFF''@|$(HAVE_MODFF)|g' \
-	      -e 's|@''HAVE_MODFL''@|$(HAVE_MODFL)|g' \
-	      -e 's|@''HAVE_POWF''@|$(HAVE_POWF)|g' \
-	      -e 's|@''HAVE_REMAINDER''@|$(HAVE_REMAINDER)|g' \
-	      -e 's|@''HAVE_REMAINDERF''@|$(HAVE_REMAINDERF)|g' \
-	      -e 's|@''HAVE_RINT''@|$(HAVE_RINT)|g' \
-	      -e 's|@''HAVE_RINTL''@|$(HAVE_RINTL)|g' \
-	      -e 's|@''HAVE_SINF''@|$(HAVE_SINF)|g' \
-	      -e 's|@''HAVE_SINL''@|$(HAVE_SINL)|g' \
-	      -e 's|@''HAVE_SINHF''@|$(HAVE_SINHF)|g' \
-	      -e 's|@''HAVE_SQRTF''@|$(HAVE_SQRTF)|g' \
-	      -e 's|@''HAVE_SQRTL''@|$(HAVE_SQRTL)|g' \
-	      -e 's|@''HAVE_TANF''@|$(HAVE_TANF)|g' \
-	      -e 's|@''HAVE_TANL''@|$(HAVE_TANL)|g' \
-	      -e 's|@''HAVE_TANHF''@|$(HAVE_TANHF)|g' \
-	      -e 's|@''HAVE_DECL_ACOSL''@|$(HAVE_DECL_ACOSL)|g' \
-	      -e 's|@''HAVE_DECL_ASINL''@|$(HAVE_DECL_ASINL)|g' \
-	      -e 's|@''HAVE_DECL_ATANL''@|$(HAVE_DECL_ATANL)|g' \
-	      -e 's|@''HAVE_DECL_CBRTF''@|$(HAVE_DECL_CBRTF)|g' \
-	      -e 's|@''HAVE_DECL_CBRTL''@|$(HAVE_DECL_CBRTL)|g' \
-	      -e 's|@''HAVE_DECL_CEILF''@|$(HAVE_DECL_CEILF)|g' \
-	      -e 's|@''HAVE_DECL_CEILL''@|$(HAVE_DECL_CEILL)|g' \
-	      -e 's|@''HAVE_DECL_COPYSIGNF''@|$(HAVE_DECL_COPYSIGNF)|g' \
-	      -e 's|@''HAVE_DECL_COSL''@|$(HAVE_DECL_COSL)|g' \
-	      -e 's|@''HAVE_DECL_EXPL''@|$(HAVE_DECL_EXPL)|g' \
-	      -e 's|@''HAVE_DECL_EXP2''@|$(HAVE_DECL_EXP2)|g' \
-	      -e 's|@''HAVE_DECL_EXP2F''@|$(HAVE_DECL_EXP2F)|g' \
-	      -e 's|@''HAVE_DECL_EXP2L''@|$(HAVE_DECL_EXP2L)|g' \
-	      -e 's|@''HAVE_DECL_EXPM1L''@|$(HAVE_DECL_EXPM1L)|g' \
-	      -e 's|@''HAVE_DECL_FLOORF''@|$(HAVE_DECL_FLOORF)|g' \
-	      -e 's|@''HAVE_DECL_FLOORL''@|$(HAVE_DECL_FLOORL)|g' \
-	      -e 's|@''HAVE_DECL_FREXPL''@|$(HAVE_DECL_FREXPL)|g' \
-	      -e 's|@''HAVE_DECL_LDEXPL''@|$(HAVE_DECL_LDEXPL)|g' \
-	      -e 's|@''HAVE_DECL_LOGL''@|$(HAVE_DECL_LOGL)|g' \
-	      -e 's|@''HAVE_DECL_LOG10L''@|$(HAVE_DECL_LOG10L)|g' \
-	      -e 's|@''HAVE_DECL_LOG2''@|$(HAVE_DECL_LOG2)|g' \
-	      -e 's|@''HAVE_DECL_LOG2F''@|$(HAVE_DECL_LOG2F)|g' \
-	      -e 's|@''HAVE_DECL_LOG2L''@|$(HAVE_DECL_LOG2L)|g' \
-	      -e 's|@''HAVE_DECL_LOGB''@|$(HAVE_DECL_LOGB)|g' \
-	      -e 's|@''HAVE_DECL_REMAINDER''@|$(HAVE_DECL_REMAINDER)|g' \
-	      -e 's|@''HAVE_DECL_REMAINDERL''@|$(HAVE_DECL_REMAINDERL)|g' \
-	      -e 's|@''HAVE_DECL_RINTF''@|$(HAVE_DECL_RINTF)|g' \
-	      -e 's|@''HAVE_DECL_ROUND''@|$(HAVE_DECL_ROUND)|g' \
-	      -e 's|@''HAVE_DECL_ROUNDF''@|$(HAVE_DECL_ROUNDF)|g' \
-	      -e 's|@''HAVE_DECL_ROUNDL''@|$(HAVE_DECL_ROUNDL)|g' \
-	      -e 's|@''HAVE_DECL_SINL''@|$(HAVE_DECL_SINL)|g' \
-	      -e 's|@''HAVE_DECL_SQRTL''@|$(HAVE_DECL_SQRTL)|g' \
-	      -e 's|@''HAVE_DECL_TANL''@|$(HAVE_DECL_TANL)|g' \
-	      -e 's|@''HAVE_DECL_TRUNC''@|$(HAVE_DECL_TRUNC)|g' \
-	      -e 's|@''HAVE_DECL_TRUNCF''@|$(HAVE_DECL_TRUNCF)|g' \
-	      -e 's|@''HAVE_DECL_TRUNCL''@|$(HAVE_DECL_TRUNCL)|g' \
-	  | \
-	  sed -e 's|@''REPLACE_CBRTF''@|$(REPLACE_CBRTF)|g' \
-	      -e 's|@''REPLACE_CBRTL''@|$(REPLACE_CBRTL)|g' \
-	      -e 's|@''REPLACE_CEIL''@|$(REPLACE_CEIL)|g' \
-	      -e 's|@''REPLACE_CEILF''@|$(REPLACE_CEILF)|g' \
-	      -e 's|@''REPLACE_CEILL''@|$(REPLACE_CEILL)|g' \
-	      -e 's|@''REPLACE_EXPM1''@|$(REPLACE_EXPM1)|g' \
-	      -e 's|@''REPLACE_EXPM1F''@|$(REPLACE_EXPM1F)|g' \
-	      -e 's|@''REPLACE_EXP2''@|$(REPLACE_EXP2)|g' \
-	      -e 's|@''REPLACE_EXP2L''@|$(REPLACE_EXP2L)|g' \
-	      -e 's|@''REPLACE_FABSL''@|$(REPLACE_FABSL)|g' \
-	      -e 's|@''REPLACE_FLOOR''@|$(REPLACE_FLOOR)|g' \
-	      -e 's|@''REPLACE_FLOORF''@|$(REPLACE_FLOORF)|g' \
-	      -e 's|@''REPLACE_FLOORL''@|$(REPLACE_FLOORL)|g' \
-	      -e 's|@''REPLACE_FMA''@|$(REPLACE_FMA)|g' \
-	      -e 's|@''REPLACE_FMAF''@|$(REPLACE_FMAF)|g' \
-	      -e 's|@''REPLACE_FMAL''@|$(REPLACE_FMAL)|g' \
-	      -e 's|@''REPLACE_FMOD''@|$(REPLACE_FMOD)|g' \
-	      -e 's|@''REPLACE_FMODF''@|$(REPLACE_FMODF)|g' \
-	      -e 's|@''REPLACE_FMODL''@|$(REPLACE_FMODL)|g' \
-	      -e 's|@''REPLACE_FREXPF''@|$(REPLACE_FREXPF)|g' \
-	      -e 's|@''REPLACE_FREXP''@|$(REPLACE_FREXP)|g' \
-	      -e 's|@''REPLACE_FREXPL''@|$(REPLACE_FREXPL)|g' \
-	      -e 's|@''REPLACE_HUGE_VAL''@|$(REPLACE_HUGE_VAL)|g' \
-	      -e 's|@''REPLACE_HYPOT''@|$(REPLACE_HYPOT)|g' \
-	      -e 's|@''REPLACE_HYPOTF''@|$(REPLACE_HYPOTF)|g' \
-	      -e 's|@''REPLACE_HYPOTL''@|$(REPLACE_HYPOTL)|g' \
-	      -e 's|@''REPLACE_ILOGB''@|$(REPLACE_ILOGB)|g' \
-	      -e 's|@''REPLACE_ILOGBF''@|$(REPLACE_ILOGBF)|g' \
-	      -e 's|@''REPLACE_ISFINITE''@|$(REPLACE_ISFINITE)|g' \
-	      -e 's|@''REPLACE_ISINF''@|$(REPLACE_ISINF)|g' \
-	      -e 's|@''REPLACE_ISNAN''@|$(REPLACE_ISNAN)|g' \
-	      -e 's|@''REPLACE_ITOLD''@|$(REPLACE_ITOLD)|g' \
-	      -e 's|@''REPLACE_LDEXPL''@|$(REPLACE_LDEXPL)|g' \
-	      -e 's|@''REPLACE_LOG''@|$(REPLACE_LOG)|g' \
-	      -e 's|@''REPLACE_LOGF''@|$(REPLACE_LOGF)|g' \
-	      -e 's|@''REPLACE_LOGL''@|$(REPLACE_LOGL)|g' \
-	      -e 's|@''REPLACE_LOG10''@|$(REPLACE_LOG10)|g' \
-	      -e 's|@''REPLACE_LOG10F''@|$(REPLACE_LOG10F)|g' \
-	      -e 's|@''REPLACE_LOG10L''@|$(REPLACE_LOG10L)|g' \
-	      -e 's|@''REPLACE_LOG1P''@|$(REPLACE_LOG1P)|g' \
-	      -e 's|@''REPLACE_LOG1PF''@|$(REPLACE_LOG1PF)|g' \
-	      -e 's|@''REPLACE_LOG1PL''@|$(REPLACE_LOG1PL)|g' \
-	      -e 's|@''REPLACE_LOG2''@|$(REPLACE_LOG2)|g' \
-	      -e 's|@''REPLACE_LOG2F''@|$(REPLACE_LOG2F)|g' \
-	      -e 's|@''REPLACE_LOG2L''@|$(REPLACE_LOG2L)|g' \
-	      -e 's|@''REPLACE_LOGB''@|$(REPLACE_LOGB)|g' \
-	      -e 's|@''REPLACE_LOGBF''@|$(REPLACE_LOGBF)|g' \
-	      -e 's|@''REPLACE_LOGBL''@|$(REPLACE_LOGBL)|g' \
-	      -e 's|@''REPLACE_MODF''@|$(REPLACE_MODF)|g' \
-	      -e 's|@''REPLACE_MODFF''@|$(REPLACE_MODFF)|g' \
-	      -e 's|@''REPLACE_MODFL''@|$(REPLACE_MODFL)|g' \
-	      -e 's|@''REPLACE_NAN''@|$(REPLACE_NAN)|g' \
-	      -e 's|@''REPLACE_REMAINDER''@|$(REPLACE_REMAINDER)|g' \
-	      -e 's|@''REPLACE_REMAINDERF''@|$(REPLACE_REMAINDERF)|g' \
-	      -e 's|@''REPLACE_REMAINDERL''@|$(REPLACE_REMAINDERL)|g' \
-	      -e 's|@''REPLACE_ROUND''@|$(REPLACE_ROUND)|g' \
-	      -e 's|@''REPLACE_ROUNDF''@|$(REPLACE_ROUNDF)|g' \
-	      -e 's|@''REPLACE_ROUNDL''@|$(REPLACE_ROUNDL)|g' \
-	      -e 's|@''REPLACE_SIGNBIT''@|$(REPLACE_SIGNBIT)|g' \
-	      -e 's|@''REPLACE_SIGNBIT_USING_GCC''@|$(REPLACE_SIGNBIT_USING_GCC)|g' \
-	      -e 's|@''REPLACE_SQRTL''@|$(REPLACE_SQRTL)|g' \
-	      -e 's|@''REPLACE_TRUNC''@|$(REPLACE_TRUNC)|g' \
-	      -e 's|@''REPLACE_TRUNCF''@|$(REPLACE_TRUNCF)|g' \
-	      -e 's|@''REPLACE_TRUNCL''@|$(REPLACE_TRUNCL)|g' \
-	      -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
-	      -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
-	      -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)'; \
-	} > $@-t && \
-	mv $@-t $@
-MOSTLYCLEANFILES += math.h math.h-t
-
-EXTRA_DIST += math.in.h
-
-## end   gnulib module math
-
-## begin gnulib module mbrtowc
-
-
-EXTRA_DIST += mbrtowc.c
-
-EXTRA_libgnu_la_SOURCES += mbrtowc.c
-
-## end   gnulib module mbrtowc
-
-## begin gnulib module mbsinit
-
-
-EXTRA_DIST += mbsinit.c
-
-EXTRA_libgnu_la_SOURCES += mbsinit.c
-
-## end   gnulib module mbsinit
-
-## begin gnulib module mbsrtowcs
-
-
-EXTRA_DIST += mbsrtowcs-impl.h mbsrtowcs-state.c mbsrtowcs.c
-
-EXTRA_libgnu_la_SOURCES += mbsrtowcs-state.c mbsrtowcs.c
-
-## end   gnulib module mbsrtowcs
-
-## begin gnulib module memchr
-
-
-EXTRA_DIST += memchr.c memchr.valgrind
-
-EXTRA_libgnu_la_SOURCES += memchr.c
-
-## end   gnulib module memchr
-
-## begin gnulib module mempcpy
-
-
-EXTRA_DIST += mempcpy.c
-
-EXTRA_libgnu_la_SOURCES += mempcpy.c
-
-## end   gnulib module mempcpy
-
-## begin gnulib module memrchr
-
-
-EXTRA_DIST += memrchr.c
-
-EXTRA_libgnu_la_SOURCES += memrchr.c
-
-## end   gnulib module memrchr
-
-## begin gnulib module mkdir
-
-
-EXTRA_DIST += mkdir.c
-
-EXTRA_libgnu_la_SOURCES += mkdir.c
-
-## end   gnulib module mkdir
-
-## begin gnulib module mkfifo
-
-
-EXTRA_DIST += mkfifo.c
-
-EXTRA_libgnu_la_SOURCES += mkfifo.c
-
-## end   gnulib module mkfifo
-
-## begin gnulib module mkostemp
-
-
-EXTRA_DIST += mkostemp.c
-
-EXTRA_libgnu_la_SOURCES += mkostemp.c
-
-## end   gnulib module mkostemp
-
-## begin gnulib module mktime
-
-
-EXTRA_DIST += mktime-internal.h mktime.c
-
-EXTRA_libgnu_la_SOURCES += mktime.c
-
-## end   gnulib module mktime
-
-## begin gnulib module msvc-inval
-
-
-EXTRA_DIST += msvc-inval.c msvc-inval.h
-
-EXTRA_libgnu_la_SOURCES += msvc-inval.c
-
-## end   gnulib module msvc-inval
-
-## begin gnulib module msvc-nothrow
-
-
-EXTRA_DIST += msvc-nothrow.c msvc-nothrow.h
-
-EXTRA_libgnu_la_SOURCES += msvc-nothrow.c
-
-## end   gnulib module msvc-nothrow
-
-## begin gnulib module nanosleep
-
-
-EXTRA_DIST += nanosleep.c
-
-EXTRA_libgnu_la_SOURCES += nanosleep.c
-
-## end   gnulib module nanosleep
-
-## begin gnulib module nproc
-
-libgnu_la_SOURCES += nproc.c
-
-EXTRA_DIST += nproc.h
-
-## end   gnulib module nproc
-
-## begin gnulib module open
-
-
-EXTRA_DIST += open.c
-
-EXTRA_libgnu_la_SOURCES += open.c
-
-## end   gnulib module open
-
-## begin gnulib module openat
-
-
-EXTRA_DIST += openat-priv.h openat.c
-
-EXTRA_libgnu_la_SOURCES += openat.c
-
-## end   gnulib module openat
-
-## begin gnulib module openat-die
-
-libgnu_la_SOURCES += openat-die.c
-
-## end   gnulib module openat-die
-
-## begin gnulib module openat-h
-
-
-EXTRA_DIST += openat.h
-
-## end   gnulib module openat-h
-
-## begin gnulib module opendir
-
-
-EXTRA_DIST += dirent-private.h opendir.c
-
-EXTRA_libgnu_la_SOURCES += opendir.c
-
-## end   gnulib module opendir
-
-## begin gnulib module pathmax
-
-
-EXTRA_DIST += pathmax.h
-
-## end   gnulib module pathmax
-
-## begin gnulib module progname
-
-libgnu_la_SOURCES += progname.h progname.c
-
-## end   gnulib module progname
-
-## begin gnulib module putenv
-
-
-EXTRA_DIST += putenv.c
-
-EXTRA_libgnu_la_SOURCES += putenv.c
-
-## end   gnulib module putenv
-
-## begin gnulib module raise
-
-
-EXTRA_DIST += raise.c
-
-EXTRA_libgnu_la_SOURCES += raise.c
-
-## end   gnulib module raise
-
-## begin gnulib module readdir
-
-
-EXTRA_DIST += dirent-private.h readdir.c
-
-EXTRA_libgnu_la_SOURCES += readdir.c
-
-## end   gnulib module readdir
-
-## begin gnulib module readlink
-
-
-EXTRA_DIST += readlink.c
-
-EXTRA_libgnu_la_SOURCES += readlink.c
-
-## end   gnulib module readlink
-
-## begin gnulib module realloc-gnu
-
-
-EXTRA_DIST += realloc.c
-
-EXTRA_libgnu_la_SOURCES += realloc.c
-
-## end   gnulib module realloc-gnu
-
-## begin gnulib module realloc-posix
-
-
-EXTRA_DIST += realloc.c
-
-EXTRA_libgnu_la_SOURCES += realloc.c
-
-## end   gnulib module realloc-posix
-
-## begin gnulib module rename
-
-
-EXTRA_DIST += rename.c
-
-EXTRA_libgnu_la_SOURCES += rename.c
-
-## end   gnulib module rename
-
-## begin gnulib module rewinddir
-
-
-EXTRA_DIST += dirent-private.h rewinddir.c
-
-EXTRA_libgnu_la_SOURCES += rewinddir.c
-
-## end   gnulib module rewinddir
-
-## begin gnulib module rmdir
-
-
-EXTRA_DIST += rmdir.c
-
-EXTRA_libgnu_la_SOURCES += rmdir.c
-
-## end   gnulib module rmdir
-
-## begin gnulib module round
-
-
-EXTRA_DIST += round.c
-
-EXTRA_libgnu_la_SOURCES += round.c
-
-## end   gnulib module round
-
-## begin gnulib module roundf
-
-
-EXTRA_DIST += round.c roundf.c
-
-EXTRA_libgnu_la_SOURCES += round.c roundf.c
-
-## end   gnulib module roundf
-
-## begin gnulib module same
-
-libgnu_la_SOURCES += same.c
-
-EXTRA_DIST += same.h
-
-## end   gnulib module same
-
-## begin gnulib module same-inode
-
-
-EXTRA_DIST += same-inode.h
-
-## end   gnulib module same-inode
-
-## begin gnulib module save-cwd
-
-libgnu_la_SOURCES += save-cwd.c
-
-EXTRA_DIST += save-cwd.h
-
-## end   gnulib module save-cwd
-
-## begin gnulib module select
-
-
-EXTRA_DIST += select.c
-
-EXTRA_libgnu_la_SOURCES += select.c
-
-## end   gnulib module select
-
-## begin gnulib module sigaction
-
-
-EXTRA_DIST += sig-handler.h sigaction.c
-
-EXTRA_libgnu_la_SOURCES += sigaction.c
-
-## end   gnulib module sigaction
-
-## begin gnulib module signal-h
-
-BUILT_SOURCES += signal.h
-
-# We need the following in order to create <signal.h> when the system
-# doesn't have a complete one.
-signal.h: signal.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_SIGNAL_H''@|$(NEXT_SIGNAL_H)|g' \
-	      -e 's|@''GNULIB_PTHREAD_SIGMASK''@|$(GNULIB_PTHREAD_SIGMASK)|g' \
-	      -e 's|@''GNULIB_RAISE''@|$(GNULIB_RAISE)|g' \
-	      -e 's/@''GNULIB_SIGNAL_H_SIGPIPE''@/$(GNULIB_SIGNAL_H_SIGPIPE)/g' \
-	      -e 's/@''GNULIB_SIGPROCMASK''@/$(GNULIB_SIGPROCMASK)/g' \
-	      -e 's/@''GNULIB_SIGACTION''@/$(GNULIB_SIGACTION)/g' \
-	      -e 's|@''HAVE_POSIX_SIGNALBLOCKING''@|$(HAVE_POSIX_SIGNALBLOCKING)|g' \
-	      -e 's|@''HAVE_PTHREAD_SIGMASK''@|$(HAVE_PTHREAD_SIGMASK)|g' \
-	      -e 's|@''HAVE_RAISE''@|$(HAVE_RAISE)|g' \
-	      -e 's|@''HAVE_SIGSET_T''@|$(HAVE_SIGSET_T)|g' \
-	      -e 's|@''HAVE_SIGINFO_T''@|$(HAVE_SIGINFO_T)|g' \
-	      -e 's|@''HAVE_SIGACTION''@|$(HAVE_SIGACTION)|g' \
-	      -e 's|@''HAVE_STRUCT_SIGACTION_SA_SIGACTION''@|$(HAVE_STRUCT_SIGACTION_SA_SIGACTION)|g' \
-	      -e 's|@''HAVE_TYPE_VOLATILE_SIG_ATOMIC_T''@|$(HAVE_TYPE_VOLATILE_SIG_ATOMIC_T)|g' \
-	      -e 's|@''HAVE_SIGHANDLER_T''@|$(HAVE_SIGHANDLER_T)|g' \
-	      -e 's|@''REPLACE_PTHREAD_SIGMASK''@|$(REPLACE_PTHREAD_SIGMASK)|g' \
-	      -e 's|@''REPLACE_RAISE''@|$(REPLACE_RAISE)|g' \
-	      -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
-	      -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
-	      -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
-	      < $(srcdir)/signal.in.h; \
-	} > $@-t && \
-	mv $@-t $@
-MOSTLYCLEANFILES += signal.h signal.h-t
-
-EXTRA_DIST += signal.in.h
-
-## end   gnulib module signal-h
-
-## begin gnulib module signbit
-
-
-EXTRA_DIST += float+.h signbitd.c signbitf.c signbitl.c
-
-EXTRA_libgnu_la_SOURCES += signbitd.c signbitf.c signbitl.c
-
-## end   gnulib module signbit
-
-## begin gnulib module sigprocmask
-
-
-EXTRA_DIST += sigprocmask.c
-
-EXTRA_libgnu_la_SOURCES += sigprocmask.c
-
-## end   gnulib module sigprocmask
-
-## begin gnulib module size_max
-
-libgnu_la_SOURCES += size_max.h
-
-## end   gnulib module size_max
-
-## begin gnulib module sleep
-
-
-EXTRA_DIST += sleep.c
-
-EXTRA_libgnu_la_SOURCES += sleep.c
-
-## end   gnulib module sleep
-
-## begin gnulib module snippet/_Noreturn
-
-# Because this Makefile snippet defines a variable used by other
-# gnulib Makefile snippets, it must be present in all Makefile.am that
-# need it. This is ensured by the applicability 'all' defined above.
-
-_NORETURN_H=$(top_srcdir)/build-aux/snippet/_Noreturn.h
-
-EXTRA_DIST += $(top_srcdir)/build-aux/snippet/_Noreturn.h
-
-## end   gnulib module snippet/_Noreturn
-
-## begin gnulib module snippet/arg-nonnull
-
-# The BUILT_SOURCES created by this Makefile snippet are not used via #include
-# statements but through direct file reference. Therefore this snippet must be
-# present in all Makefile.am that need it. This is ensured by the applicability
-# 'all' defined above.
-
-BUILT_SOURCES += arg-nonnull.h
-# The arg-nonnull.h that gets inserted into generated .h files is the same as
-# build-aux/snippet/arg-nonnull.h, except that it has the copyright header cut
-# off.
-arg-nonnull.h: $(top_srcdir)/build-aux/snippet/arg-nonnull.h
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	sed -n -e '/GL_ARG_NONNULL/,$$p' \
-	  < $(top_srcdir)/build-aux/snippet/arg-nonnull.h \
-	  > $@-t && \
-	mv $@-t $@
-MOSTLYCLEANFILES += arg-nonnull.h arg-nonnull.h-t
-
-ARG_NONNULL_H=arg-nonnull.h
-
-EXTRA_DIST += $(top_srcdir)/build-aux/snippet/arg-nonnull.h
-
-## end   gnulib module snippet/arg-nonnull
-
-## begin gnulib module snippet/c++defs
-
-# The BUILT_SOURCES created by this Makefile snippet are not used via #include
-# statements but through direct file reference. Therefore this snippet must be
-# present in all Makefile.am that need it. This is ensured by the applicability
-# 'all' defined above.
-
-BUILT_SOURCES += c++defs.h
-# The c++defs.h that gets inserted into generated .h files is the same as
-# build-aux/snippet/c++defs.h, except that it has the copyright header cut off.
-c++defs.h: $(top_srcdir)/build-aux/snippet/c++defs.h
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	sed -n -e '/_GL_CXXDEFS/,$$p' \
-	  < $(top_srcdir)/build-aux/snippet/c++defs.h \
-	  > $@-t && \
-	mv $@-t $@
-MOSTLYCLEANFILES += c++defs.h c++defs.h-t
-
-CXXDEFS_H=c++defs.h
-
-EXTRA_DIST += $(top_srcdir)/build-aux/snippet/c++defs.h
-
-## end   gnulib module snippet/c++defs
-
-## begin gnulib module snippet/unused-parameter
-
-# The BUILT_SOURCES created by this Makefile snippet are not used via #include
-# statements but through direct file reference. Therefore this snippet must be
-# present in all Makefile.am that need it. This is ensured by the applicability
-# 'all' defined above.
-
-BUILT_SOURCES += unused-parameter.h
-# The unused-parameter.h that gets inserted into generated .h files is the same
-# as build-aux/snippet/unused-parameter.h, except that it has the copyright
-# header cut off.
-unused-parameter.h: $(top_srcdir)/build-aux/snippet/unused-parameter.h
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	sed -n -e '/GL_UNUSED_PARAMETER/,$$p' \
-	  < $(top_srcdir)/build-aux/snippet/unused-parameter.h \
-	  > $@-t && \
-	mv $@-t $@
-MOSTLYCLEANFILES += unused-parameter.h unused-parameter.h-t
-
-UNUSED_PARAMETER_H=unused-parameter.h
-
-EXTRA_DIST += $(top_srcdir)/build-aux/snippet/unused-parameter.h
-
-## end   gnulib module snippet/unused-parameter
-
-## begin gnulib module snippet/warn-on-use
-
-BUILT_SOURCES += warn-on-use.h
-# The warn-on-use.h that gets inserted into generated .h files is the same as
-# build-aux/snippet/warn-on-use.h, except that it has the copyright header cut
-# off.
-warn-on-use.h: $(top_srcdir)/build-aux/snippet/warn-on-use.h
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	sed -n -e '/^.ifndef/,$$p' \
-	  < $(top_srcdir)/build-aux/snippet/warn-on-use.h \
-	  > $@-t && \
-	mv $@-t $@
-MOSTLYCLEANFILES += warn-on-use.h warn-on-use.h-t
-
-WARN_ON_USE_H=warn-on-use.h
-
-EXTRA_DIST += $(top_srcdir)/build-aux/snippet/warn-on-use.h
-
-## end   gnulib module snippet/warn-on-use
-
-## begin gnulib module sockets
-
-libgnu_la_SOURCES += sockets.h sockets.c
-
-EXTRA_DIST += w32sock.h
-
-## end   gnulib module sockets
-
-## begin gnulib module stat
-
-
-EXTRA_DIST += stat.c
-
-EXTRA_libgnu_la_SOURCES += stat.c
-
-## end   gnulib module stat
-
-## begin gnulib module stdalign
-
-BUILT_SOURCES += $(STDALIGN_H)
-
-# We need the following in order to create <stdalign.h> when the system
-# doesn't have one that works.
-if GL_GENERATE_STDALIGN_H
-stdalign.h: stdalign.in.h $(top_builddir)/config.status
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
-	  cat $(srcdir)/stdalign.in.h; \
-	} > $@-t && \
-	mv $@-t $@
-else
-stdalign.h: $(top_builddir)/config.status
-	rm -f $@
-endif
-MOSTLYCLEANFILES += stdalign.h stdalign.h-t
-
-EXTRA_DIST += stdalign.in.h
-
-## end   gnulib module stdalign
-
-## begin gnulib module stdbool
-
-BUILT_SOURCES += $(STDBOOL_H)
-
-# We need the following in order to create <stdbool.h> when the system
-# doesn't have one that works.
-if GL_GENERATE_STDBOOL_H
-stdbool.h: stdbool.in.h $(top_builddir)/config.status
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
-	  sed -e 's/@''HAVE__BOOL''@/$(HAVE__BOOL)/g' < $(srcdir)/stdbool.in.h; \
-	} > $@-t && \
-	mv $@-t $@
-else
-stdbool.h: $(top_builddir)/config.status
-	rm -f $@
-endif
-MOSTLYCLEANFILES += stdbool.h stdbool.h-t
-
-EXTRA_DIST += stdbool.in.h
-
-## end   gnulib module stdbool
-
-## begin gnulib module stddef
-
-BUILT_SOURCES += $(STDDEF_H)
-
-# We need the following in order to create <stddef.h> when the system
-# doesn't have one that works with the given compiler.
-if GL_GENERATE_STDDEF_H
-stddef.h: stddef.in.h $(top_builddir)/config.status
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_STDDEF_H''@|$(NEXT_STDDEF_H)|g' \
-	      -e 's|@''HAVE_WCHAR_T''@|$(HAVE_WCHAR_T)|g' \
-	      -e 's|@''REPLACE_NULL''@|$(REPLACE_NULL)|g' \
-	      < $(srcdir)/stddef.in.h; \
-	} > $@-t && \
-	mv $@-t $@
-else
-stddef.h: $(top_builddir)/config.status
-	rm -f $@
-endif
-MOSTLYCLEANFILES += stddef.h stddef.h-t
-
-EXTRA_DIST += stddef.in.h
-
-## end   gnulib module stddef
-
-## begin gnulib module stdint
-
-BUILT_SOURCES += $(STDINT_H)
-
-# We need the following in order to create <stdint.h> when the system
-# doesn't have one that works with the given compiler.
-if GL_GENERATE_STDINT_H
-stdint.h: stdint.in.h $(top_builddir)/config.status
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's/@''HAVE_STDINT_H''@/$(HAVE_STDINT_H)/g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_STDINT_H''@|$(NEXT_STDINT_H)|g' \
-	      -e 's/@''HAVE_SYS_TYPES_H''@/$(HAVE_SYS_TYPES_H)/g' \
-	      -e 's/@''HAVE_INTTYPES_H''@/$(HAVE_INTTYPES_H)/g' \
-	      -e 's/@''HAVE_SYS_INTTYPES_H''@/$(HAVE_SYS_INTTYPES_H)/g' \
-	      -e 's/@''HAVE_SYS_BITYPES_H''@/$(HAVE_SYS_BITYPES_H)/g' \
-	      -e 's/@''HAVE_WCHAR_H''@/$(HAVE_WCHAR_H)/g' \
-	      -e 's/@''HAVE_LONG_LONG_INT''@/$(HAVE_LONG_LONG_INT)/g' \
-	      -e 's/@''HAVE_UNSIGNED_LONG_LONG_INT''@/$(HAVE_UNSIGNED_LONG_LONG_INT)/g' \
-	      -e 's/@''APPLE_UNIVERSAL_BUILD''@/$(APPLE_UNIVERSAL_BUILD)/g' \
-	      -e 's/@''BITSIZEOF_PTRDIFF_T''@/$(BITSIZEOF_PTRDIFF_T)/g' \
-	      -e 's/@''PTRDIFF_T_SUFFIX''@/$(PTRDIFF_T_SUFFIX)/g' \
-	      -e 's/@''BITSIZEOF_SIG_ATOMIC_T''@/$(BITSIZEOF_SIG_ATOMIC_T)/g' \
-	      -e 's/@''HAVE_SIGNED_SIG_ATOMIC_T''@/$(HAVE_SIGNED_SIG_ATOMIC_T)/g' \
-	      -e 's/@''SIG_ATOMIC_T_SUFFIX''@/$(SIG_ATOMIC_T_SUFFIX)/g' \
-	      -e 's/@''BITSIZEOF_SIZE_T''@/$(BITSIZEOF_SIZE_T)/g' \
-	      -e 's/@''SIZE_T_SUFFIX''@/$(SIZE_T_SUFFIX)/g' \
-	      -e 's/@''BITSIZEOF_WCHAR_T''@/$(BITSIZEOF_WCHAR_T)/g' \
-	      -e 's/@''HAVE_SIGNED_WCHAR_T''@/$(HAVE_SIGNED_WCHAR_T)/g' \
-	      -e 's/@''WCHAR_T_SUFFIX''@/$(WCHAR_T_SUFFIX)/g' \
-	      -e 's/@''BITSIZEOF_WINT_T''@/$(BITSIZEOF_WINT_T)/g' \
-	      -e 's/@''HAVE_SIGNED_WINT_T''@/$(HAVE_SIGNED_WINT_T)/g' \
-	      -e 's/@''WINT_T_SUFFIX''@/$(WINT_T_SUFFIX)/g' \
-	      < $(srcdir)/stdint.in.h; \
-	} > $@-t && \
-	mv $@-t $@
-else
-stdint.h: $(top_builddir)/config.status
-	rm -f $@
-endif
-MOSTLYCLEANFILES += stdint.h stdint.h-t
-
-EXTRA_DIST += stdint.in.h
-
-## end   gnulib module stdint
-
-## begin gnulib module stdio
-
-BUILT_SOURCES += stdio.h
-
-# We need the following in order to create <stdio.h> when the system
-# doesn't have one that works with the given compiler.
-stdio.h: stdio.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_STDIO_H''@|$(NEXT_STDIO_H)|g' \
-	      -e 's/@''GNULIB_DPRINTF''@/$(GNULIB_DPRINTF)/g' \
-	      -e 's/@''GNULIB_FCLOSE''@/$(GNULIB_FCLOSE)/g' \
-	      -e 's/@''GNULIB_FDOPEN''@/$(GNULIB_FDOPEN)/g' \
-	      -e 's/@''GNULIB_FFLUSH''@/$(GNULIB_FFLUSH)/g' \
-	      -e 's/@''GNULIB_FGETC''@/$(GNULIB_FGETC)/g' \
-	      -e 's/@''GNULIB_FGETS''@/$(GNULIB_FGETS)/g' \
-	      -e 's/@''GNULIB_FOPEN''@/$(GNULIB_FOPEN)/g' \
-	      -e 's/@''GNULIB_FPRINTF''@/$(GNULIB_FPRINTF)/g' \
-	      -e 's/@''GNULIB_FPRINTF_POSIX''@/$(GNULIB_FPRINTF_POSIX)/g' \
-	      -e 's/@''GNULIB_FPURGE''@/$(GNULIB_FPURGE)/g' \
-	      -e 's/@''GNULIB_FPUTC''@/$(GNULIB_FPUTC)/g' \
-	      -e 's/@''GNULIB_FPUTS''@/$(GNULIB_FPUTS)/g' \
-	      -e 's/@''GNULIB_FREAD''@/$(GNULIB_FREAD)/g' \
-	      -e 's/@''GNULIB_FREOPEN''@/$(GNULIB_FREOPEN)/g' \
-	      -e 's/@''GNULIB_FSCANF''@/$(GNULIB_FSCANF)/g' \
-	      -e 's/@''GNULIB_FSEEK''@/$(GNULIB_FSEEK)/g' \
-	      -e 's/@''GNULIB_FSEEKO''@/$(GNULIB_FSEEKO)/g' \
-	      -e 's/@''GNULIB_FTELL''@/$(GNULIB_FTELL)/g' \
-	      -e 's/@''GNULIB_FTELLO''@/$(GNULIB_FTELLO)/g' \
-	      -e 's/@''GNULIB_FWRITE''@/$(GNULIB_FWRITE)/g' \
-	      -e 's/@''GNULIB_GETC''@/$(GNULIB_GETC)/g' \
-	      -e 's/@''GNULIB_GETCHAR''@/$(GNULIB_GETCHAR)/g' \
-	      -e 's/@''GNULIB_GETDELIM''@/$(GNULIB_GETDELIM)/g' \
-	      -e 's/@''GNULIB_GETLINE''@/$(GNULIB_GETLINE)/g' \
-	      -e 's/@''GNULIB_OBSTACK_PRINTF''@/$(GNULIB_OBSTACK_PRINTF)/g' \
-	      -e 's/@''GNULIB_OBSTACK_PRINTF_POSIX''@/$(GNULIB_OBSTACK_PRINTF_POSIX)/g' \
-	      -e 's/@''GNULIB_PCLOSE''@/$(GNULIB_PCLOSE)/g' \
-	      -e 's/@''GNULIB_PERROR''@/$(GNULIB_PERROR)/g' \
-	      -e 's/@''GNULIB_POPEN''@/$(GNULIB_POPEN)/g' \
-	      -e 's/@''GNULIB_PRINTF''@/$(GNULIB_PRINTF)/g' \
-	      -e 's/@''GNULIB_PRINTF_POSIX''@/$(GNULIB_PRINTF_POSIX)/g' \
-	      -e 's/@''GNULIB_PUTC''@/$(GNULIB_PUTC)/g' \
-	      -e 's/@''GNULIB_PUTCHAR''@/$(GNULIB_PUTCHAR)/g' \
-	      -e 's/@''GNULIB_PUTS''@/$(GNULIB_PUTS)/g' \
-	      -e 's/@''GNULIB_REMOVE''@/$(GNULIB_REMOVE)/g' \
-	      -e 's/@''GNULIB_RENAME''@/$(GNULIB_RENAME)/g' \
-	      -e 's/@''GNULIB_RENAMEAT''@/$(GNULIB_RENAMEAT)/g' \
-	      -e 's/@''GNULIB_SCANF''@/$(GNULIB_SCANF)/g' \
-	      -e 's/@''GNULIB_SNPRINTF''@/$(GNULIB_SNPRINTF)/g' \
-	      -e 's/@''GNULIB_SPRINTF_POSIX''@/$(GNULIB_SPRINTF_POSIX)/g' \
-	      -e 's/@''GNULIB_STDIO_H_NONBLOCKING''@/$(GNULIB_STDIO_H_NONBLOCKING)/g' \
-	      -e 's/@''GNULIB_STDIO_H_SIGPIPE''@/$(GNULIB_STDIO_H_SIGPIPE)/g' \
-	      -e 's/@''GNULIB_TMPFILE''@/$(GNULIB_TMPFILE)/g' \
-	      -e 's/@''GNULIB_VASPRINTF''@/$(GNULIB_VASPRINTF)/g' \
-	      -e 's/@''GNULIB_VDPRINTF''@/$(GNULIB_VDPRINTF)/g' \
-	      -e 's/@''GNULIB_VFPRINTF''@/$(GNULIB_VFPRINTF)/g' \
-	      -e 's/@''GNULIB_VFPRINTF_POSIX''@/$(GNULIB_VFPRINTF_POSIX)/g' \
-	      -e 's/@''GNULIB_VFSCANF''@/$(GNULIB_VFSCANF)/g' \
-	      -e 's/@''GNULIB_VSCANF''@/$(GNULIB_VSCANF)/g' \
-	      -e 's/@''GNULIB_VPRINTF''@/$(GNULIB_VPRINTF)/g' \
-	      -e 's/@''GNULIB_VPRINTF_POSIX''@/$(GNULIB_VPRINTF_POSIX)/g' \
-	      -e 's/@''GNULIB_VSNPRINTF''@/$(GNULIB_VSNPRINTF)/g' \
-	      -e 's/@''GNULIB_VSPRINTF_POSIX''@/$(GNULIB_VSPRINTF_POSIX)/g' \
-	      < $(srcdir)/stdio.in.h | \
-	  sed -e 's|@''HAVE_DECL_FPURGE''@|$(HAVE_DECL_FPURGE)|g' \
-	      -e 's|@''HAVE_DECL_FSEEKO''@|$(HAVE_DECL_FSEEKO)|g' \
-	      -e 's|@''HAVE_DECL_FTELLO''@|$(HAVE_DECL_FTELLO)|g' \
-	      -e 's|@''HAVE_DECL_GETDELIM''@|$(HAVE_DECL_GETDELIM)|g' \
-	      -e 's|@''HAVE_DECL_GETLINE''@|$(HAVE_DECL_GETLINE)|g' \
-	      -e 's|@''HAVE_DECL_OBSTACK_PRINTF''@|$(HAVE_DECL_OBSTACK_PRINTF)|g' \
-	      -e 's|@''HAVE_DECL_SNPRINTF''@|$(HAVE_DECL_SNPRINTF)|g' \
-	      -e 's|@''HAVE_DECL_VSNPRINTF''@|$(HAVE_DECL_VSNPRINTF)|g' \
-	      -e 's|@''HAVE_DPRINTF''@|$(HAVE_DPRINTF)|g' \
-	      -e 's|@''HAVE_FSEEKO''@|$(HAVE_FSEEKO)|g' \
-	      -e 's|@''HAVE_FTELLO''@|$(HAVE_FTELLO)|g' \
-	      -e 's|@''HAVE_PCLOSE''@|$(HAVE_PCLOSE)|g' \
-	      -e 's|@''HAVE_POPEN''@|$(HAVE_POPEN)|g' \
-	      -e 's|@''HAVE_RENAMEAT''@|$(HAVE_RENAMEAT)|g' \
-	      -e 's|@''HAVE_VASPRINTF''@|$(HAVE_VASPRINTF)|g' \
-	      -e 's|@''HAVE_VDPRINTF''@|$(HAVE_VDPRINTF)|g' \
-	      -e 's|@''REPLACE_DPRINTF''@|$(REPLACE_DPRINTF)|g' \
-	      -e 's|@''REPLACE_FCLOSE''@|$(REPLACE_FCLOSE)|g' \
-	      -e 's|@''REPLACE_FDOPEN''@|$(REPLACE_FDOPEN)|g' \
-	      -e 's|@''REPLACE_FFLUSH''@|$(REPLACE_FFLUSH)|g' \
-	      -e 's|@''REPLACE_FOPEN''@|$(REPLACE_FOPEN)|g' \
-	      -e 's|@''REPLACE_FPRINTF''@|$(REPLACE_FPRINTF)|g' \
-	      -e 's|@''REPLACE_FPURGE''@|$(REPLACE_FPURGE)|g' \
-	      -e 's|@''REPLACE_FREOPEN''@|$(REPLACE_FREOPEN)|g' \
-	      -e 's|@''REPLACE_FSEEK''@|$(REPLACE_FSEEK)|g' \
-	      -e 's|@''REPLACE_FSEEKO''@|$(REPLACE_FSEEKO)|g' \
-	      -e 's|@''REPLACE_FTELL''@|$(REPLACE_FTELL)|g' \
-	      -e 's|@''REPLACE_FTELLO''@|$(REPLACE_FTELLO)|g' \
-	      -e 's|@''REPLACE_GETDELIM''@|$(REPLACE_GETDELIM)|g' \
-	      -e 's|@''REPLACE_GETLINE''@|$(REPLACE_GETLINE)|g' \
-	      -e 's|@''REPLACE_OBSTACK_PRINTF''@|$(REPLACE_OBSTACK_PRINTF)|g' \
-	      -e 's|@''REPLACE_PERROR''@|$(REPLACE_PERROR)|g' \
-	      -e 's|@''REPLACE_POPEN''@|$(REPLACE_POPEN)|g' \
-	      -e 's|@''REPLACE_PRINTF''@|$(REPLACE_PRINTF)|g' \
-	      -e 's|@''REPLACE_REMOVE''@|$(REPLACE_REMOVE)|g' \
-	      -e 's|@''REPLACE_RENAME''@|$(REPLACE_RENAME)|g' \
-	      -e 's|@''REPLACE_RENAMEAT''@|$(REPLACE_RENAMEAT)|g' \
-	      -e 's|@''REPLACE_SNPRINTF''@|$(REPLACE_SNPRINTF)|g' \
-	      -e 's|@''REPLACE_SPRINTF''@|$(REPLACE_SPRINTF)|g' \
-	      -e 's|@''REPLACE_STDIO_READ_FUNCS''@|$(REPLACE_STDIO_READ_FUNCS)|g' \
-	      -e 's|@''REPLACE_STDIO_WRITE_FUNCS''@|$(REPLACE_STDIO_WRITE_FUNCS)|g' \
-	      -e 's|@''REPLACE_TMPFILE''@|$(REPLACE_TMPFILE)|g' \
-	      -e 's|@''REPLACE_VASPRINTF''@|$(REPLACE_VASPRINTF)|g' \
-	      -e 's|@''REPLACE_VDPRINTF''@|$(REPLACE_VDPRINTF)|g' \
-	      -e 's|@''REPLACE_VFPRINTF''@|$(REPLACE_VFPRINTF)|g' \
-	      -e 's|@''REPLACE_VPRINTF''@|$(REPLACE_VPRINTF)|g' \
-	      -e 's|@''REPLACE_VSNPRINTF''@|$(REPLACE_VSNPRINTF)|g' \
-	      -e 's|@''REPLACE_VSPRINTF''@|$(REPLACE_VSPRINTF)|g' \
-	      -e 's|@''ASM_SYMBOL_PREFIX''@|$(ASM_SYMBOL_PREFIX)|g' \
-	      -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
-	      -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
-	      -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)'; \
-	} > $@-t && \
-	mv $@-t $@
-MOSTLYCLEANFILES += stdio.h stdio.h-t
-
-EXTRA_DIST += stdio.in.h
-
-## end   gnulib module stdio
-
-## begin gnulib module stdlib
-
-BUILT_SOURCES += stdlib.h
-
-# We need the following in order to create <stdlib.h> when the system
-# doesn't have one that works with the given compiler.
-stdlib.h: stdlib.in.h $(top_builddir)/config.status $(CXXDEFS_H) \
-  $(_NORETURN_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_STDLIB_H''@|$(NEXT_STDLIB_H)|g' \
-	      -e 's/@''GNULIB__EXIT''@/$(GNULIB__EXIT)/g' \
-	      -e 's/@''GNULIB_ATOLL''@/$(GNULIB_ATOLL)/g' \
-	      -e 's/@''GNULIB_CALLOC_POSIX''@/$(GNULIB_CALLOC_POSIX)/g' \
-	      -e 's/@''GNULIB_CANONICALIZE_FILE_NAME''@/$(GNULIB_CANONICALIZE_FILE_NAME)/g' \
-	      -e 's/@''GNULIB_GETLOADAVG''@/$(GNULIB_GETLOADAVG)/g' \
-	      -e 's/@''GNULIB_GETSUBOPT''@/$(GNULIB_GETSUBOPT)/g' \
-	      -e 's/@''GNULIB_GRANTPT''@/$(GNULIB_GRANTPT)/g' \
-	      -e 's/@''GNULIB_MALLOC_POSIX''@/$(GNULIB_MALLOC_POSIX)/g' \
-	      -e 's/@''GNULIB_MBTOWC''@/$(GNULIB_MBTOWC)/g' \
-	      -e 's/@''GNULIB_MKDTEMP''@/$(GNULIB_MKDTEMP)/g' \
-	      -e 's/@''GNULIB_MKOSTEMP''@/$(GNULIB_MKOSTEMP)/g' \
-	      -e 's/@''GNULIB_MKOSTEMPS''@/$(GNULIB_MKOSTEMPS)/g' \
-	      -e 's/@''GNULIB_MKSTEMP''@/$(GNULIB_MKSTEMP)/g' \
-	      -e 's/@''GNULIB_MKSTEMPS''@/$(GNULIB_MKSTEMPS)/g' \
-	      -e 's/@''GNULIB_POSIX_OPENPT''@/$(GNULIB_POSIX_OPENPT)/g' \
-	      -e 's/@''GNULIB_PTSNAME''@/$(GNULIB_PTSNAME)/g' \
-	      -e 's/@''GNULIB_PTSNAME_R''@/$(GNULIB_PTSNAME_R)/g' \
-	      -e 's/@''GNULIB_PUTENV''@/$(GNULIB_PUTENV)/g' \
-	      -e 's/@''GNULIB_RANDOM''@/$(GNULIB_RANDOM)/g' \
-	      -e 's/@''GNULIB_RANDOM_R''@/$(GNULIB_RANDOM_R)/g' \
-	      -e 's/@''GNULIB_REALLOC_POSIX''@/$(GNULIB_REALLOC_POSIX)/g' \
-	      -e 's/@''GNULIB_REALPATH''@/$(GNULIB_REALPATH)/g' \
-	      -e 's/@''GNULIB_RPMATCH''@/$(GNULIB_RPMATCH)/g' \
-	      -e 's/@''GNULIB_SETENV''@/$(GNULIB_SETENV)/g' \
-	      -e 's/@''GNULIB_STRTOD''@/$(GNULIB_STRTOD)/g' \
-	      -e 's/@''GNULIB_STRTOLL''@/$(GNULIB_STRTOLL)/g' \
-	      -e 's/@''GNULIB_STRTOULL''@/$(GNULIB_STRTOULL)/g' \
-	      -e 's/@''GNULIB_SYSTEM_POSIX''@/$(GNULIB_SYSTEM_POSIX)/g' \
-	      -e 's/@''GNULIB_UNLOCKPT''@/$(GNULIB_UNLOCKPT)/g' \
-	      -e 's/@''GNULIB_UNSETENV''@/$(GNULIB_UNSETENV)/g' \
-	      -e 's/@''GNULIB_WCTOMB''@/$(GNULIB_WCTOMB)/g' \
-	      < $(srcdir)/stdlib.in.h | \
-	  sed -e 's|@''HAVE__EXIT''@|$(HAVE__EXIT)|g' \
-	      -e 's|@''HAVE_ATOLL''@|$(HAVE_ATOLL)|g' \
-	      -e 's|@''HAVE_CANONICALIZE_FILE_NAME''@|$(HAVE_CANONICALIZE_FILE_NAME)|g' \
-	      -e 's|@''HAVE_DECL_GETLOADAVG''@|$(HAVE_DECL_GETLOADAVG)|g' \
-	      -e 's|@''HAVE_GETSUBOPT''@|$(HAVE_GETSUBOPT)|g' \
-	      -e 's|@''HAVE_GRANTPT''@|$(HAVE_GRANTPT)|g' \
-	      -e 's|@''HAVE_MKDTEMP''@|$(HAVE_MKDTEMP)|g' \
-	      -e 's|@''HAVE_MKOSTEMP''@|$(HAVE_MKOSTEMP)|g' \
-	      -e 's|@''HAVE_MKOSTEMPS''@|$(HAVE_MKOSTEMPS)|g' \
-	      -e 's|@''HAVE_MKSTEMP''@|$(HAVE_MKSTEMP)|g' \
-	      -e 's|@''HAVE_MKSTEMPS''@|$(HAVE_MKSTEMPS)|g' \
-	      -e 's|@''HAVE_POSIX_OPENPT''@|$(HAVE_POSIX_OPENPT)|g' \
-	      -e 's|@''HAVE_PTSNAME''@|$(HAVE_PTSNAME)|g' \
-	      -e 's|@''HAVE_PTSNAME_R''@|$(HAVE_PTSNAME_R)|g' \
-	      -e 's|@''HAVE_RANDOM''@|$(HAVE_RANDOM)|g' \
-	      -e 's|@''HAVE_RANDOM_H''@|$(HAVE_RANDOM_H)|g' \
-	      -e 's|@''HAVE_RANDOM_R''@|$(HAVE_RANDOM_R)|g' \
-	      -e 's|@''HAVE_REALPATH''@|$(HAVE_REALPATH)|g' \
-	      -e 's|@''HAVE_RPMATCH''@|$(HAVE_RPMATCH)|g' \
-	      -e 's|@''HAVE_DECL_SETENV''@|$(HAVE_DECL_SETENV)|g' \
-	      -e 's|@''HAVE_STRTOD''@|$(HAVE_STRTOD)|g' \
-	      -e 's|@''HAVE_STRTOLL''@|$(HAVE_STRTOLL)|g' \
-	      -e 's|@''HAVE_STRTOULL''@|$(HAVE_STRTOULL)|g' \
-	      -e 's|@''HAVE_STRUCT_RANDOM_DATA''@|$(HAVE_STRUCT_RANDOM_DATA)|g' \
-	      -e 's|@''HAVE_SYS_LOADAVG_H''@|$(HAVE_SYS_LOADAVG_H)|g' \
-	      -e 's|@''HAVE_UNLOCKPT''@|$(HAVE_UNLOCKPT)|g' \
-	      -e 's|@''HAVE_DECL_UNSETENV''@|$(HAVE_DECL_UNSETENV)|g' \
-	      -e 's|@''REPLACE_CALLOC''@|$(REPLACE_CALLOC)|g' \
-	      -e 's|@''REPLACE_CANONICALIZE_FILE_NAME''@|$(REPLACE_CANONICALIZE_FILE_NAME)|g' \
-	      -e 's|@''REPLACE_MALLOC''@|$(REPLACE_MALLOC)|g' \
-	      -e 's|@''REPLACE_MBTOWC''@|$(REPLACE_MBTOWC)|g' \
-	      -e 's|@''REPLACE_MKSTEMP''@|$(REPLACE_MKSTEMP)|g' \
-	      -e 's|@''REPLACE_PTSNAME_R''@|$(REPLACE_PTSNAME_R)|g' \
-	      -e 's|@''REPLACE_PUTENV''@|$(REPLACE_PUTENV)|g' \
-	      -e 's|@''REPLACE_RANDOM_R''@|$(REPLACE_RANDOM_R)|g' \
-	      -e 's|@''REPLACE_REALLOC''@|$(REPLACE_REALLOC)|g' \
-	      -e 's|@''REPLACE_REALPATH''@|$(REPLACE_REALPATH)|g' \
-	      -e 's|@''REPLACE_SETENV''@|$(REPLACE_SETENV)|g' \
-	      -e 's|@''REPLACE_STRTOD''@|$(REPLACE_STRTOD)|g' \
-	      -e 's|@''REPLACE_UNSETENV''@|$(REPLACE_UNSETENV)|g' \
-	      -e 's|@''REPLACE_WCTOMB''@|$(REPLACE_WCTOMB)|g' \
-	      -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
-	      -e '/definition of _Noreturn/r $(_NORETURN_H)' \
-	      -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
-	      -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)'; \
-	} > $@-t && \
-	mv $@-t $@
-MOSTLYCLEANFILES += stdlib.h stdlib.h-t
-
-EXTRA_DIST += stdlib.in.h
-
-## end   gnulib module stdlib
-
-## begin gnulib module strcase
-
-
-EXTRA_DIST += strcasecmp.c strncasecmp.c
-
-EXTRA_libgnu_la_SOURCES += strcasecmp.c strncasecmp.c
-
-## end   gnulib module strcase
-
-## begin gnulib module strdup-posix
-
-
-EXTRA_DIST += strdup.c
-
-EXTRA_libgnu_la_SOURCES += strdup.c
-
-## end   gnulib module strdup-posix
-
-## begin gnulib module streq
-
-
-EXTRA_DIST += streq.h
-
-## end   gnulib module streq
-
-## begin gnulib module strerror
-
-
-EXTRA_DIST += strerror.c
-
-EXTRA_libgnu_la_SOURCES += strerror.c
-
-## end   gnulib module strerror
-
-## begin gnulib module strerror-override
-
-
-EXTRA_DIST += strerror-override.c strerror-override.h
-
-EXTRA_libgnu_la_SOURCES += strerror-override.c
-
-## end   gnulib module strerror-override
-
-## begin gnulib module strftime
-
-libgnu_la_SOURCES += strftime.c
-
-EXTRA_DIST += strftime.h
-
-## end   gnulib module strftime
-
-## begin gnulib module string
-
-BUILT_SOURCES += string.h
-
-# We need the following in order to create <string.h> when the system
-# doesn't have one that works with the given compiler.
-string.h: string.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_STRING_H''@|$(NEXT_STRING_H)|g' \
-	      -e 's/@''GNULIB_FFSL''@/$(GNULIB_FFSL)/g' \
-	      -e 's/@''GNULIB_FFSLL''@/$(GNULIB_FFSLL)/g' \
-	      -e 's/@''GNULIB_MBSLEN''@/$(GNULIB_MBSLEN)/g' \
-	      -e 's/@''GNULIB_MBSNLEN''@/$(GNULIB_MBSNLEN)/g' \
-	      -e 's/@''GNULIB_MBSCHR''@/$(GNULIB_MBSCHR)/g' \
-	      -e 's/@''GNULIB_MBSRCHR''@/$(GNULIB_MBSRCHR)/g' \
-	      -e 's/@''GNULIB_MBSSTR''@/$(GNULIB_MBSSTR)/g' \
-	      -e 's/@''GNULIB_MBSCASECMP''@/$(GNULIB_MBSCASECMP)/g' \
-	      -e 's/@''GNULIB_MBSNCASECMP''@/$(GNULIB_MBSNCASECMP)/g' \
-	      -e 's/@''GNULIB_MBSPCASECMP''@/$(GNULIB_MBSPCASECMP)/g' \
-	      -e 's/@''GNULIB_MBSCASESTR''@/$(GNULIB_MBSCASESTR)/g' \
-	      -e 's/@''GNULIB_MBSCSPN''@/$(GNULIB_MBSCSPN)/g' \
-	      -e 's/@''GNULIB_MBSPBRK''@/$(GNULIB_MBSPBRK)/g' \
-	      -e 's/@''GNULIB_MBSSPN''@/$(GNULIB_MBSSPN)/g' \
-	      -e 's/@''GNULIB_MBSSEP''@/$(GNULIB_MBSSEP)/g' \
-	      -e 's/@''GNULIB_MBSTOK_R''@/$(GNULIB_MBSTOK_R)/g' \
-	      -e 's/@''GNULIB_MEMCHR''@/$(GNULIB_MEMCHR)/g' \
-	      -e 's/@''GNULIB_MEMMEM''@/$(GNULIB_MEMMEM)/g' \
-	      -e 's/@''GNULIB_MEMPCPY''@/$(GNULIB_MEMPCPY)/g' \
-	      -e 's/@''GNULIB_MEMRCHR''@/$(GNULIB_MEMRCHR)/g' \
-	      -e 's/@''GNULIB_RAWMEMCHR''@/$(GNULIB_RAWMEMCHR)/g' \
-	      -e 's/@''GNULIB_STPCPY''@/$(GNULIB_STPCPY)/g' \
-	      -e 's/@''GNULIB_STPNCPY''@/$(GNULIB_STPNCPY)/g' \
-	      -e 's/@''GNULIB_STRCHRNUL''@/$(GNULIB_STRCHRNUL)/g' \
-	      -e 's/@''GNULIB_STRDUP''@/$(GNULIB_STRDUP)/g' \
-	      -e 's/@''GNULIB_STRNCAT''@/$(GNULIB_STRNCAT)/g' \
-	      -e 's/@''GNULIB_STRNDUP''@/$(GNULIB_STRNDUP)/g' \
-	      -e 's/@''GNULIB_STRNLEN''@/$(GNULIB_STRNLEN)/g' \
-	      -e 's/@''GNULIB_STRPBRK''@/$(GNULIB_STRPBRK)/g' \
-	      -e 's/@''GNULIB_STRSEP''@/$(GNULIB_STRSEP)/g' \
-	      -e 's/@''GNULIB_STRSTR''@/$(GNULIB_STRSTR)/g' \
-	      -e 's/@''GNULIB_STRCASESTR''@/$(GNULIB_STRCASESTR)/g' \
-	      -e 's/@''GNULIB_STRTOK_R''@/$(GNULIB_STRTOK_R)/g' \
-	      -e 's/@''GNULIB_STRERROR''@/$(GNULIB_STRERROR)/g' \
-	      -e 's/@''GNULIB_STRERROR_R''@/$(GNULIB_STRERROR_R)/g' \
-	      -e 's/@''GNULIB_STRSIGNAL''@/$(GNULIB_STRSIGNAL)/g' \
-	      -e 's/@''GNULIB_STRVERSCMP''@/$(GNULIB_STRVERSCMP)/g' \
-	      < $(srcdir)/string.in.h | \
-	  sed -e 's|@''HAVE_FFSL''@|$(HAVE_FFSL)|g' \
-	      -e 's|@''HAVE_FFSLL''@|$(HAVE_FFSLL)|g' \
-	      -e 's|@''HAVE_MBSLEN''@|$(HAVE_MBSLEN)|g' \
-	      -e 's|@''HAVE_MEMCHR''@|$(HAVE_MEMCHR)|g' \
-	      -e 's|@''HAVE_DECL_MEMMEM''@|$(HAVE_DECL_MEMMEM)|g' \
-	      -e 's|@''HAVE_MEMPCPY''@|$(HAVE_MEMPCPY)|g' \
-	      -e 's|@''HAVE_DECL_MEMRCHR''@|$(HAVE_DECL_MEMRCHR)|g' \
-	      -e 's|@''HAVE_RAWMEMCHR''@|$(HAVE_RAWMEMCHR)|g' \
-	      -e 's|@''HAVE_STPCPY''@|$(HAVE_STPCPY)|g' \
-	      -e 's|@''HAVE_STPNCPY''@|$(HAVE_STPNCPY)|g' \
-	      -e 's|@''HAVE_STRCHRNUL''@|$(HAVE_STRCHRNUL)|g' \
-	      -e 's|@''HAVE_DECL_STRDUP''@|$(HAVE_DECL_STRDUP)|g' \
-	      -e 's|@''HAVE_DECL_STRNDUP''@|$(HAVE_DECL_STRNDUP)|g' \
-	      -e 's|@''HAVE_DECL_STRNLEN''@|$(HAVE_DECL_STRNLEN)|g' \
-	      -e 's|@''HAVE_STRPBRK''@|$(HAVE_STRPBRK)|g' \
-	      -e 's|@''HAVE_STRSEP''@|$(HAVE_STRSEP)|g' \
-	      -e 's|@''HAVE_STRCASESTR''@|$(HAVE_STRCASESTR)|g' \
-	      -e 's|@''HAVE_DECL_STRTOK_R''@|$(HAVE_DECL_STRTOK_R)|g' \
-	      -e 's|@''HAVE_DECL_STRERROR_R''@|$(HAVE_DECL_STRERROR_R)|g' \
-	      -e 's|@''HAVE_DECL_STRSIGNAL''@|$(HAVE_DECL_STRSIGNAL)|g' \
-	      -e 's|@''HAVE_STRVERSCMP''@|$(HAVE_STRVERSCMP)|g' \
-	      -e 's|@''REPLACE_STPNCPY''@|$(REPLACE_STPNCPY)|g' \
-	      -e 's|@''REPLACE_MEMCHR''@|$(REPLACE_MEMCHR)|g' \
-	      -e 's|@''REPLACE_MEMMEM''@|$(REPLACE_MEMMEM)|g' \
-	      -e 's|@''REPLACE_STRCASESTR''@|$(REPLACE_STRCASESTR)|g' \
-	      -e 's|@''REPLACE_STRCHRNUL''@|$(REPLACE_STRCHRNUL)|g' \
-	      -e 's|@''REPLACE_STRDUP''@|$(REPLACE_STRDUP)|g' \
-	      -e 's|@''REPLACE_STRSTR''@|$(REPLACE_STRSTR)|g' \
-	      -e 's|@''REPLACE_STRERROR''@|$(REPLACE_STRERROR)|g' \
-	      -e 's|@''REPLACE_STRERROR_R''@|$(REPLACE_STRERROR_R)|g' \
-	      -e 's|@''REPLACE_STRNCAT''@|$(REPLACE_STRNCAT)|g' \
-	      -e 's|@''REPLACE_STRNDUP''@|$(REPLACE_STRNDUP)|g' \
-	      -e 's|@''REPLACE_STRNLEN''@|$(REPLACE_STRNLEN)|g' \
-	      -e 's|@''REPLACE_STRSIGNAL''@|$(REPLACE_STRSIGNAL)|g' \
-	      -e 's|@''REPLACE_STRTOK_R''@|$(REPLACE_STRTOK_R)|g' \
-	      -e 's|@''UNDEFINE_STRTOK_R''@|$(UNDEFINE_STRTOK_R)|g' \
-	      -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
-	      -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
-	      -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)'; \
-	      < $(srcdir)/string.in.h; \
-	} > $@-t && \
-	mv $@-t $@
-MOSTLYCLEANFILES += string.h string.h-t
-
-EXTRA_DIST += string.in.h
-
-## end   gnulib module string
-
-## begin gnulib module strings
-
-BUILT_SOURCES += strings.h
-
-# We need the following in order to create <strings.h> when the system
-# doesn't have one that works with the given compiler.
-strings.h: strings.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(WARN_ON_USE_H) $(ARG_NONNULL_H)
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's|@''HAVE_STRINGS_H''@|$(HAVE_STRINGS_H)|g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_STRINGS_H''@|$(NEXT_STRINGS_H)|g' \
-	      -e 's|@''GNULIB_FFS''@|$(GNULIB_FFS)|g' \
-	      -e 's|@''HAVE_FFS''@|$(HAVE_FFS)|g' \
-	      -e 's|@''HAVE_STRCASECMP''@|$(HAVE_STRCASECMP)|g' \
-	      -e 's|@''HAVE_DECL_STRNCASECMP''@|$(HAVE_DECL_STRNCASECMP)|g' \
-	      -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
-	      -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
-	      -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
-	      < $(srcdir)/strings.in.h; \
-	} > $@-t && \
-	mv $@-t $@
-MOSTLYCLEANFILES += strings.h strings.h-t
-
-EXTRA_DIST += strings.in.h
-
-## end   gnulib module strings
-
-## begin gnulib module strndup
-
-
-EXTRA_DIST += strndup.c
-
-EXTRA_libgnu_la_SOURCES += strndup.c
-
-## end   gnulib module strndup
-
-## begin gnulib module strnlen
-
-
-EXTRA_DIST += strnlen.c
-
-EXTRA_libgnu_la_SOURCES += strnlen.c
-
-## end   gnulib module strnlen
-
-## begin gnulib module strnlen1
-
-libgnu_la_SOURCES += strnlen1.h strnlen1.c
-
-## end   gnulib module strnlen1
-
-## begin gnulib module strptime
-
-
-EXTRA_DIST += strptime.c
-
-EXTRA_libgnu_la_SOURCES += strptime.c
-
-## end   gnulib module strptime
-
-## begin gnulib module symlink
-
-
-EXTRA_DIST += symlink.c
-
-EXTRA_libgnu_la_SOURCES += symlink.c
-
-## end   gnulib module symlink
-
-## begin gnulib module sys_select
-
-BUILT_SOURCES += sys/select.h
-
-# We need the following in order to create <sys/select.h> when the system
-# doesn't have one that works with the given compiler.
-sys/select.h: sys_select.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(WARN_ON_USE_H)
-	$(AM_V_at)$(MKDIR_P) sys
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_SYS_SELECT_H''@|$(NEXT_SYS_SELECT_H)|g' \
-	      -e 's|@''HAVE_SYS_SELECT_H''@|$(HAVE_SYS_SELECT_H)|g' \
-	      -e 's/@''GNULIB_PSELECT''@/$(GNULIB_PSELECT)/g' \
-	      -e 's/@''GNULIB_SELECT''@/$(GNULIB_SELECT)/g' \
-	      -e 's|@''HAVE_WINSOCK2_H''@|$(HAVE_WINSOCK2_H)|g' \
-	      -e 's|@''HAVE_PSELECT''@|$(HAVE_PSELECT)|g' \
-	      -e 's|@''REPLACE_PSELECT''@|$(REPLACE_PSELECT)|g' \
-	      -e 's|@''REPLACE_SELECT''@|$(REPLACE_SELECT)|g' \
-	      -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
-	      -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
-	      < $(srcdir)/sys_select.in.h; \
-	} > $@-t && \
-	mv $@-t $@
-MOSTLYCLEANFILES += sys/select.h sys/select.h-t
-MOSTLYCLEANDIRS += sys
-
-EXTRA_DIST += sys_select.in.h
-
-## end   gnulib module sys_select
-
-## begin gnulib module sys_socket
-
-BUILT_SOURCES += sys/socket.h
-
-# We need the following in order to create <sys/socket.h> when the system
-# doesn't have one that works with the given compiler.
-sys/socket.h: sys_socket.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(WARN_ON_USE_H) $(ARG_NONNULL_H)
-	$(AM_V_at)$(MKDIR_P) sys
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_SYS_SOCKET_H''@|$(NEXT_SYS_SOCKET_H)|g' \
-	      -e 's|@''HAVE_SYS_SOCKET_H''@|$(HAVE_SYS_SOCKET_H)|g' \
-	      -e 's/@''GNULIB_CLOSE''@/$(GNULIB_CLOSE)/g' \
-	      -e 's/@''GNULIB_SOCKET''@/$(GNULIB_SOCKET)/g' \
-	      -e 's/@''GNULIB_CONNECT''@/$(GNULIB_CONNECT)/g' \
-	      -e 's/@''GNULIB_ACCEPT''@/$(GNULIB_ACCEPT)/g' \
-	      -e 's/@''GNULIB_BIND''@/$(GNULIB_BIND)/g' \
-	      -e 's/@''GNULIB_GETPEERNAME''@/$(GNULIB_GETPEERNAME)/g' \
-	      -e 's/@''GNULIB_GETSOCKNAME''@/$(GNULIB_GETSOCKNAME)/g' \
-	      -e 's/@''GNULIB_GETSOCKOPT''@/$(GNULIB_GETSOCKOPT)/g' \
-	      -e 's/@''GNULIB_LISTEN''@/$(GNULIB_LISTEN)/g' \
-	      -e 's/@''GNULIB_RECV''@/$(GNULIB_RECV)/g' \
-	      -e 's/@''GNULIB_SEND''@/$(GNULIB_SEND)/g' \
-	      -e 's/@''GNULIB_RECVFROM''@/$(GNULIB_RECVFROM)/g' \
-	      -e 's/@''GNULIB_SENDTO''@/$(GNULIB_SENDTO)/g' \
-	      -e 's/@''GNULIB_SETSOCKOPT''@/$(GNULIB_SETSOCKOPT)/g' \
-	      -e 's/@''GNULIB_SHUTDOWN''@/$(GNULIB_SHUTDOWN)/g' \
-	      -e 's/@''GNULIB_ACCEPT4''@/$(GNULIB_ACCEPT4)/g' \
-	      -e 's|@''HAVE_WINSOCK2_H''@|$(HAVE_WINSOCK2_H)|g' \
-	      -e 's|@''HAVE_WS2TCPIP_H''@|$(HAVE_WS2TCPIP_H)|g' \
-	      -e 's|@''HAVE_STRUCT_SOCKADDR_STORAGE''@|$(HAVE_STRUCT_SOCKADDR_STORAGE)|g' \
-	      -e 's|@''HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY''@|$(HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY)|g' \
-	      -e 's|@''HAVE_SA_FAMILY_T''@|$(HAVE_SA_FAMILY_T)|g' \
-	      -e 's|@''HAVE_ACCEPT4''@|$(HAVE_ACCEPT4)|g' \
-	      -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
-	      -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
-	      -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
-	      < $(srcdir)/sys_socket.in.h; \
-	} > $@-t && \
-	mv -f $@-t $@
-MOSTLYCLEANFILES += sys/socket.h sys/socket.h-t
-MOSTLYCLEANDIRS += sys
-
-EXTRA_DIST += sys_socket.in.h
-
-## end   gnulib module sys_socket
-
-## begin gnulib module sys_stat
-
-BUILT_SOURCES += sys/stat.h
-
-# We need the following in order to create <sys/stat.h> when the system
-# has one that is incomplete.
-sys/stat.h: sys_stat.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
-	$(AM_V_at)$(MKDIR_P) sys
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_SYS_STAT_H''@|$(NEXT_SYS_STAT_H)|g' \
-	      -e 's|@''WINDOWS_64_BIT_ST_SIZE''@|$(WINDOWS_64_BIT_ST_SIZE)|g' \
-	      -e 's/@''GNULIB_FCHMODAT''@/$(GNULIB_FCHMODAT)/g' \
-	      -e 's/@''GNULIB_FSTAT''@/$(GNULIB_FSTAT)/g' \
-	      -e 's/@''GNULIB_FSTATAT''@/$(GNULIB_FSTATAT)/g' \
-	      -e 's/@''GNULIB_FUTIMENS''@/$(GNULIB_FUTIMENS)/g' \
-	      -e 's/@''GNULIB_LCHMOD''@/$(GNULIB_LCHMOD)/g' \
-	      -e 's/@''GNULIB_LSTAT''@/$(GNULIB_LSTAT)/g' \
-	      -e 's/@''GNULIB_MKDIRAT''@/$(GNULIB_MKDIRAT)/g' \
-	      -e 's/@''GNULIB_MKFIFO''@/$(GNULIB_MKFIFO)/g' \
-	      -e 's/@''GNULIB_MKFIFOAT''@/$(GNULIB_MKFIFOAT)/g' \
-	      -e 's/@''GNULIB_MKNOD''@/$(GNULIB_MKNOD)/g' \
-	      -e 's/@''GNULIB_MKNODAT''@/$(GNULIB_MKNODAT)/g' \
-	      -e 's/@''GNULIB_STAT''@/$(GNULIB_STAT)/g' \
-	      -e 's/@''GNULIB_UTIMENSAT''@/$(GNULIB_UTIMENSAT)/g' \
-	      -e 's|@''HAVE_FCHMODAT''@|$(HAVE_FCHMODAT)|g' \
-	      -e 's|@''HAVE_FSTATAT''@|$(HAVE_FSTATAT)|g' \
-	      -e 's|@''HAVE_FUTIMENS''@|$(HAVE_FUTIMENS)|g' \
-	      -e 's|@''HAVE_LCHMOD''@|$(HAVE_LCHMOD)|g' \
-	      -e 's|@''HAVE_LSTAT''@|$(HAVE_LSTAT)|g' \
-	      -e 's|@''HAVE_MKDIRAT''@|$(HAVE_MKDIRAT)|g' \
-	      -e 's|@''HAVE_MKFIFO''@|$(HAVE_MKFIFO)|g' \
-	      -e 's|@''HAVE_MKFIFOAT''@|$(HAVE_MKFIFOAT)|g' \
-	      -e 's|@''HAVE_MKNOD''@|$(HAVE_MKNOD)|g' \
-	      -e 's|@''HAVE_MKNODAT''@|$(HAVE_MKNODAT)|g' \
-	      -e 's|@''HAVE_UTIMENSAT''@|$(HAVE_UTIMENSAT)|g' \
-	      -e 's|@''REPLACE_FSTAT''@|$(REPLACE_FSTAT)|g' \
-	      -e 's|@''REPLACE_FSTATAT''@|$(REPLACE_FSTATAT)|g' \
-	      -e 's|@''REPLACE_FUTIMENS''@|$(REPLACE_FUTIMENS)|g' \
-	      -e 's|@''REPLACE_LSTAT''@|$(REPLACE_LSTAT)|g' \
-	      -e 's|@''REPLACE_MKDIR''@|$(REPLACE_MKDIR)|g' \
-	      -e 's|@''REPLACE_MKFIFO''@|$(REPLACE_MKFIFO)|g' \
-	      -e 's|@''REPLACE_MKNOD''@|$(REPLACE_MKNOD)|g' \
-	      -e 's|@''REPLACE_STAT''@|$(REPLACE_STAT)|g' \
-	      -e 's|@''REPLACE_UTIMENSAT''@|$(REPLACE_UTIMENSAT)|g' \
-	      -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
-	      -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
-	      -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
-	      < $(srcdir)/sys_stat.in.h; \
-	} > $@-t && \
-	mv $@-t $@
-MOSTLYCLEANFILES += sys/stat.h sys/stat.h-t
-MOSTLYCLEANDIRS += sys
-
-EXTRA_DIST += sys_stat.in.h
-
-## end   gnulib module sys_stat
-
-## begin gnulib module sys_time
-
-BUILT_SOURCES += sys/time.h
-
-# We need the following in order to create <sys/time.h> when the system
-# doesn't have one that works with the given compiler.
-sys/time.h: sys_time.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
-	$(AM_V_at)$(MKDIR_P) sys
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's/@''HAVE_SYS_TIME_H''@/$(HAVE_SYS_TIME_H)/g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_SYS_TIME_H''@|$(NEXT_SYS_TIME_H)|g' \
-	      -e 's/@''GNULIB_GETTIMEOFDAY''@/$(GNULIB_GETTIMEOFDAY)/g' \
-	      -e 's|@''HAVE_WINSOCK2_H''@|$(HAVE_WINSOCK2_H)|g' \
-	      -e 's/@''HAVE_GETTIMEOFDAY''@/$(HAVE_GETTIMEOFDAY)/g' \
-	      -e 's/@''HAVE_STRUCT_TIMEVAL''@/$(HAVE_STRUCT_TIMEVAL)/g' \
-	      -e 's/@''REPLACE_GETTIMEOFDAY''@/$(REPLACE_GETTIMEOFDAY)/g' \
-	      -e 's/@''REPLACE_STRUCT_TIMEVAL''@/$(REPLACE_STRUCT_TIMEVAL)/g' \
-	      -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
-	      -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
-	      -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
-	      < $(srcdir)/sys_time.in.h; \
-	} > $@-t && \
-	mv $@-t $@
-MOSTLYCLEANFILES += sys/time.h sys/time.h-t
-
-EXTRA_DIST += sys_time.in.h
-
-## end   gnulib module sys_time
-
-## begin gnulib module sys_times
-
-BUILT_SOURCES += sys/times.h
-
-# We need the following in order to create <sys/times.h> when the system
-# doesn't have one that works with the given compiler.
-sys/times.h: sys_times.in.h $(top_builddir)/config.status $(WARN_ON_USE_H) $(ARG_NONNULL_H)
-	$(AM_V_at)$(MKDIR_P) sys
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's/@''HAVE_SYS_TIMES_H''@/$(HAVE_SYS_TIMES_H)/g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_SYS_TIMES_H''@|$(NEXT_SYS_TIMES_H)|g' \
-	      -e 's/@''GNULIB_TIMES''@/$(GNULIB_TIMES)/g' \
-	      -e 's|@''HAVE_STRUCT_TMS''@|$(HAVE_STRUCT_TMS)|g' \
-	      -e 's|@''HAVE_TIMES''@|$(HAVE_TIMES)|g' \
-	      -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
-	      -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
-	      < $(srcdir)/sys_times.in.h; \
-	} > $@-t && \
-	mv $@-t $@
-MOSTLYCLEANFILES += sys/times.h sys/times.h-t
-MOSTLYCLEANDIRS += sys
-
-EXTRA_DIST += sys_times.in.h
-
-## end   gnulib module sys_times
-
-## begin gnulib module sys_types
-
-BUILT_SOURCES += sys/types.h
-
-# We need the following in order to create <sys/types.h> when the system
-# doesn't have one that works with the given compiler.
-sys/types.h: sys_types.in.h $(top_builddir)/config.status
-	$(AM_V_at)$(MKDIR_P) sys
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_SYS_TYPES_H''@|$(NEXT_SYS_TYPES_H)|g' \
-	      -e 's|@''WINDOWS_64_BIT_OFF_T''@|$(WINDOWS_64_BIT_OFF_T)|g' \
-	      < $(srcdir)/sys_types.in.h; \
-	} > $@-t && \
-	mv $@-t $@
-MOSTLYCLEANFILES += sys/types.h sys/types.h-t
-
-EXTRA_DIST += sys_types.in.h
-
-## end   gnulib module sys_types
-
-## begin gnulib module sys_uio
-
-BUILT_SOURCES += sys/uio.h
-
-# We need the following in order to create <sys/uio.h> when the system
-# doesn't have one that works with the given compiler.
-sys/uio.h: sys_uio.in.h $(top_builddir)/config.status
-	$(AM_V_at)$(MKDIR_P) sys
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_SYS_UIO_H''@|$(NEXT_SYS_UIO_H)|g' \
-	      -e 's|@''HAVE_SYS_UIO_H''@|$(HAVE_SYS_UIO_H)|g' \
-	      < $(srcdir)/sys_uio.in.h; \
-	} > $@-t && \
-	mv -f $@-t $@
-MOSTLYCLEANFILES += sys/uio.h sys/uio.h-t
-MOSTLYCLEANDIRS += sys
-
-EXTRA_DIST += sys_uio.in.h
-
-## end   gnulib module sys_uio
-
-## begin gnulib module tempname
-
-libgnu_la_SOURCES += tempname.c
-
-EXTRA_DIST += tempname.h
-
-## end   gnulib module tempname
-
-## begin gnulib module time
-
-BUILT_SOURCES += time.h
-
-# We need the following in order to create <time.h> when the system
-# doesn't have one that works with the given compiler.
-time.h: time.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */' && \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_TIME_H''@|$(NEXT_TIME_H)|g' \
-	      -e 's/@''GNULIB_MKTIME''@/$(GNULIB_MKTIME)/g' \
-	      -e 's/@''GNULIB_NANOSLEEP''@/$(GNULIB_NANOSLEEP)/g' \
-	      -e 's/@''GNULIB_STRPTIME''@/$(GNULIB_STRPTIME)/g' \
-	      -e 's/@''GNULIB_TIMEGM''@/$(GNULIB_TIMEGM)/g' \
-	      -e 's/@''GNULIB_TIME_R''@/$(GNULIB_TIME_R)/g' \
-	      -e 's|@''HAVE_DECL_LOCALTIME_R''@|$(HAVE_DECL_LOCALTIME_R)|g' \
-	      -e 's|@''HAVE_NANOSLEEP''@|$(HAVE_NANOSLEEP)|g' \
-	      -e 's|@''HAVE_STRPTIME''@|$(HAVE_STRPTIME)|g' \
-	      -e 's|@''HAVE_TIMEGM''@|$(HAVE_TIMEGM)|g' \
-	      -e 's|@''REPLACE_LOCALTIME_R''@|$(REPLACE_LOCALTIME_R)|g' \
-	      -e 's|@''REPLACE_MKTIME''@|$(REPLACE_MKTIME)|g' \
-	      -e 's|@''REPLACE_NANOSLEEP''@|$(REPLACE_NANOSLEEP)|g' \
-	      -e 's|@''REPLACE_TIMEGM''@|$(REPLACE_TIMEGM)|g' \
-	      -e 's|@''PTHREAD_H_DEFINES_STRUCT_TIMESPEC''@|$(PTHREAD_H_DEFINES_STRUCT_TIMESPEC)|g' \
-	      -e 's|@''SYS_TIME_H_DEFINES_STRUCT_TIMESPEC''@|$(SYS_TIME_H_DEFINES_STRUCT_TIMESPEC)|g' \
-	      -e 's|@''TIME_H_DEFINES_STRUCT_TIMESPEC''@|$(TIME_H_DEFINES_STRUCT_TIMESPEC)|g' \
-	      -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
-	      -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
-	      -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
-	      < $(srcdir)/time.in.h; \
-	} > $@-t && \
-	mv $@-t $@
-MOSTLYCLEANFILES += time.h time.h-t
-
-EXTRA_DIST += time.in.h
-
-## end   gnulib module time
-
-## begin gnulib module time_r
-
-
-EXTRA_DIST += time_r.c
-
-EXTRA_libgnu_la_SOURCES += time_r.c
-
-## end   gnulib module time_r
-
-## begin gnulib module times
-
-
-EXTRA_DIST += times.c
-
-EXTRA_libgnu_la_SOURCES += times.c
-
-## end   gnulib module times
-
-## begin gnulib module tmpdir
-
-libgnu_la_SOURCES += tmpdir.h tmpdir.c
-
-## end   gnulib module tmpdir
-
-## begin gnulib module tmpfile
-
-
-EXTRA_DIST += tmpfile.c
-
-EXTRA_libgnu_la_SOURCES += tmpfile.c
-
-## end   gnulib module tmpfile
-
-## begin gnulib module trunc
-
-
-EXTRA_DIST += trunc.c
-
-EXTRA_libgnu_la_SOURCES += trunc.c
-
-## end   gnulib module trunc
-
-## begin gnulib module truncf
-
-
-EXTRA_DIST += trunc.c truncf.c
-
-EXTRA_libgnu_la_SOURCES += trunc.c truncf.c
-
-## end   gnulib module truncf
-
-## begin gnulib module unistd
-
-BUILT_SOURCES += unistd.h
-
-# We need the following in order to create an empty placeholder for
-# <unistd.h> when the system doesn't have one.
-unistd.h: unistd.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's|@''HAVE_UNISTD_H''@|$(HAVE_UNISTD_H)|g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_UNISTD_H''@|$(NEXT_UNISTD_H)|g' \
-	      -e 's|@''WINDOWS_64_BIT_OFF_T''@|$(WINDOWS_64_BIT_OFF_T)|g' \
-	      -e 's/@''GNULIB_CHDIR''@/$(GNULIB_CHDIR)/g' \
-	      -e 's/@''GNULIB_CHOWN''@/$(GNULIB_CHOWN)/g' \
-	      -e 's/@''GNULIB_CLOSE''@/$(GNULIB_CLOSE)/g' \
-	      -e 's/@''GNULIB_DUP''@/$(GNULIB_DUP)/g' \
-	      -e 's/@''GNULIB_DUP2''@/$(GNULIB_DUP2)/g' \
-	      -e 's/@''GNULIB_DUP3''@/$(GNULIB_DUP3)/g' \
-	      -e 's/@''GNULIB_ENVIRON''@/$(GNULIB_ENVIRON)/g' \
-	      -e 's/@''GNULIB_EUIDACCESS''@/$(GNULIB_EUIDACCESS)/g' \
-	      -e 's/@''GNULIB_FACCESSAT''@/$(GNULIB_FACCESSAT)/g' \
-	      -e 's/@''GNULIB_FCHDIR''@/$(GNULIB_FCHDIR)/g' \
-	      -e 's/@''GNULIB_FCHOWNAT''@/$(GNULIB_FCHOWNAT)/g' \
-	      -e 's/@''GNULIB_FDATASYNC''@/$(GNULIB_FDATASYNC)/g' \
-	      -e 's/@''GNULIB_FSYNC''@/$(GNULIB_FSYNC)/g' \
-	      -e 's/@''GNULIB_FTRUNCATE''@/$(GNULIB_FTRUNCATE)/g' \
-	      -e 's/@''GNULIB_GETCWD''@/$(GNULIB_GETCWD)/g' \
-	      -e 's/@''GNULIB_GETDOMAINNAME''@/$(GNULIB_GETDOMAINNAME)/g' \
-	      -e 's/@''GNULIB_GETDTABLESIZE''@/$(GNULIB_GETDTABLESIZE)/g' \
-	      -e 's/@''GNULIB_GETGROUPS''@/$(GNULIB_GETGROUPS)/g' \
-	      -e 's/@''GNULIB_GETHOSTNAME''@/$(GNULIB_GETHOSTNAME)/g' \
-	      -e 's/@''GNULIB_GETLOGIN''@/$(GNULIB_GETLOGIN)/g' \
-	      -e 's/@''GNULIB_GETLOGIN_R''@/$(GNULIB_GETLOGIN_R)/g' \
-	      -e 's/@''GNULIB_GETPAGESIZE''@/$(GNULIB_GETPAGESIZE)/g' \
-	      -e 's/@''GNULIB_GETUSERSHELL''@/$(GNULIB_GETUSERSHELL)/g' \
-	      -e 's/@''GNULIB_GROUP_MEMBER''@/$(GNULIB_GROUP_MEMBER)/g' \
-	      -e 's/@''GNULIB_ISATTY''@/$(GNULIB_ISATTY)/g' \
-	      -e 's/@''GNULIB_LCHOWN''@/$(GNULIB_LCHOWN)/g' \
-	      -e 's/@''GNULIB_LINK''@/$(GNULIB_LINK)/g' \
-	      -e 's/@''GNULIB_LINKAT''@/$(GNULIB_LINKAT)/g' \
-	      -e 's/@''GNULIB_LSEEK''@/$(GNULIB_LSEEK)/g' \
-	      -e 's/@''GNULIB_PIPE''@/$(GNULIB_PIPE)/g' \
-	      -e 's/@''GNULIB_PIPE2''@/$(GNULIB_PIPE2)/g' \
-	      -e 's/@''GNULIB_PREAD''@/$(GNULIB_PREAD)/g' \
-	      -e 's/@''GNULIB_PWRITE''@/$(GNULIB_PWRITE)/g' \
-	      -e 's/@''GNULIB_READ''@/$(GNULIB_READ)/g' \
-	      -e 's/@''GNULIB_READLINK''@/$(GNULIB_READLINK)/g' \
-	      -e 's/@''GNULIB_READLINKAT''@/$(GNULIB_READLINKAT)/g' \
-	      -e 's/@''GNULIB_RMDIR''@/$(GNULIB_RMDIR)/g' \
-	      -e 's/@''GNULIB_SETHOSTNAME''@/$(GNULIB_SETHOSTNAME)/g' \
-	      -e 's/@''GNULIB_SLEEP''@/$(GNULIB_SLEEP)/g' \
-	      -e 's/@''GNULIB_SYMLINK''@/$(GNULIB_SYMLINK)/g' \
-	      -e 's/@''GNULIB_SYMLINKAT''@/$(GNULIB_SYMLINKAT)/g' \
-	      -e 's/@''GNULIB_TTYNAME_R''@/$(GNULIB_TTYNAME_R)/g' \
-	      -e 's/@''GNULIB_UNISTD_H_GETOPT''@/0$(GNULIB_GL_UNISTD_H_GETOPT)/g' \
-	      -e 's/@''GNULIB_UNISTD_H_NONBLOCKING''@/$(GNULIB_UNISTD_H_NONBLOCKING)/g' \
-	      -e 's/@''GNULIB_UNISTD_H_SIGPIPE''@/$(GNULIB_UNISTD_H_SIGPIPE)/g' \
-	      -e 's/@''GNULIB_UNLINK''@/$(GNULIB_UNLINK)/g' \
-	      -e 's/@''GNULIB_UNLINKAT''@/$(GNULIB_UNLINKAT)/g' \
-	      -e 's/@''GNULIB_USLEEP''@/$(GNULIB_USLEEP)/g' \
-	      -e 's/@''GNULIB_WRITE''@/$(GNULIB_WRITE)/g' \
-	      < $(srcdir)/unistd.in.h | \
-	  sed -e 's|@''HAVE_CHOWN''@|$(HAVE_CHOWN)|g' \
-	      -e 's|@''HAVE_DUP2''@|$(HAVE_DUP2)|g' \
-	      -e 's|@''HAVE_DUP3''@|$(HAVE_DUP3)|g' \
-	      -e 's|@''HAVE_EUIDACCESS''@|$(HAVE_EUIDACCESS)|g' \
-	      -e 's|@''HAVE_FACCESSAT''@|$(HAVE_FACCESSAT)|g' \
-	      -e 's|@''HAVE_FCHDIR''@|$(HAVE_FCHDIR)|g' \
-	      -e 's|@''HAVE_FCHOWNAT''@|$(HAVE_FCHOWNAT)|g' \
-	      -e 's|@''HAVE_FDATASYNC''@|$(HAVE_FDATASYNC)|g' \
-	      -e 's|@''HAVE_FSYNC''@|$(HAVE_FSYNC)|g' \
-	      -e 's|@''HAVE_FTRUNCATE''@|$(HAVE_FTRUNCATE)|g' \
-	      -e 's|@''HAVE_GETDTABLESIZE''@|$(HAVE_GETDTABLESIZE)|g' \
-	      -e 's|@''HAVE_GETGROUPS''@|$(HAVE_GETGROUPS)|g' \
-	      -e 's|@''HAVE_GETHOSTNAME''@|$(HAVE_GETHOSTNAME)|g' \
-	      -e 's|@''HAVE_GETLOGIN''@|$(HAVE_GETLOGIN)|g' \
-	      -e 's|@''HAVE_GETPAGESIZE''@|$(HAVE_GETPAGESIZE)|g' \
-	      -e 's|@''HAVE_GROUP_MEMBER''@|$(HAVE_GROUP_MEMBER)|g' \
-	      -e 's|@''HAVE_LCHOWN''@|$(HAVE_LCHOWN)|g' \
-	      -e 's|@''HAVE_LINK''@|$(HAVE_LINK)|g' \
-	      -e 's|@''HAVE_LINKAT''@|$(HAVE_LINKAT)|g' \
-	      -e 's|@''HAVE_PIPE''@|$(HAVE_PIPE)|g' \
-	      -e 's|@''HAVE_PIPE2''@|$(HAVE_PIPE2)|g' \
-	      -e 's|@''HAVE_PREAD''@|$(HAVE_PREAD)|g' \
-	      -e 's|@''HAVE_PWRITE''@|$(HAVE_PWRITE)|g' \
-	      -e 's|@''HAVE_READLINK''@|$(HAVE_READLINK)|g' \
-	      -e 's|@''HAVE_READLINKAT''@|$(HAVE_READLINKAT)|g' \
-	      -e 's|@''HAVE_SETHOSTNAME''@|$(HAVE_SETHOSTNAME)|g' \
-	      -e 's|@''HAVE_SLEEP''@|$(HAVE_SLEEP)|g' \
-	      -e 's|@''HAVE_SYMLINK''@|$(HAVE_SYMLINK)|g' \
-	      -e 's|@''HAVE_SYMLINKAT''@|$(HAVE_SYMLINKAT)|g' \
-	      -e 's|@''HAVE_UNLINKAT''@|$(HAVE_UNLINKAT)|g' \
-	      -e 's|@''HAVE_USLEEP''@|$(HAVE_USLEEP)|g' \
-	      -e 's|@''HAVE_DECL_ENVIRON''@|$(HAVE_DECL_ENVIRON)|g' \
-	      -e 's|@''HAVE_DECL_FCHDIR''@|$(HAVE_DECL_FCHDIR)|g' \
-	      -e 's|@''HAVE_DECL_FDATASYNC''@|$(HAVE_DECL_FDATASYNC)|g' \
-	      -e 's|@''HAVE_DECL_GETDOMAINNAME''@|$(HAVE_DECL_GETDOMAINNAME)|g' \
-	      -e 's|@''HAVE_DECL_GETLOGIN_R''@|$(HAVE_DECL_GETLOGIN_R)|g' \
-	      -e 's|@''HAVE_DECL_GETPAGESIZE''@|$(HAVE_DECL_GETPAGESIZE)|g' \
-	      -e 's|@''HAVE_DECL_GETUSERSHELL''@|$(HAVE_DECL_GETUSERSHELL)|g' \
-	      -e 's|@''HAVE_DECL_SETHOSTNAME''@|$(HAVE_DECL_SETHOSTNAME)|g' \
-	      -e 's|@''HAVE_DECL_TTYNAME_R''@|$(HAVE_DECL_TTYNAME_R)|g' \
-	      -e 's|@''HAVE_OS_H''@|$(HAVE_OS_H)|g' \
-	      -e 's|@''HAVE_SYS_PARAM_H''@|$(HAVE_SYS_PARAM_H)|g' \
-	  | \
-	  sed -e 's|@''REPLACE_CHOWN''@|$(REPLACE_CHOWN)|g' \
-	      -e 's|@''REPLACE_CLOSE''@|$(REPLACE_CLOSE)|g' \
-	      -e 's|@''REPLACE_DUP''@|$(REPLACE_DUP)|g' \
-	      -e 's|@''REPLACE_DUP2''@|$(REPLACE_DUP2)|g' \
-	      -e 's|@''REPLACE_FCHOWNAT''@|$(REPLACE_FCHOWNAT)|g' \
-	      -e 's|@''REPLACE_FTRUNCATE''@|$(REPLACE_FTRUNCATE)|g' \
-	      -e 's|@''REPLACE_GETCWD''@|$(REPLACE_GETCWD)|g' \
-	      -e 's|@''REPLACE_GETDOMAINNAME''@|$(REPLACE_GETDOMAINNAME)|g' \
-	      -e 's|@''REPLACE_GETLOGIN_R''@|$(REPLACE_GETLOGIN_R)|g' \
-	      -e 's|@''REPLACE_GETGROUPS''@|$(REPLACE_GETGROUPS)|g' \
-	      -e 's|@''REPLACE_GETPAGESIZE''@|$(REPLACE_GETPAGESIZE)|g' \
-	      -e 's|@''REPLACE_ISATTY''@|$(REPLACE_ISATTY)|g' \
-	      -e 's|@''REPLACE_LCHOWN''@|$(REPLACE_LCHOWN)|g' \
-	      -e 's|@''REPLACE_LINK''@|$(REPLACE_LINK)|g' \
-	      -e 's|@''REPLACE_LINKAT''@|$(REPLACE_LINKAT)|g' \
-	      -e 's|@''REPLACE_LSEEK''@|$(REPLACE_LSEEK)|g' \
-	      -e 's|@''REPLACE_PREAD''@|$(REPLACE_PREAD)|g' \
-	      -e 's|@''REPLACE_PWRITE''@|$(REPLACE_PWRITE)|g' \
-	      -e 's|@''REPLACE_READ''@|$(REPLACE_READ)|g' \
-	      -e 's|@''REPLACE_READLINK''@|$(REPLACE_READLINK)|g' \
-	      -e 's|@''REPLACE_RMDIR''@|$(REPLACE_RMDIR)|g' \
-	      -e 's|@''REPLACE_SLEEP''@|$(REPLACE_SLEEP)|g' \
-	      -e 's|@''REPLACE_SYMLINK''@|$(REPLACE_SYMLINK)|g' \
-	      -e 's|@''REPLACE_TTYNAME_R''@|$(REPLACE_TTYNAME_R)|g' \
-	      -e 's|@''REPLACE_UNLINK''@|$(REPLACE_UNLINK)|g' \
-	      -e 's|@''REPLACE_UNLINKAT''@|$(REPLACE_UNLINKAT)|g' \
-	      -e 's|@''REPLACE_USLEEP''@|$(REPLACE_USLEEP)|g' \
-	      -e 's|@''REPLACE_WRITE''@|$(REPLACE_WRITE)|g' \
-	      -e 's|@''UNISTD_H_HAVE_WINSOCK2_H''@|$(UNISTD_H_HAVE_WINSOCK2_H)|g' \
-	      -e 's|@''UNISTD_H_HAVE_WINSOCK2_H_AND_USE_SOCKETS''@|$(UNISTD_H_HAVE_WINSOCK2_H_AND_USE_SOCKETS)|g' \
-	      -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
-	      -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
-	      -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)'; \
-	} > $@-t && \
-	mv $@-t $@
-MOSTLYCLEANFILES += unistd.h unistd.h-t
-
-EXTRA_DIST += unistd.in.h
-
-## end   gnulib module unistd
-
-## begin gnulib module unistd-safer
-
-libgnu_la_SOURCES += dup-safer.c fd-safer.c pipe-safer.c
-
-EXTRA_DIST += unistd--.h unistd-safer.h
-
-## end   gnulib module unistd-safer
-
-## begin gnulib module unlink
-
-
-EXTRA_DIST += unlink.c
-
-EXTRA_libgnu_la_SOURCES += unlink.c
-
-## end   gnulib module unlink
-
-## begin gnulib module vasnprintf
-
-
-EXTRA_DIST += asnprintf.c float+.h printf-args.c printf-args.h printf-parse.c printf-parse.h vasnprintf.c vasnprintf.h
-
-EXTRA_libgnu_la_SOURCES += asnprintf.c printf-args.c printf-parse.c vasnprintf.c
-
-## end   gnulib module vasnprintf
-
-## begin gnulib module vasprintf
-
-
-EXTRA_DIST += asprintf.c vasprintf.c
-
-EXTRA_libgnu_la_SOURCES += asprintf.c vasprintf.c
-
-## end   gnulib module vasprintf
-
-## begin gnulib module verify
-
-
-EXTRA_DIST += verify.h
-
-## end   gnulib module verify
-
-## begin gnulib module wchar
-
-BUILT_SOURCES += wchar.h
-
-# We need the following in order to create <wchar.h> when the system
-# version does not work standalone.
-wchar.h: wchar.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(ARG_NONNULL_H) $(WARN_ON_USE_H)
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''HAVE_FEATURES_H''@|$(HAVE_FEATURES_H)|g' \
-	      -e 's|@''NEXT_WCHAR_H''@|$(NEXT_WCHAR_H)|g' \
-	      -e 's|@''HAVE_WCHAR_H''@|$(HAVE_WCHAR_H)|g' \
-	      -e 's/@''GNULIB_BTOWC''@/$(GNULIB_BTOWC)/g' \
-	      -e 's/@''GNULIB_WCTOB''@/$(GNULIB_WCTOB)/g' \
-	      -e 's/@''GNULIB_MBSINIT''@/$(GNULIB_MBSINIT)/g' \
-	      -e 's/@''GNULIB_MBRTOWC''@/$(GNULIB_MBRTOWC)/g' \
-	      -e 's/@''GNULIB_MBRLEN''@/$(GNULIB_MBRLEN)/g' \
-	      -e 's/@''GNULIB_MBSRTOWCS''@/$(GNULIB_MBSRTOWCS)/g' \
-	      -e 's/@''GNULIB_MBSNRTOWCS''@/$(GNULIB_MBSNRTOWCS)/g' \
-	      -e 's/@''GNULIB_WCRTOMB''@/$(GNULIB_WCRTOMB)/g' \
-	      -e 's/@''GNULIB_WCSRTOMBS''@/$(GNULIB_WCSRTOMBS)/g' \
-	      -e 's/@''GNULIB_WCSNRTOMBS''@/$(GNULIB_WCSNRTOMBS)/g' \
-	      -e 's/@''GNULIB_WCWIDTH''@/$(GNULIB_WCWIDTH)/g' \
-	      -e 's/@''GNULIB_WMEMCHR''@/$(GNULIB_WMEMCHR)/g' \
-	      -e 's/@''GNULIB_WMEMCMP''@/$(GNULIB_WMEMCMP)/g' \
-	      -e 's/@''GNULIB_WMEMCPY''@/$(GNULIB_WMEMCPY)/g' \
-	      -e 's/@''GNULIB_WMEMMOVE''@/$(GNULIB_WMEMMOVE)/g' \
-	      -e 's/@''GNULIB_WMEMSET''@/$(GNULIB_WMEMSET)/g' \
-	      -e 's/@''GNULIB_WCSLEN''@/$(GNULIB_WCSLEN)/g' \
-	      -e 's/@''GNULIB_WCSNLEN''@/$(GNULIB_WCSNLEN)/g' \
-	      -e 's/@''GNULIB_WCSCPY''@/$(GNULIB_WCSCPY)/g' \
-	      -e 's/@''GNULIB_WCPCPY''@/$(GNULIB_WCPCPY)/g' \
-	      -e 's/@''GNULIB_WCSNCPY''@/$(GNULIB_WCSNCPY)/g' \
-	      -e 's/@''GNULIB_WCPNCPY''@/$(GNULIB_WCPNCPY)/g' \
-	      -e 's/@''GNULIB_WCSCAT''@/$(GNULIB_WCSCAT)/g' \
-	      -e 's/@''GNULIB_WCSNCAT''@/$(GNULIB_WCSNCAT)/g' \
-	      -e 's/@''GNULIB_WCSCMP''@/$(GNULIB_WCSCMP)/g' \
-	      -e 's/@''GNULIB_WCSNCMP''@/$(GNULIB_WCSNCMP)/g' \
-	      -e 's/@''GNULIB_WCSCASECMP''@/$(GNULIB_WCSCASECMP)/g' \
-	      -e 's/@''GNULIB_WCSNCASECMP''@/$(GNULIB_WCSNCASECMP)/g' \
-	      -e 's/@''GNULIB_WCSCOLL''@/$(GNULIB_WCSCOLL)/g' \
-	      -e 's/@''GNULIB_WCSXFRM''@/$(GNULIB_WCSXFRM)/g' \
-	      -e 's/@''GNULIB_WCSDUP''@/$(GNULIB_WCSDUP)/g' \
-	      -e 's/@''GNULIB_WCSCHR''@/$(GNULIB_WCSCHR)/g' \
-	      -e 's/@''GNULIB_WCSRCHR''@/$(GNULIB_WCSRCHR)/g' \
-	      -e 's/@''GNULIB_WCSCSPN''@/$(GNULIB_WCSCSPN)/g' \
-	      -e 's/@''GNULIB_WCSSPN''@/$(GNULIB_WCSSPN)/g' \
-	      -e 's/@''GNULIB_WCSPBRK''@/$(GNULIB_WCSPBRK)/g' \
-	      -e 's/@''GNULIB_WCSSTR''@/$(GNULIB_WCSSTR)/g' \
-	      -e 's/@''GNULIB_WCSTOK''@/$(GNULIB_WCSTOK)/g' \
-	      -e 's/@''GNULIB_WCSWIDTH''@/$(GNULIB_WCSWIDTH)/g' \
-	      < $(srcdir)/wchar.in.h | \
-	  sed -e 's|@''HAVE_WINT_T''@|$(HAVE_WINT_T)|g' \
-	      -e 's|@''HAVE_BTOWC''@|$(HAVE_BTOWC)|g' \
-	      -e 's|@''HAVE_MBSINIT''@|$(HAVE_MBSINIT)|g' \
-	      -e 's|@''HAVE_MBRTOWC''@|$(HAVE_MBRTOWC)|g' \
-	      -e 's|@''HAVE_MBRLEN''@|$(HAVE_MBRLEN)|g' \
-	      -e 's|@''HAVE_MBSRTOWCS''@|$(HAVE_MBSRTOWCS)|g' \
-	      -e 's|@''HAVE_MBSNRTOWCS''@|$(HAVE_MBSNRTOWCS)|g' \
-	      -e 's|@''HAVE_WCRTOMB''@|$(HAVE_WCRTOMB)|g' \
-	      -e 's|@''HAVE_WCSRTOMBS''@|$(HAVE_WCSRTOMBS)|g' \
-	      -e 's|@''HAVE_WCSNRTOMBS''@|$(HAVE_WCSNRTOMBS)|g' \
-	      -e 's|@''HAVE_WMEMCHR''@|$(HAVE_WMEMCHR)|g' \
-	      -e 's|@''HAVE_WMEMCMP''@|$(HAVE_WMEMCMP)|g' \
-	      -e 's|@''HAVE_WMEMCPY''@|$(HAVE_WMEMCPY)|g' \
-	      -e 's|@''HAVE_WMEMMOVE''@|$(HAVE_WMEMMOVE)|g' \
-	      -e 's|@''HAVE_WMEMSET''@|$(HAVE_WMEMSET)|g' \
-	      -e 's|@''HAVE_WCSLEN''@|$(HAVE_WCSLEN)|g' \
-	      -e 's|@''HAVE_WCSNLEN''@|$(HAVE_WCSNLEN)|g' \
-	      -e 's|@''HAVE_WCSCPY''@|$(HAVE_WCSCPY)|g' \
-	      -e 's|@''HAVE_WCPCPY''@|$(HAVE_WCPCPY)|g' \
-	      -e 's|@''HAVE_WCSNCPY''@|$(HAVE_WCSNCPY)|g' \
-	      -e 's|@''HAVE_WCPNCPY''@|$(HAVE_WCPNCPY)|g' \
-	      -e 's|@''HAVE_WCSCAT''@|$(HAVE_WCSCAT)|g' \
-	      -e 's|@''HAVE_WCSNCAT''@|$(HAVE_WCSNCAT)|g' \
-	      -e 's|@''HAVE_WCSCMP''@|$(HAVE_WCSCMP)|g' \
-	      -e 's|@''HAVE_WCSNCMP''@|$(HAVE_WCSNCMP)|g' \
-	      -e 's|@''HAVE_WCSCASECMP''@|$(HAVE_WCSCASECMP)|g' \
-	      -e 's|@''HAVE_WCSNCASECMP''@|$(HAVE_WCSNCASECMP)|g' \
-	      -e 's|@''HAVE_WCSCOLL''@|$(HAVE_WCSCOLL)|g' \
-	      -e 's|@''HAVE_WCSXFRM''@|$(HAVE_WCSXFRM)|g' \
-	      -e 's|@''HAVE_WCSDUP''@|$(HAVE_WCSDUP)|g' \
-	      -e 's|@''HAVE_WCSCHR''@|$(HAVE_WCSCHR)|g' \
-	      -e 's|@''HAVE_WCSRCHR''@|$(HAVE_WCSRCHR)|g' \
-	      -e 's|@''HAVE_WCSCSPN''@|$(HAVE_WCSCSPN)|g' \
-	      -e 's|@''HAVE_WCSSPN''@|$(HAVE_WCSSPN)|g' \
-	      -e 's|@''HAVE_WCSPBRK''@|$(HAVE_WCSPBRK)|g' \
-	      -e 's|@''HAVE_WCSSTR''@|$(HAVE_WCSSTR)|g' \
-	      -e 's|@''HAVE_WCSTOK''@|$(HAVE_WCSTOK)|g' \
-	      -e 's|@''HAVE_WCSWIDTH''@|$(HAVE_WCSWIDTH)|g' \
-	      -e 's|@''HAVE_DECL_WCTOB''@|$(HAVE_DECL_WCTOB)|g' \
-	      -e 's|@''HAVE_DECL_WCWIDTH''@|$(HAVE_DECL_WCWIDTH)|g' \
-	  | \
-	  sed -e 's|@''REPLACE_MBSTATE_T''@|$(REPLACE_MBSTATE_T)|g' \
-	      -e 's|@''REPLACE_BTOWC''@|$(REPLACE_BTOWC)|g' \
-	      -e 's|@''REPLACE_WCTOB''@|$(REPLACE_WCTOB)|g' \
-	      -e 's|@''REPLACE_MBSINIT''@|$(REPLACE_MBSINIT)|g' \
-	      -e 's|@''REPLACE_MBRTOWC''@|$(REPLACE_MBRTOWC)|g' \
-	      -e 's|@''REPLACE_MBRLEN''@|$(REPLACE_MBRLEN)|g' \
-	      -e 's|@''REPLACE_MBSRTOWCS''@|$(REPLACE_MBSRTOWCS)|g' \
-	      -e 's|@''REPLACE_MBSNRTOWCS''@|$(REPLACE_MBSNRTOWCS)|g' \
-	      -e 's|@''REPLACE_WCRTOMB''@|$(REPLACE_WCRTOMB)|g' \
-	      -e 's|@''REPLACE_WCSRTOMBS''@|$(REPLACE_WCSRTOMBS)|g' \
-	      -e 's|@''REPLACE_WCSNRTOMBS''@|$(REPLACE_WCSNRTOMBS)|g' \
-	      -e 's|@''REPLACE_WCWIDTH''@|$(REPLACE_WCWIDTH)|g' \
-	      -e 's|@''REPLACE_WCSWIDTH''@|$(REPLACE_WCSWIDTH)|g' \
-	      -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
-	      -e '/definition of _GL_ARG_NONNULL/r $(ARG_NONNULL_H)' \
-	      -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)'; \
-	} > $@-t && \
-	mv $@-t $@
-MOSTLYCLEANFILES += wchar.h wchar.h-t
-
-EXTRA_DIST += wchar.in.h
-
-## end   gnulib module wchar
-
-## begin gnulib module wctype-h
-
-BUILT_SOURCES += wctype.h
-
-# We need the following in order to create <wctype.h> when the system
-# doesn't have one that works with the given compiler.
-wctype.h: wctype.in.h $(top_builddir)/config.status $(CXXDEFS_H) $(WARN_ON_USE_H)
-	$(AM_V_GEN)rm -f $@-t $@ && \
-	{ echo '/* DO NOT EDIT! GENERATED AUTOMATICALLY! */'; \
-	  sed -e 's|@''GUARD_PREFIX''@|GL|g' \
-	      -e 's/@''HAVE_WCTYPE_H''@/$(HAVE_WCTYPE_H)/g' \
-	      -e 's|@''INCLUDE_NEXT''@|$(INCLUDE_NEXT)|g' \
-	      -e 's|@''PRAGMA_SYSTEM_HEADER''@|@PRAGMA_SYSTEM_HEADER@|g' \
-	      -e 's|@''PRAGMA_COLUMNS''@|@PRAGMA_COLUMNS@|g' \
-	      -e 's|@''NEXT_WCTYPE_H''@|$(NEXT_WCTYPE_H)|g' \
-	      -e 's/@''GNULIB_ISWBLANK''@/$(GNULIB_ISWBLANK)/g' \
-	      -e 's/@''GNULIB_WCTYPE''@/$(GNULIB_WCTYPE)/g' \
-	      -e 's/@''GNULIB_ISWCTYPE''@/$(GNULIB_ISWCTYPE)/g' \
-	      -e 's/@''GNULIB_WCTRANS''@/$(GNULIB_WCTRANS)/g' \
-	      -e 's/@''GNULIB_TOWCTRANS''@/$(GNULIB_TOWCTRANS)/g' \
-	      -e 's/@''HAVE_ISWBLANK''@/$(HAVE_ISWBLANK)/g' \
-	      -e 's/@''HAVE_ISWCNTRL''@/$(HAVE_ISWCNTRL)/g' \
-	      -e 's/@''HAVE_WCTYPE_T''@/$(HAVE_WCTYPE_T)/g' \
-	      -e 's/@''HAVE_WCTRANS_T''@/$(HAVE_WCTRANS_T)/g' \
-	      -e 's/@''HAVE_WINT_T''@/$(HAVE_WINT_T)/g' \
-	      -e 's/@''REPLACE_ISWBLANK''@/$(REPLACE_ISWBLANK)/g' \
-	      -e 's/@''REPLACE_ISWCNTRL''@/$(REPLACE_ISWCNTRL)/g' \
-	      -e 's/@''REPLACE_TOWLOWER''@/$(REPLACE_TOWLOWER)/g' \
-	      -e '/definitions of _GL_FUNCDECL_RPL/r $(CXXDEFS_H)' \
-	      -e '/definition of _GL_WARN_ON_USE/r $(WARN_ON_USE_H)' \
-	      < $(srcdir)/wctype.in.h; \
-	} > $@-t && \
-	mv $@-t $@
-MOSTLYCLEANFILES += wctype.h wctype.h-t
-
-EXTRA_DIST += wctype.in.h
-
-## end   gnulib module wctype-h
-
-## begin gnulib module xalloc
-
-libgnu_la_SOURCES += xmalloc.c
-
-EXTRA_DIST += xalloc.h
-
-## end   gnulib module xalloc
-
-## begin gnulib module xalloc-die
-
-libgnu_la_SOURCES += xalloc-die.c
-
-## end   gnulib module xalloc-die
-
-## begin gnulib module xalloc-oversized
-
-
-EXTRA_DIST += xalloc-oversized.h
-
-## end   gnulib module xalloc-oversized
-
-## begin gnulib module xgetcwd
-
-libgnu_la_SOURCES += xgetcwd.c
-
-EXTRA_DIST += xgetcwd.h
-
-## end   gnulib module xgetcwd
-
-## begin gnulib module xsize
-
-libgnu_la_SOURCES += xsize.h
-
-## end   gnulib module xsize
-
-## begin gnulib module xstrndup
-
-libgnu_la_SOURCES += xstrndup.h xstrndup.c
-
-## end   gnulib module xstrndup
-
-
-mostlyclean-local: mostlyclean-generic
-	@for dir in '' $(MOSTLYCLEANDIRS); do \
-	  if test -n "$$dir" && test -d $$dir; then \
-	    echo "rmdir $$dir"; rmdir $$dir; \
-	  fi; \
-	done; \
-	:
--- a/libgui/Makefile.am	Thu Nov 01 15:01:20 2012 -0400
+++ b/libgui/Makefile.am	Sun Dec 23 13:00:02 2012 -0500
@@ -22,14 +22,6 @@
 
 AUTOMAKE_OPTIONS = subdir-objects
 
-QT_INCDIR = @QT_INCDIR@
-
-QT_LIBDIR = @QT_LIBDIR@
-
-QT_LIBS = -lQtCore -lQtGui -lQtNetwork -lqscintilla2
-
-QT_LDFLAGS = -L$(QT_LIBDIR)
-
 MOC_CPPFLAGS =
 
 octlib_LTLIBRARIES = liboctgui.la
--- a/libgui/default-qt-settings	Thu Nov 01 15:01:20 2012 -0400
+++ b/libgui/default-qt-settings	Sun Dec 23 13:00:02 2012 -0500
@@ -3,7 +3,6 @@
 showMessageOfTheDay=true
 showTopic=true
 autoIdentification=false
-nickServPassword=
 useCustomFileEditor=false
 customFileEditor=emacs
 showFilenames=true
@@ -23,15 +22,50 @@
 showLineNumbers=true
 highlightCurrentLine=true
 codeCompletion=true
-fontName=Ubuntu Mono
-fontSize=12
-shortWindowTitle=true
-longWindowTitle=true
+fontName=Courier
+fontSize=10
+longWindowTitle=false
+restoreSession=false
+savedSessionTabs=@Invalid()
 
 [terminal]
 fontSize=10
-fontName=Andale Mono
+fontName=Courier
+cursorBlinking=true
+cursorType=ibeam
 
 [MainWindow]
-geometry=@ByteArray(\x1\xd9\xd0\xcb\0\x1\0\0\0\0\0\x31\0\0\0\x18\0\0\x4\xff\0\0\x3\xff\0\0\0\0\0\0\0\0\xff\xff\xff\xfe\xff\xff\xff\xfe\0\0\0\0\x2\0)
-windowState=@ByteArray(\0\0\0\xff\0\0\0\0\xfd\0\0\0\x1\0\0\0\x1\0\0\x4\xcf\0\0\x3\x91\xfc\x2\0\0\0\x1\xfc\0\0\0\x41\0\0\x3\x91\0\0\x1\xc7\0\xff\xff\xff\xfc\x1\0\0\0\x3\xfc\0\0\0\0\0\0\x1.\0\0\0R\0\xff\xff\xff\xfc\x2\0\0\0\x2\xfb\0\0\0\x1a\0W\0o\0r\0k\0s\0p\0\x61\0\x63\0\x65\0V\0i\0\x65\0w\x1\0\0\0\x41\0\0\x1\xe8\0\0\0k\0\xff\xff\xff\xfb\0\0\0\"\0H\0i\0s\0t\0o\0r\0y\0\x44\0o\0\x63\0k\0W\0i\0\x64\0g\0\x65\0t\x1\0\0\x2/\0\0\x1\xa3\0\0\0\x8c\0\xff\xff\xff\xfc\0\0\x1\x34\0\0\x2\x81\0\0\x2\x81\0\0\x2\x81\xfa\0\0\0\0\x2\0\0\0\x2\xfb\0\0\0$\0T\0\x65\0r\0m\0i\0n\0\x61\0l\0\x44\0o\0\x63\0k\0W\0i\0\x64\0g\0\x65\0t\x1\0\0\0\0\xff\xff\xff\xff\0\0\x1\xa9\0\xff\xff\xff\xfb\0\0\0\x14\0\x46\0i\0l\0\x65\0\x45\0\x64\0i\0t\0o\0r\x1\0\0\x1\xf0\0\0\x1\xe2\0\0\0j\0\xff\xff\xff\xfb\0\0\0\x1e\0\x46\0i\0l\0\x65\0s\0\x44\0o\0\x63\0k\0W\0i\0\x64\0g\0\x65\0t\x1\0\0\x3\xbb\0\0\x1\x14\0\0\0P\0\xff\xff\xff\0\0\0\0\0\0\x3\x91\0\0\0\x4\0\0\0\x4\0\0\0\b\0\0\0\b\xfc\0\0\0\x1\0\0\0\x2\0\0\0\x1\xff\xff\xff\xff\x1\0\0\0\0\xff\xff\xff\xff\0\0\0\0\0\0\0\0)
+geometry=@ByteArray(\x1\xd9\xd0\xcb\0\x1\0\0\0\0\0\0\0\0\0\x18\0\0\x3G\0\0\x2\xe9\0\0\0\x1\0\0\0\x33\0\0\x3\x46\0\0\x2\xe8\0\0\0\0\0\0)
+windowState=@ByteArray(\0\0\0\xff\0\0\0\0\xfd\0\0\0\x1\0\0\0\x1\0\0\x3\x46\0\0\x2x\xfc\x2\0\0\0\x1\xfc\0\0\0(\0\0\x2x\0\0\x1\xc5\0\xff\xff\xff\xfc\x1\0\0\0\x2\xfc\0\0\0\0\0\0\0\xe8\0\0\0R\0\xff\xff\xff\xfc\x2\0\0\0\x3\xfb\0\0\0\x1e\0\x46\0i\0l\0\x65\0s\0\x44\0o\0\x63\0k\0W\0i\0\x64\0g\0\x65\0t\x1\0\0\0(\0\0\0\xc9\0\0\0\x8d\0\xff\xff\xff\xfb\0\0\0\x1a\0W\0o\0r\0k\0s\0p\0\x61\0\x63\0\x65\0V\0i\0\x65\0w\x1\0\0\0\xf7\0\0\0\xd7\0\0\0k\0\xff\xff\xff\xfb\0\0\0\"\0H\0i\0s\0t\0o\0r\0y\0\x44\0o\0\x63\0k\0W\0i\0\x64\0g\0\x65\0t\x1\0\0\x1\xd4\0\0\0\xcc\0\0\0\x8a\0\xff\xff\xff\xfc\0\0\0\xee\0\0\x2X\0\0\x2X\0\xff\xff\xff\xfa\0\0\0\0\x2\0\0\0\x3\xfb\0\0\0$\0T\0\x65\0r\0m\0i\0n\0\x61\0l\0\x44\0o\0\x63\0k\0W\0i\0\x64\0g\0\x65\0t\x1\0\0\0\0\xff\xff\xff\xff\0\0\x1\xa9\0\xff\xff\xff\xfb\0\0\0\x14\0\x46\0i\0l\0\x65\0\x45\0\x64\0i\0t\0o\0r\x1\0\0\0\0\xff\xff\xff\xff\0\0\0h\0\xff\xff\xff\xfb\0\0\0.\0\x44\0o\0\x63\0u\0m\0\x65\0n\0t\0\x61\0t\0i\0o\0n\0\x44\0o\0\x63\0k\0W\0i\0\x64\0g\0\x65\0t\x1\0\0\0\0\xff\xff\xff\xff\0\0\0\xac\0\xff\xff\xff\0\0\0\0\0\0\x2x\0\0\0\x4\0\0\0\x4\0\0\0\b\0\0\0\b\xfc\0\0\0\x1\0\0\0\x2\0\0\0\x1\xff\xff\xff\xff\x1\0\0\0\0\xff\xff\xff\xff\0\0\0\0\0\0\0\0)
+current_directory_list=@Invalid()
+
+[DockWidgets]
+TerminalDockWidget=@ByteArray(\x1\xd9\xd0\xcb\0\x1\0\0\0\0\0\xee\0\0\0(\0\0\x3\x45\0\0\x2\x83\0\0\0\xee\0\0\0(\0\0\x3\x45\0\0\x2\x83\0\0\0\0\0\0)
+TerminalDockWidgetFloating=false
+TerminalDockWidgetVisible=true
+WorkspaceView=@ByteArray(\x1\xd9\xd0\xcb\0\x1\0\0\0\0\0\0\0\0\0\xf7\0\0\0\xe7\0\0\x1\xcd\0\0\0\0\0\0\0\xf7\0\0\0\xe7\0\0\x1\xcd\0\0\0\0\0\0)
+WorkspaceViewFloating=false
+WorkspaceViewVisible=true
+HistoryDockWidget=@ByteArray(\x1\xd9\xd0\xcb\0\x1\0\0\0\0\0\0\0\0\x1\xd4\0\0\0\xe7\0\0\x2\x9f\0\0\0\0\0\0\x1\xd4\0\0\0\xe7\0\0\x2\x9f\0\0\0\0\0\0)
+HistoryDockWidgetFloating=false
+HistoryDockWidgetVisible=true
+FilesDockWidget=@ByteArray(\x1\xd9\xd0\xcb\0\x1\0\0\0\0\0\0\0\0\0(\0\0\0\xe7\0\0\0\xf0\0\0\0\0\0\0\0(\0\0\0\xe7\0\0\0\xf0\0\0\0\0\0\0)
+FilesDockWidgetFloating=false
+FilesDockWidgetVisible=true
+DocumentationDockWidget=@ByteArray(\x1\xd9\xd0\xcb\0\x1\0\0\xff\xff\xfb\xb3\xff\xff\xfb\xb1\xff\xff\xfe\v\xff\xff\xfe\v\xff\xff\xfb\xb3\xff\xff\xfb\xb1\xff\xff\xfe\v\xff\xff\xfe\v\0\0\0\0\0\0)
+DocumentationDockWidgetFloating=false
+DocumentationDockWidgetVisible=true
+FileEditor=@ByteArray(\x1\xd9\xd0\xcb\0\x1\0\0\xff\xff\xfb\xb3\xff\xff\xfb\xb1\xff\xff\xfe\v\xff\xff\xfe\v\xff\xff\xfb\xb3\xff\xff\xfb\xb1\xff\xff\xfe\v\xff\xff\xfe\v\0\0\0\0\0\0)
+FileEditorFloating=false
+FileEditorVisible=true
+
+[workspaceview]
+local_collapsed=false
+global_collapsed=false
+persistent_collapsed=false
+column_state=@ByteArray(\0\0\0\xff\0\0\0\0\0\0\0\x1\0\0\0\x1\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x1\x90\0\0\0\x4\x1\0\0\x1\0\0\0\0\0\0\0\0\0\0\0\0\x64\xff\xff\xff\xff\0\0\0\x81\0\0\0\0\0\0\0\x1\0\0\x1\x90\0\0\0\x4\0\0\0\0)
+
+[filesdockwidget]
+sort_files_by_column=0
+sort_files_by_order=0
+column_state=@ByteArray(\0\0\0\xff\0\0\0\0\0\0\0\x1\0\0\0\0\0\0\0\0\x1\0\0\0\0\0\0\0\0\0\0\0\x4\xe\0\0\0\x3\0\0\0\x3\0\0\0\x64\0\0\0\x2\0\0\0\x64\0\0\0\x1\0\0\0\x64\0\0\0\xd4\0\0\0\x4\x1\x1\0\x1\0\0\0\0\0\0\0\0\0\0\0\0\x64\xff\xff\xff\xff\0\0\0\x81\0\0\0\0\0\0\0\x2\0\0\0\xd4\0\0\0\x1\0\0\0\0\0\0\0\0\0\0\0\x3\0\0\0\0)
--- a/libgui/link-deps.mk	Thu Nov 01 15:01:20 2012 -0400
+++ b/libgui/link-deps.mk	Sun Dec 23 13:00:02 2012 -0500
@@ -7,10 +7,10 @@
 endif
 
 LIBOCTGUI_LINK_DEPS += \
-  $(QT_LIBS)
+  @QT_LIBS@
 
 LIBOCTGUI_LINK_OPTS = \
-  $(QT_LDFLAGS)
+  @QT_LDFLAGS@
 
 if AMCOND_LINK_ALL_DEPS
   LIBOCTGUI_LINK_DEPS += $(LIBOCTINTERP_LINK_DEPS)
--- a/libgui/qterminal-module.mk	Thu Nov 01 15:01:20 2012 -0400
+++ b/libgui/qterminal-module.mk	Sun Dec 23 13:00:02 2012 -0500
@@ -35,9 +35,7 @@
 
 qterminal_libqterminal_la_CPPFLAGS = \
   $(AM_CPPFLAGS) \
-  -I$(QT_INCDIR) \
-  -I$(QT_INCDIR)/QtCore \
-  -I$(QT_INCDIR)/QtGui \
+  @QT_CPPFLAGS@ \
   -I$(srcdir)/qterminal/libqterminal
 
 qterminal_libqterminal_la_CFLAGS = $(AM_CFLAGS)
@@ -56,7 +54,7 @@
 qterminal_libqterminal_la_CPPFLAGS += -DUNICODE
 
 # This flag is required to let MOC know about Q_OS_WIN32.
-MOC_CPPFLAGS += -DWIN32
+MOC_CPPFLAGS += -DQ_OS_WIN32
 
 else
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/LineFont.src	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,786 @@
+#2500: single horizontal line
+2500
+     
+     
+-----
+     
+     
+
+#2501: triple horizontal line
+2501
+     
+-----
+-----
+-----
+     
+
+#2502: single vertical line
+2502
+  |  
+  |  
+  |  
+  |  
+  |  
+
+#2503: triple vertical line
+2503
+ ||| 
+ ||| 
+ ||| 
+ ||| 
+ ||| 
+
+#2504-250B are dashed - not handled
+
+#250C: top-left corner (lines on bottom + right)
+250C
+     
+     
+  .--
+  |  
+  |  
+
+#250D: as above, but top line triple-width
+250D
+     
+  .--
+  .--
+  |--
+  |  
+
+#250E: now the vert line triple-width
+250E
+     
+     
+ ..--
+ ||| 
+ ||| 
+
+#250F: and now both lines triple-width
+250F
+     
+ .___
+ |.--
+ ||._
+ ||| 
+
+#2510: top-right corner
+2510
+     
+     
+--.  
+  |  
+  |  
+
+2511
+     
+==.  
+==.  
+==|  
+  | 
+
+2512
+     
+     
+==.. 
+ ||| 
+ ||| 
+
+2513
+     
+===. 
+==.| 
+=.|| 
+ ||| 
+
+#2514: bottom-left corner
+2514
+  |  
+  |  
+  .==
+     
+     
+
+2515
+  |  
+  |==
+  |==
+  ===
+     
+
+
+2516
+ ||| 
+ ||| 
+ |.==
+     
+     
+
+2517
+ ||| 
+ ||.=
+ |.==
+ .===
+     
+
+#2518: bottm-right corner
+2518
+  |  
+  |  
+==.  
+     
+     
+
+2519
+  |  
+==|  
+==|  
+===  
+     
+
+
+251A
+ ||| 
+ ||| 
+==== 
+     
+     
+
+251B
+ ||| 
+=.|| 
+==.| 
+===. 
+     
+
+#251C: Join of vertical line and one from the right
+251C
+  |  
+  |  
+  |==
+  |  
+  |  
+
+251D
+  |  
+  |==
+  |==
+  |==
+  |  
+
+251E
+ ||| 
+ ||| 
+ ||==
+  |  
+  |  
+
+251F
+  |  
+  |  
+ ||==
+ ||| 
+ ||| 
+
+
+2520
+ ||| 
+ ||| 
+ ||==
+ ||| 
+ ||| 
+
+2521
+ ||| 
+ |||=
+ ||==
+ .|==
+  |  
+
+2522
+  |  
+ .|==
+ ||==
+ |||=
+ ||| 
+
+2523
+ ||| 
+ ||.=
+ ||==
+ ||.=
+ ||| 
+
+#2524: Join of vertical line and one from the left
+2524
+  |  
+  |  
+==|  
+  |  
+  |  
+
+2525
+  |  
+==|  
+==|  
+==|  
+  |  
+
+2526
+ ||| 
+ ||| 
+==+| 
+  |  
+  |  
+
+2527
+  |  
+  |  
+==+| 
+ ||| 
+ ||| 
+
+2528
+ ||| 
+ ||| 
+==+| 
+ ||| 
+ ||| 
+
+2529
+ ||| 
+=+|| 
+==+| 
+===+ 
+  |  
+
+252A
+  |  
+=+|| 
+==+| 
+===+ 
+ ||| 
+
+252B
+ |||
+=+|| 
+==+| 
+=+|| 
+ |||
+
+#252C: horizontal line joined to from below
+252C
+     
+     
+=====
+  |  
+  |  
+
+252D
+     
+===  
+==|==
+==|  
+  |  
+
+252E
+     
+  ===
+==|==
+  |==
+  |  
+
+252F
+     
+==+==
+==|==
+==|==
+  |  
+
+2530
+     
+=====
+=====
+==|==
+  |  
+
+2531
+     
+===| 
+==||=
+=||| 
+ ||| 
+
+2532
+     
+ |===
+=||==
+ ||==
+ ||  
+
+2533
+     
+=====
+==|==
+=+|+=
+ ||| 
+
+#2534: bottom line, connected to from top
+2534
+  |
+  |
+=====
+     
+     
+
+2535
+  |
+==|
+=====
+===  
+    
+
+2536
+  |
+  |==
+=====
+  ===
+     
+
+2537
+  |
+==|==
+=====
+=====
+     
+
+2538
+ |||
+ |||
+=====
+     
+     
+
+2539
+ |||
+==||
+=====
+===| 
+    
+
+
+253A
+ |||
+ ||==
+=|===
+ |===
+     
+
+253B
+ |||
+==|==
+=====
+=====
+     
+
+#253C: vertical + horizontal lines intersecting
+253C
+  |  
+  |  
+=====
+  |  
+  |
+
+253D
+  |  
+==|  
+=====
+==|  
+  |
+
+253E
+  |  
+  |==
+=====
+  |==
+  |
+
+253F
+  |  
+==|==
+=====
+==|==
+  |
+
+2540
+ ||| 
+ ||| 
+=====
+  |  
+  |
+
+2541
+  |  
+  |  
+=====
+ ||| 
+ |||
+
+2542
+ ||| 
+ ||| 
+=====
+ ||| 
+ |||
+
+2543
+ ||| 
+=|||
+=====
+==|+ 
+  |
+
+2544
+ ||| 
+ ||==
+=====
+  |==
+  |
+
+2545
+  |
+==|+ 
+=====
+=|||
+ ||| 
+
+2546
+  |
+  |==
+=====
+ ||==
+ ||| 
+
+2547
+ ||| 
+=|||=
+=====
+=|||=
+  | 
+
+2548
+  |  
+=|||=
+=====
+=|||=
+ |||
+
+2549
+ ||| 
+=||| 
+=====
+=||| 
+ |||
+
+254A
+ ||| 
+ |||=
+=====
+ |||=
+ |||
+
+254B
+ ||| 
+=|||=
+=====
+=|||=
+ |||
+
+#254C-254F are dashed
+2550
+     
+_____
+     
+_____
+     
+
+2551
+ | | 
+ | |
+ | |
+ | |
+ | |
+
+2552
+     
+  |--
+  |
+  |--
+  |
+
+2553
+     
+     
+ ----
+ | | 
+ | | 
+
+2554
+     
+ +---
+ |
+ + +-
+ | |
+
+2555
+     
+--+
+  |  
+--+  
+  |  
+
+2556
+    
+    
+-+-+
+ | |
+ | |
+
+2557
+     
+---+ 
+   | 
+-+ |
+ | |
+
+2558
+  |
+  +--
+  |
+  +--
+
+2559
+ | | 
+ | | 
+ +-+-
+     
+     
+
+255A
+ | | 
+ | +-
+ |   
+ +---
+     
+
+255B
+  |  
+--+  
+  | 
+--+  
+     
+
+255C
+ | | 
+ | | 
+-+-+ 
+    
+
+255D
+ | | 
+-+ | 
+   |
+---+
+    
+
+255E
+  |
+  +--
+  |
+  +--
+  |
+
+255F
+ | |
+ | |
+ | +-
+ | |
+ | |
+
+2560
+ | |
+ | +-
+ | |
+ | +-
+ | |
+
+2561
+  |
+--+
+  |
+--+
+  |
+
+2562
+ | | 
+ | |
+-+ +
+ | |
+ | |
+
+2563
+ | |
+-+ |
+   |
+-+ |
+ | |
+
+2564
+     
+-----
+     
+--+--
+  |
+
+2565
+     
+     
+-+-+-
+ | | 
+ | |
+
+2566
+     
+-----
+     
+-+ +-
+ | |
+
+2567
+  |  
+--+--
+     
+-----
+     
+
+2568
+ | | 
+ | | 
+-+-+-
+     
+     
+
+2569
+ | | 
+-+ +-
+     
+-----
+     
+
+256A
+  |  
+--+--
+  |  
+--+--
+  |
+
+256B
+ | | 
+ | | 
+-+-+-
+ | | 
+ | | 
+
+256C
+ | | 
+-+ +-
+
+-+ +-
+ | | 
+
+#256F-2570 are curly,
+#2571-2573 are slashes and X
+
+2574
+     
+     
+___  
+     
+     
+
+2575
+  |  
+  |  
+  |  
+     
+    
+
+2576
+     
+     
+  ___
+     
+     
+
+2577
+     
+    
+  |  
+  |  
+  |  
+
+2578
+     
+___  
+___  
+___  
+     
+
+2579
+ ||| 
+ ||| 
+ ||| 
+     
+    
+
+257A
+     
+  ___
+  ___
+  ___
+     
+
+257B
+     
+    
+ ||| 
+ ||| 
+ ||| 
+
+257C
+     
+  ___
+_____
+  ___
+     
+
+257D
+  |  
+  |  
+ ||| 
+ ||| 
+ ||| 
+
+257E
+     
+___  
+_____
+___  
+     
+
+257F
+ ||| 
+ ||| 
+ ||| 
+  |  
+  |  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/QTerminal	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,23 @@
+/*
+
+Copyright (C) 2012 Michael Goffioul.
+Copyright (C) 2012 Jacob Dawid.
+
+This file is part of QTerminal.
+
+Foobar is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+QTerminal 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 Foobar.  If not, see <http://www.gnu.org/licenses/>.
+
+*/
+
+#include "QTerminal.h"
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/QTerminal.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,50 @@
+/*
+
+Copyright (C) 2012 Michael Goffioul.
+Copyright (C) 2012 Jacob Dawid.
+
+This file is part of QTerminal.
+
+Foobar is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+QTerminal 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 Foobar.  If not, see <http://www.gnu.org/licenses/>.
+
+*/
+
+#ifndef QTERMINAL_H
+#define QTERMINAL_H
+
+#include <QtGlobal>
+
+#ifdef Q_OS_WIN32
+    #include "win32/QWinTerminalImpl.h"
+    class QTerminal : public QWinTerminalImpl
+    {
+        Q_OBJECT
+    public:
+        QTerminal(QWidget *parent = 0)
+            : QWinTerminalImpl(parent) { }
+        ~QTerminal() { }
+    };
+#else
+    #include "unix/QUnixTerminalImpl.h"
+    class QTerminal : public QUnixTerminalImpl
+    {
+        Q_OBJECT
+    public:
+        QTerminal(QWidget *parent = 0)
+            : QUnixTerminalImpl(parent) { }
+        ~QTerminal() { }
+    };
+#endif
+
+#endif // QTERMINAL_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/QTerminalInterface.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,77 @@
+/*
+
+Copyright (C) 2012 Michael Goffioul.
+Copyright (C) 2012 Jacob Dawid.
+
+This file is part of QTerminal.
+
+Foobar is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+QTerminal 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 Foobar.  If not, see <http://www.gnu.org/licenses/>.
+
+*/
+
+#ifndef QTERMINALINTERFACE_H
+#define QTERMINALINTERFACE_H
+
+#include <QWidget>
+#include <QMenu>
+
+class QTerminalInterface : public QWidget
+{
+    Q_OBJECT
+public:
+    QTerminalInterface(QWidget *parent = 0) : QWidget(parent) {
+      connect (this, SIGNAL(customContextMenuRequested(QPoint)),
+               this, SLOT(handleCustomContextMenuRequested(QPoint)));
+
+      setContextMenuPolicy (Qt::CustomContextMenu);
+
+      _contextMenu = new QMenu (this);
+      QAction *copyAction  = _contextMenu->addAction ("Copy");
+      QAction *pasteAction = _contextMenu->addAction ("Paste");
+
+      connect (copyAction, SIGNAL (triggered()), this, SLOT (copyClipboard()));
+      connect (pasteAction, SIGNAL (triggered()), this, SLOT (pasteClipboard()));
+    }
+    virtual ~QTerminalInterface() { }
+
+    virtual void setTerminalFont(const QFont& font) = 0;
+    virtual void setSize(int h, int v) = 0;
+    virtual void sendText(const QString& text) = 0;
+
+    enum CursorType {
+      UnderlineCursor,
+      BlockCursor,
+      IBeamCursor
+    };
+
+    virtual void setCursorType(CursorType type, bool blinking) {
+        // Provide empty default impl in order to avoid conflicts with the win impl.
+        Q_UNUSED(type);
+        Q_UNUSED(blinking);
+    }
+
+public slots:
+    virtual void copyClipboard() = 0;
+    virtual void pasteClipboard() = 0;
+
+    virtual void handleCustomContextMenuRequested(QPoint at) {
+      _contextMenu->move (mapToGlobal(at));
+      _contextMenu->show ();
+    }
+
+private:
+    QMenu *_contextMenu;
+};
+
+#endif // QTERMINALINTERFACE_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/README	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,7 @@
+lib.pro is a *.pro-file for qmake
+
+It produces static lib (libqtermwidget.a) only. 
+For creating shared lib (*.so) uncomment "dll" in "CONFIG" line in *.pro-file
+
+Library was tested both with HAVE_POSIX_OPENPT and HAVE_GETPT precompiler directives, 
+defined in "DEFINES" line. You should select variant which would be correct for your system.
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/default.keytab	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,128 @@
+# [README.default.Keytab] Buildin Keyboard Table
+#
+# To customize your keyboard, copy this file to something
+# ending with .keytab and change it to meet you needs.
+# Please read the README.KeyTab and the README.keyboard
+# in this case.
+#
+# --------------------------------------------------------------
+
+keyboard "Default (XFree 4)"
+
+# --------------------------------------------------------------
+#
+# Note that this particular table is a "risc" version made to
+# ease customization without bothering with obsolete details.
+# See VT100.keytab for the more hairy stuff.
+#
+# --------------------------------------------------------------
+
+# common keys
+
+key Escape             : "\E"
+
+key Tab   -Shift       : "\t"
+key Tab   +Shift+Ansi  : "\E[Z"
+key Tab   +Shift-Ansi  : "\t"
+key Backtab     +Ansi  : "\E[Z"
+key Backtab     -Ansi  : "\t"
+
+key Return-Shift-NewLine : "\r"
+key Return-Shift+NewLine : "\r\n"
+
+key Return+Shift         : "\EOM"
+
+# Backspace and Delete codes are preserving CTRL-H.
+
+key Backspace      : "\x7f"
+
+# Arrow keys in VT52 mode
+# shift up/down are reserved for scrolling.
+# shift left/right are reserved for switching between tabs (this is hardcoded).
+
+key Up   -Shift-Ansi : "\EA"
+key Down -Shift-Ansi : "\EB"
+key Right-Shift-Ansi : "\EC"
+key Left -Shift-Ansi : "\ED"
+
+# Arrow keys in ANSI mode with Application - and Normal Cursor Mode)
+
+key Up    -Shift-AnyMod+Ansi+AppCuKeys           : "\EOA"
+key Down  -Shift-AnyMod+Ansi+AppCuKeys           : "\EOB"
+key Right -Shift-AnyMod+Ansi+AppCuKeys           : "\EOC"
+key Left  -Shift-AnyMod+Ansi+AppCuKeys           : "\EOD"
+
+key Up    -Shift-AnyMod+Ansi-AppCuKeys           : "\E[A"
+key Down  -Shift-AnyMod+Ansi-AppCuKeys           : "\E[B"
+key Right -Shift-AnyMod+Ansi-AppCuKeys           : "\E[C"
+key Left  -Shift-AnyMod+Ansi-AppCuKeys           : "\E[D"
+
+key Up    -Shift+AnyMod+Ansi                     : "\E[1;*A"
+key Down  -Shift+AnyMod+Ansi                     : "\E[1;*B"
+key Right -Shift+AnyMod+Ansi                     : "\E[1;*C"
+key Left  -Shift+AnyMod+Ansi                     : "\E[1;*D"
+
+# other grey PC keys
+
+key Enter+NewLine : "\r\n"
+key Enter-NewLine : "\r"
+
+key Home        -AnyMod     -AppCuKeys           : "\E[H"  
+key End         -AnyMod     -AppCuKeys           : "\E[F"  
+key Home        -AnyMod     +AppCuKeys           : "\EOH"  
+key End         -AnyMod     +AppCuKeys           : "\EOF"  
+key Home        +AnyMod                          : "\E[1;*H"
+key End         +AnyMod                          : "\E[1;*F"
+
+key Insert      -AnyMod                          : "\E[2~"
+key Delete      -AnyMod                          : "\E[3~"
+key Insert      +AnyMod                          : "\E[2;*~"
+key Delete      +AnyMod                          : "\E[3;*~"
+
+key Prior -Shift-AnyMod                          : "\E[5~"
+key Next  -Shift-AnyMod                          : "\E[6~"
+key Prior -Shift+AnyMod                          : "\E[5;*~"
+key Next  -Shift+AnyMod                          : "\E[6;*~"
+
+# Function keys
+key F1          -AnyMod                          : "\EOP"
+key F2          -AnyMod                          : "\EOQ"
+key F3          -AnyMod                          : "\EOR"
+key F4          -AnyMod                          : "\EOS"
+key F5          -AnyMod                          : "\E[15~"
+key F6          -AnyMod                          : "\E[17~"
+key F7          -AnyMod                          : "\E[18~"
+key F8          -AnyMod                          : "\E[19~"
+key F9          -AnyMod                          : "\E[20~"
+key F10         -AnyMod                          : "\E[21~"
+key F11         -AnyMod                          : "\E[23~"
+key F12         -AnyMod                          : "\E[24~"
+
+key F1          +AnyMod                          : "\EO*P"
+key F2          +AnyMod                          : "\EO*Q"
+key F3          +AnyMod                          : "\EO*R"
+key F4          +AnyMod                          : "\EO*S"
+key F5          +AnyMod                          : "\E[15;*~"
+key F6          +AnyMod                          : "\E[17;*~"
+key F7          +AnyMod                          : "\E[18;*~"
+key F8          +AnyMod                          : "\E[19;*~"
+key F9          +AnyMod                          : "\E[20;*~"
+key F10         +AnyMod                          : "\E[21;*~"
+key F11         +AnyMod                          : "\E[23;*~"
+key F12         +AnyMod                          : "\E[24;*~"
+
+# Work around dead keys
+
+key Space +Control : "\x00"
+
+# Some keys are used by konsole to cause operations.
+# The scroll* operations refer to the history buffer.
+
+key Up    +Shift-AppScreen  : scrollLineUp
+key Prior +Shift-AppScreen  : scrollPageUp
+key Down  +Shift-AppScreen  : scrollLineDown
+key Next  +Shift-AppScreen  : scrollPageDown
+
+key ScrollLock     : scrollLock
+
+# keypad characters are not offered differently by Qt.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/kb-layouts/default.keytab	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,133 @@
+# [README.default.Keytab] Buildin Keyboard Table
+#
+# To customize your keyboard, copy this file to something
+# ending with .keytab and change it to meet you needs.
+# Please read the README.KeyTab and the README.keyboard
+# in this case.
+#
+# --------------------------------------------------------------
+
+keyboard "Default (XFree 4)"
+
+# --------------------------------------------------------------
+#
+# Note that this particular table is a "risc" version made to
+# ease customization without bothering with obsolete details.
+# See VT100.keytab for the more hairy stuff.
+#
+# --------------------------------------------------------------
+
+# common keys
+
+key Escape             : "\E"
+
+key Tab   -Shift       : "\t"
+key Tab   +Shift+Ansi  : "\E[Z"
+key Tab   +Shift-Ansi  : "\t"
+key Backtab     +Ansi  : "\E[Z"
+key Backtab     -Ansi  : "\t"
+
+key Return-Shift-NewLine : "\r"
+key Return-Shift+NewLine : "\r\n"
+
+key Return+Shift         : "\EOM"
+
+# Backspace and Delete codes are preserving CTRL-H.
+
+key Backspace      : "\x7f"
+
+# Arrow keys in VT52 mode
+# shift up/down are reserved for scrolling.
+# shift left/right are reserved for switching between tabs (this is hardcoded).
+
+key Up   -Shift-Ansi : "\EA"
+key Down -Shift-Ansi : "\EB"
+key Right-Shift-Ansi : "\EC"
+key Left -Shift-Ansi : "\ED"
+
+# Arrow keys in ANSI mode with Application - and Normal Cursor Mode)
+
+key Up    -Shift-AnyMod+Ansi+AppCuKeys           : "\EOA"
+key Down  -Shift-AnyMod+Ansi+AppCuKeys           : "\EOB"
+key Right -Shift-AnyMod+Ansi+AppCuKeys           : "\EOC"
+key Left  -Shift-AnyMod+Ansi+AppCuKeys           : "\EOD"
+
+key Up    -Shift-AnyMod+Ansi-AppCuKeys           : "\E[A"
+key Down  -Shift-AnyMod+Ansi-AppCuKeys           : "\E[B"
+key Right -Shift-AnyMod+Ansi-AppCuKeys           : "\E[C"
+key Left  -Shift-AnyMod+Ansi-AppCuKeys           : "\E[D"
+
+key Up    -Shift+AnyMod+Ansi                     : "\E[1;*A"
+key Down  -Shift+AnyMod+Ansi                     : "\E[1;*B"
+key Right -Shift+AnyMod+Ansi                     : "\E[1;*C"
+key Left  -Shift+AnyMod+Ansi                     : "\E[1;*D"
+
+# other grey PC keys
+
+key Enter+NewLine : "\r\n"
+key Enter-NewLine : "\r"
+
+key Home        -AnyMod     -AppCuKeys           : "\E[H"  
+key End         -AnyMod     -AppCuKeys           : "\E[F"  
+key Home        -AnyMod     +AppCuKeys           : "\EOH"  
+key End         -AnyMod     +AppCuKeys           : "\EOF"  
+key Home        +AnyMod                          : "\E[1;*H"
+key End         +AnyMod                          : "\E[1;*F"
+
+key Insert      -AnyMod                          : "\E[2~"
+key Delete      -AnyMod                          : "\E[3~"
+key Insert      +AnyMod                          : "\E[2;*~"
+key Delete      +AnyMod                          : "\E[3;*~"
+
+key Prior -Shift-AnyMod                          : "\E[5~"
+key Next  -Shift-AnyMod                          : "\E[6~"
+key Prior -Shift+AnyMod                          : "\E[5;*~"
+key Next  -Shift+AnyMod                          : "\E[6;*~"
+
+# Function keys
+key F1          -AnyMod                          : "\EOP"
+key F2          -AnyMod                          : "\EOQ"
+key F3          -AnyMod                          : "\EOR"
+key F4          -AnyMod                          : "\EOS"
+key F5          -AnyMod                          : "\E[15~"
+key F6          -AnyMod                          : "\E[17~"
+key F7          -AnyMod                          : "\E[18~"
+key F8          -AnyMod                          : "\E[19~"
+key F9          -AnyMod                          : "\E[20~"
+key F10         -AnyMod                          : "\E[21~"
+key F11         -AnyMod                          : "\E[23~"
+key F12         -AnyMod                          : "\E[24~"
+
+key F1          +AnyMod                          : "\EO*P"
+key F2          +AnyMod                          : "\EO*Q"
+key F3          +AnyMod                          : "\EO*R"
+key F4          +AnyMod                          : "\EO*S"
+key F5          +AnyMod                          : "\E[15;*~"
+key F6          +AnyMod                          : "\E[17;*~"
+key F7          +AnyMod                          : "\E[18;*~"
+key F8          +AnyMod                          : "\E[19;*~"
+key F9          +AnyMod                          : "\E[20;*~"
+key F10         +AnyMod                          : "\E[21;*~"
+key F11         +AnyMod                          : "\E[23;*~"
+key F12         +AnyMod                          : "\E[24;*~"
+
+# Work around dead keys
+
+key Space +Control : "\x00"
+
+# Some keys are used by konsole to cause operations.
+# The scroll* operations refer to the history buffer.
+
+key Up    +Shift-AppScreen  : scrollLineUp
+key Prior +Shift-AppScreen  : scrollPageUp
+key Down  +Shift-AppScreen  : scrollLineDown
+key Next  +Shift-AppScreen  : scrollPageDown
+
+#key Up    +Shift  : scrollLineUp
+#key Prior +Shift  : scrollPageUp
+#key Down  +Shift  : scrollLineDown
+#key Next  +Shift  : scrollPageDown
+
+key ScrollLock     : scrollLock
+
+# keypad characters are not offered differently by Qt.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/kb-layouts/linux.keytab	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,133 @@
+# [linux.keytab] Konsole Keyboard Table (Linux console keys)
+#
+# --------------------------------------------------------------
+
+# NOT TESTED, MAY NEED SOME CLEANUPS
+keyboard "Linux console"
+
+# --------------------------------------------------------------
+#
+# This configuration table allows to customize the
+# meaning of the keys.
+#
+# The syntax is that each entry has the form : 
+#
+#   "key" Keyname { ("+"|"-") Modename } ":" (String|Operation)
+#
+# Keynames are those defined in <qnamespace.h> with the
+# "Qt::Key_" removed. (We'd better insert the list here)
+#
+# Mode names are : 
+#
+# - Shift
+# - Alt
+# - Control
+#
+#   The VT100 emulation has two modes that can affect the
+#   sequences emitted by certain keys. These modes are
+#   under control of the client program.
+#   
+# - Newline     : effects Return and Enter key.
+# - Application : effects Up and Down key.
+#
+# - Ansi        : effects Up and Down key (This is for VT52, really).
+#
+# Operations are
+#
+# - scrollUpLine
+# - scrollUpPage
+# - scrollDownLine
+# - scrollDownPage
+#
+# - emitSelection
+#
+# If the key is not found here, the text of the
+# key event as provided by QT is emitted, possibly
+# preceeded by ESC if the Alt key is pressed.
+#
+# --------------------------------------------------------------
+
+key Escape : "\E"
+key Tab    : "\t"
+
+# VT100 can add an extra \n after return.
+# The NewLine mode is set by an escape sequence.
+
+key Return-NewLine : "\r"  
+key Return+NewLine : "\r\n"
+
+# Some desperately try to save the ^H.
+
+key Backspace : "\x7f"
+key Delete    : "\E[3~"
+
+# These codes are for the VT52 mode of VT100
+# The Ansi mode (i.e. VT100 mode) is set by
+# an escape sequence
+
+key Up   -Shift-Ansi : "\EA"
+key Down -Shift-Ansi : "\EB"
+key Right-Shift-Ansi : "\EC"
+key Left -Shift-Ansi : "\ED"
+
+# VT100 emits a mode bit together
+# with the arrow keys.The AppCuKeys
+# mode is set by an escape sequence.
+
+key Up   -Shift+Ansi+AppCuKeys : "\EOA"
+key Down -Shift+Ansi+AppCuKeys : "\EOB"
+key Right-Shift+Ansi+AppCuKeys : "\EOC"
+key Left -Shift+Ansi+AppCuKeys : "\EOD"
+
+key Up   -Shift+Ansi-AppCuKeys : "\E[A"
+key Down -Shift+Ansi-AppCuKeys : "\E[B"
+key Right-Shift+Ansi-AppCuKeys : "\E[C"
+key Left -Shift+Ansi-AppCuKeys : "\E[D"
+
+# linux functions keys F1-F5 differ from xterm
+
+key F1 : "\E[[A" 
+key F2 : "\E[[B" 
+key F3 : "\E[[C" 
+key F4 : "\E[[D" 
+key F5 : "\E[[E" 
+
+key F6     : "\E[17~" 
+key F7     : "\E[18~" 
+key F8     : "\E[19~" 
+key F9     : "\E[20~" 
+key F10    : "\E[21~" 
+key F11    : "\E[23~" 
+key F12    : "\E[24~" 
+
+key Home   : "\E[1~"  
+key End    : "\E[4~"  
+
+key Prior -Shift : "\E[5~"  
+key Next  -Shift : "\E[6~"  
+key Insert-Shift : "\E[2~"  
+
+# Keypad-Enter. See comment on Return above.
+
+key Enter+NewLine : "\r\n"
+key Enter-NewLine : "\r"  
+
+key Space +Control : "\x00"
+
+# some of keys are used by konsole.
+
+key Up    +Shift   : scrollLineUp
+key Prior +Shift   : scrollPageUp
+key Down  +Shift   : scrollLineDown
+key Next  +Shift   : scrollPageDown
+
+key ScrollLock     : scrollLock
+
+#----------------------------------------------------------
+
+# keypad characters as offered by Qt
+# cannot be recognized as such.
+
+#----------------------------------------------------------
+
+# Following other strings as emitted by konsole.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/kb-layouts/vt420pc.keytab	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,163 @@
+# [vt420pc.keytab] Konsole Keyboard Table (VT420pc keys)
+# adapted by ferdinand gassauer f.gassauer@aon.at
+# Nov 2000
+#
+################################################################
+#
+# The escape sequences emmited by the 
+# keys Shift+F1 to Shift+F12 might not fit your needs
+#
+################# IMPORTANT NOTICE #############################
+# the key bindings (Kcontrol -> look and feel -> keybindgs) 
+# overrule the settings in this file. The key bindings might be 
+# changed by the user WITHOUT notification of the maintainer of
+# the keytab file. Konsole will not work as expected by 
+# the maintainer of the keytab file.
+################################################################
+#
+# --------------------------------------------------------------
+
+keyboard "DEC VT420 Terminal"
+
+# --------------------------------------------------------------
+#
+# This configuration table allows to customize the
+# meaning of the keys.
+#
+# The syntax is that each entry has the form : 
+#
+#   "key" Keyname { ("+"|"-") Modename } ":" (String|Operation)
+#
+# Keynames are those defined in <qnamespace.h> with the
+# "Qt::Key_" removed. (We'd better insert the list here)
+#
+# Mode names are : 
+#
+# - Shift
+# - Alt
+# - Control
+#
+#   The VT100 emulation has two modes that can affect the
+#   sequences emitted by certain keys. These modes are
+#   under control of the client program.
+#   
+# - Newline     : effects Return and Enter key.
+# - Application : effects Up and Down key.
+#
+# - Ansi        : effects Up and Down key (This is for VT52, really).
+#
+# Operations are
+#
+# - scrollUpLine
+# - scrollUpPage
+# - scrollDownLine
+# - scrollDownPage
+#
+# - emitSelection
+#
+# If the key is not found here, the text of the
+# key event as provided by QT is emitted, possibly
+# preceeded by ESC if the Alt key is pressed.
+#
+# --------------------------------------------------------------
+
+key Escape : "\E"
+key Tab    : "\t"
+key Backtab: "\E[Z"
+
+# VT100 can add an extra \n after return.
+# The NewLine mode is set by an escape sequence.
+
+key Return-NewLine : "\r"  
+key Return+NewLine : "\r\n"
+
+# Some desperately try to save the ^H.
+# may be not everyone wants this
+
+key Backspace : "\x08"  # Control H
+key Delete    : "\x7f"
+
+# These codes are for the VT420pc
+# The Ansi mode (i.e. VT100 mode) is set by
+# an escape sequence
+
+key Up   -Shift-Ansi : "\EA"
+key Down -Shift-Ansi : "\EB"
+key Right-Shift-Ansi : "\EC"
+key Left -Shift-Ansi : "\ED"
+
+# VT100 emits a mode bit together
+# with the arrow keys.The AppCuKeys
+# mode is set by an escape sequence.
+
+key Up   -Shift+Ansi+AppCuKeys : "\EOA"
+key Down -Shift+Ansi+AppCuKeys : "\EOB"
+key Right-Shift+Ansi+AppCuKeys : "\EOC"
+key Left -Shift+Ansi+AppCuKeys : "\EOD"
+
+key Up   -Shift+Ansi-AppCuKeys : "\E[A"
+key Down -Shift+Ansi-AppCuKeys : "\E[B"
+key Right-Shift+Ansi-AppCuKeys : "\E[C"
+key Left -Shift+Ansi-AppCuKeys : "\E[D"
+
+# function keys 
+
+key F1 -Shift    : "\E[11~"  
+key F2 -Shift    : "\E[12~"
+key F3 -Shift    : "\E[13~"
+key F4 -Shift    : "\E[14~"
+key F5 -Shift    : "\E[15~"
+key F6 -Shift    : "\E[17~"
+key F7 -Shift    : "\E[18~"
+key F8 -Shift    : "\E[19~"
+key F9 -Shift    : "\E[20~"
+key F10-Shift    : "\E[21~"
+key F11-Shift    : "\E[23~"
+key F12-Shift    : "\E[24~"  
+#
+# Shift F1-F12
+#
+key F1 +Shift    : "\E[11;2~"
+key F2 +Shift    : "\E[12;2~"
+key F3 +Shift    : "\E[13;2~"
+key F4 +Shift    : "\E[14;2~"
+key F5 +Shift    : "\E[15;2~"
+key F6 +Shift    : "\E[17;2~" 
+key F7 +Shift    : "\E[18;2~" 
+key F8 +Shift    : "\E[19;2~" 
+key F9 +Shift    : "\E[20;2~" 
+key F10+Shift    : "\E[21;2~" 
+key F11+Shift    : "\E[23;2~" 
+key F12+Shift    : "\E[24;2~" 
+
+key Home   : "\E[H"  
+key End    : "\E[F"  
+
+key Prior -Shift : "\E[5~"  
+key Next  -Shift : "\E[6~"  
+key Insert-Shift : "\E[2~"  
+
+# Keypad-Enter. See comment on Return above.
+
+key Enter+NewLine : "\r\n"
+key Enter-NewLine : "\r"  
+
+key Space +Control : "\x00"
+
+# some of keys are used by konsole.
+
+key Up    +Shift   : scrollLineUp
+key Prior +Shift   : scrollPageUp
+key Down  +Shift   : scrollLineDown
+key Next  +Shift   : scrollPageDown
+
+key ScrollLock     : scrollLock
+
+#----------------------------------------------------------
+
+# keypad characters as offered by Qt
+# cannot be recognized as such.
+
+#----------------------------------------------------------
+
+# Following other strings as emitted by konsole.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/libqterminal.pro	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,68 @@
+TEMPLATE	= lib
+VERSION		= 0.1.0
+TARGET		= qterminal
+
+CONFIG		+= qt staticlib
+
+QT += core gui
+
+INCLUDEPATH	+= .
+
+unix {
+
+DEFINES 	+= HAVE_POSIX_OPENPT HAVE_PTY_H HAVE_OPENPTY
+#or DEFINES 	+= HAVE_GETPT
+
+HEADERS  = unix/BlockArray.h \
+           unix/Character.h \
+           unix/CharacterColor.h \
+           unix/Emulation.h \
+           unix/ExtendedDefaultTranslator.h \
+           unix/Filter.h \
+           unix/History.h \
+           unix/KeyboardTranslator.h \
+           unix/konsole_wcwidth.h \
+           unix/kpty.h \
+           unix/kpty_p.h \
+           unix/LineFont.h \
+           unix/QUnixTerminalImpl.h \
+           unix/Screen.h \
+           unix/ScreenWindow.h \
+           unix/TerminalCharacterDecoder.h \
+           unix/Vt102Emulation.h \
+         unix/SelfListener.h \
+           unix/TerminalModel.h \
+           unix/TerminalView.h
+
+SOURCES  = unix/BlockArray.cpp \
+           unix/Emulation.cpp \
+           unix/Filter.cpp \
+           unix/History.cpp \
+           unix/KeyboardTranslator.cpp \
+           unix/konsole_wcwidth.cpp \
+           unix/kpty.cpp \
+           unix/QUnixTerminalImpl.cpp \
+           unix/Screen.cpp \
+           unix/ScreenWindow.cpp \
+           unix/TerminalCharacterDecoder.cpp \
+           unix/Vt102Emulation.cpp \
+         unix/SelfListener.cpp \
+           unix/TerminalModel.cpp \
+           unix/TerminalView.cpp
+}
+
+win32 {
+HEADERS  = win32/QTerminalColors.h \
+       win32/QWinTerminalImpl.h
+
+SOURCES  = win32/QTerminalColors.cpp \
+       win32/QWinTerminalImpl.cpp
+}
+
+win32-msvc* {
+  include(../msvc.pri)
+}
+
+HEADERS  += QTerminal.h \
+       QTerminal \
+    QTerminalInterface.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/BlockArray.cpp	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,336 @@
+/*
+    This file is part of Konsole, an X terminal.
+    Copyright (C) 2000 by Stephan Kulow <coolo@kde.org>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+
+*/
+
+// Own
+#include "unix/BlockArray.h"
+
+#include <QtCore>
+
+// System
+#include <assert.h>
+#include <sys/mman.h>
+#include <sys/param.h>
+#include <unistd.h>
+#include <stdio.h>
+
+
+static int blocksize = 0;
+
+BlockArray::BlockArray()
+    : size(0),
+      current(size_t(-1)),
+      index(size_t(-1)),
+      lastmap(0),
+      lastmap_index(size_t(-1)),
+      lastblock(0), ion(-1),
+      length(0)
+{
+    // lastmap_index = index = current = size_t(-1);
+    if (blocksize == 0)
+        blocksize = ((sizeof(Block) / getpagesize()) + 1) * getpagesize();
+
+}
+
+BlockArray::~BlockArray()
+{
+    setHistorySize(0);
+    assert(!lastblock);
+}
+
+size_t BlockArray::append(Block *block)
+{
+    if (!size)
+        return size_t(-1);
+
+    ++current;
+    if (current >= size) current = 0;
+
+    int rc;
+    rc = lseek(ion, current * blocksize, SEEK_SET); if (rc < 0) { perror("HistoryBuffer::add.seek"); setHistorySize(0); return size_t(-1); }
+    rc = write(ion, block, blocksize); if (rc < 0) { perror("HistoryBuffer::add.write"); setHistorySize(0); return size_t(-1); }
+
+    length++;
+    if (length > size) length = size;
+
+    ++index;
+
+    delete block;
+    return current;
+}
+
+size_t BlockArray::newBlock()
+{
+    if (!size)
+        return size_t(-1);
+    append(lastblock);
+
+    lastblock = new Block();
+    return index + 1;
+}
+
+Block *BlockArray::lastBlock() const
+{
+    return lastblock;
+}
+
+bool BlockArray::has(size_t i) const
+{
+    if (i == index + 1)
+        return true;
+
+    if (i > index)
+        return false;
+    if (index - i >= length)
+        return false;
+    return true;
+}
+
+const Block* BlockArray::at(size_t i)
+{
+    if (i == index + 1)
+        return lastblock;
+
+    if (i == lastmap_index)
+        return lastmap;
+
+    if (i > index) {
+        qDebug() << "BlockArray::at() i > index\n";
+        return 0;
+    }
+    
+//     if (index - i >= length) {
+//         kDebug(1211) << "BlockArray::at() index - i >= length\n";
+//         return 0;
+//     }
+
+    size_t j = i; // (current - (index - i) + (index/size+1)*size) % size ;
+
+    assert(j < size);
+    unmap();
+
+    Block *block = (Block*)mmap(0, blocksize, PROT_READ, MAP_PRIVATE, ion, j * blocksize);
+
+    if (block == (Block*)-1) { perror("mmap"); return 0; }
+
+    lastmap = block;
+    lastmap_index = i;
+
+    return block;
+}
+
+void BlockArray::unmap()
+{
+    if (lastmap) {
+        int res = munmap((char*)lastmap, blocksize);
+        if (res < 0) perror("munmap");
+    }
+    lastmap = 0;
+    lastmap_index = size_t(-1);
+}
+
+bool BlockArray::setSize(size_t newsize)
+{
+    return setHistorySize(newsize * 1024 / blocksize);
+}
+
+bool BlockArray::setHistorySize(size_t newsize)
+{
+//    kDebug(1211) << "setHistorySize " << size << " " << newsize;
+
+    if (size == newsize)
+        return false;
+
+    unmap();
+
+    if (!newsize) {
+        delete lastblock;
+        lastblock = 0;
+        if (ion >= 0) close(ion);
+        ion = -1;
+        current = size_t(-1);
+        return true;
+    }
+
+    if (!size) {
+        FILE* tmp = tmpfile();
+        if (!tmp) {
+            perror("konsole: cannot open temp file.\n");
+        } else {
+            ion = dup(fileno(tmp));
+            if (ion<0) {
+                perror("konsole: cannot dup temp file.\n");
+                fclose(tmp);
+            }
+        }
+        if (ion < 0)
+            return false;
+
+        assert(!lastblock);
+
+        lastblock = new Block();
+        size = newsize;
+        return false;
+    }
+
+    if (newsize > size) {
+        increaseBuffer();
+        size = newsize;
+        return false;
+    } else {
+        decreaseBuffer(newsize);
+        if (ftruncate(ion, length*blocksize) == -1)
+		  perror("ftruncate");
+        size = newsize;
+
+        return true;
+    }
+}
+
+void moveBlock(FILE *fion, int cursor, int newpos, char *buffer2)
+{
+    int res = fseek(fion, cursor * blocksize, SEEK_SET);
+    if (res)
+        perror("fseek");
+    res = fread(buffer2, blocksize, 1, fion);
+    if (res != 1)
+        perror("fread");
+
+    res = fseek(fion, newpos * blocksize, SEEK_SET);
+    if (res)
+        perror("fseek");
+    res = fwrite(buffer2, blocksize, 1, fion);
+    if (res != 1)
+        perror("fwrite");
+    //    printf("moving block %d to %d\n", cursor, newpos);
+}
+
+void BlockArray::decreaseBuffer(size_t newsize)
+{
+    if (index < newsize) // still fits in whole
+        return;
+
+    int offset = (current - (newsize - 1) + size) % size;
+
+    if (!offset)
+        return;
+
+    // The Block constructor could do somthing in future...
+    char *buffer1 = new char[blocksize];
+
+    FILE *fion = fdopen(dup(ion), "w+b");
+    if (!fion) {
+        delete [] buffer1;
+        perror("fdopen/dup");
+        return;
+    }
+
+    int firstblock;
+    if (current <= newsize) {
+        firstblock = current + 1;
+    } else {
+        firstblock = 0;
+    }
+
+    size_t oldpos;
+    for (size_t i = 0, cursor=firstblock; i < newsize; i++) {
+        oldpos = (size + cursor + offset) % size;
+        moveBlock(fion, oldpos, cursor, buffer1);
+        if (oldpos < newsize) {
+            cursor = oldpos;
+        } else
+            cursor++;
+    }
+
+    current = newsize - 1;
+    length = newsize;
+
+    delete [] buffer1;
+
+    fclose(fion);
+
+}
+
+void BlockArray::increaseBuffer()
+{
+    if (index < size) // not even wrapped once
+        return;
+
+    int offset = (current + size + 1) % size;
+    if (!offset) // no moving needed
+        return;
+
+    // The Block constructor could do somthing in future...
+    char *buffer1 = new char[blocksize];
+    char *buffer2 = new char[blocksize];
+
+    int runs = 1;
+    int bpr = size; // blocks per run
+
+    if (size % offset == 0) {
+        bpr = size / offset;
+        runs = offset;
+    }
+
+    FILE *fion = fdopen(dup(ion), "w+b");
+    if (!fion) {
+        perror("fdopen/dup");
+	delete [] buffer1;
+	delete [] buffer2;
+        return;
+    }
+
+    int res;
+    for (int i = 0; i < runs; i++)
+    {
+        // free one block in chain
+        int firstblock = (offset + i) % size;
+        res = fseek(fion, firstblock * blocksize, SEEK_SET);
+        if (res)
+            perror("fseek");
+        res = fread(buffer1, blocksize, 1, fion);
+        if (res != 1)
+            perror("fread");
+        int newpos = 0;
+        for (int j = 1, cursor=firstblock; j < bpr; j++)
+        {
+            cursor = (cursor + offset) % size;
+            newpos = (cursor - offset + size) % size;
+            moveBlock(fion, cursor, newpos, buffer2);
+        }
+        res = fseek(fion, i * blocksize, SEEK_SET);
+        if (res)
+            perror("fseek");
+        res = fwrite(buffer1, blocksize, 1, fion);
+        if (res != 1)
+            perror("fwrite");
+    }
+    current = size - 1;
+    length = size;
+
+    delete [] buffer1;
+    delete [] buffer2;
+
+    fclose(fion);
+
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/BlockArray.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,118 @@
+/*
+    This file is part of Konsole, an X terminal.
+    Copyright (C) 2000 by Stephan Kulow <coolo@kde.org>
+   
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+#ifndef BLOCKARRAY_H
+#define BLOCKARRAY_H
+
+#include <unistd.h>
+
+#define BlockSize (1 << 12)
+#define ENTRIES   ((BlockSize - sizeof(size_t) ) / sizeof(unsigned char))
+
+struct Block {
+    Block() { size = 0; }
+    unsigned char data[ENTRIES];
+    size_t size;
+};
+
+// ///////////////////////////////////////////////////////
+
+class BlockArray {
+public:
+    /**
+    * Creates a history file for holding
+    * maximal size blocks. If more blocks
+    * are requested, then it drops earlier
+    * added ones.
+    */
+    BlockArray();
+
+    /// destructor
+    ~BlockArray();
+
+    /**
+    * adds the Block at the end of history.
+    * This may drop other blocks.
+    *
+    * The ownership on the block is transfered.
+    * An unique index number is returned for accessing
+    * it later (if not yet dropped then)
+    *
+    * Note, that the block may be dropped completely
+    * if history is turned off.
+    */
+    size_t append(Block *block);
+
+    /**
+    * gets the block at the index. Function may return
+    * 0 if the block isn't available any more.
+    *
+    * The returned block is strictly readonly as only
+    * maped in memory - and will be invalid on the next
+    * operation on this class.
+    */
+    const Block *at(size_t index);
+
+    /**
+    * reorders blocks as needed. If newsize is null,
+    * the history is emptied completely. The indices
+    * returned on append won't change their semantic,
+    * but they may not be valid after this call.
+    */
+    bool setHistorySize(size_t newsize);
+
+    size_t newBlock();
+
+    Block *lastBlock() const;
+
+    /**
+    * Convenient function to set the size in KBytes
+    * instead of blocks
+    */
+    bool setSize(size_t newsize);
+
+    size_t len() const { return length; }
+
+    bool has(size_t index) const;
+
+    size_t getCurrent() const { return current; }
+
+private:
+    void unmap();
+    void increaseBuffer();
+    void decreaseBuffer(size_t newsize);
+
+    size_t size;
+    // current always shows to the last inserted block
+    size_t current;
+    size_t index;
+
+    Block *lastmap;
+    size_t lastmap_index;
+    Block *lastblock;
+
+    int ion;
+    size_t length;
+
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/Character.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,205 @@
+/*
+    This file is part of Konsole, KDE's terminal.
+    
+    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
+    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+#ifndef CHARACTER_H
+#define CHARACTER_H
+
+// Qt
+#include <QtCore/QHash>
+
+// Local
+#include "unix/CharacterColor.h"
+
+typedef unsigned char LineProperty;
+
+static const int LINE_DEFAULT		= 0;
+static const int LINE_WRAPPED 	 	= (1 << 0);
+static const int LINE_DOUBLEWIDTH  	= (1 << 1);
+static const int LINE_DOUBLEHEIGHT	= (1 << 2);
+
+#define DEFAULT_RENDITION  0
+#define RE_BOLD            (1 << 0)
+#define RE_BLINK           (1 << 1)
+#define RE_UNDERLINE       (1 << 2)
+#define RE_REVERSE         (1 << 3) // Screen only
+#define RE_INTENSIVE       (1 << 3) // Widget only
+#define RE_CURSOR          (1 << 4)
+#define RE_EXTENDED_CHAR   (1 << 5)
+
+/**
+ * A single character in the terminal which consists of a unicode character
+ * value, foreground and background colors and a set of rendition attributes
+ * which specify how it should be drawn.
+ */
+class Character
+{
+public:
+  /** 
+   * Constructs a new character.
+   *
+   * @param _c The unicode character value of this character.
+   * @param _f The foreground color used to draw the character.
+   * @param _b The color used to draw the character's background.
+   * @param _r A set of rendition flags which specify how this character is to be drawn.
+   */
+  inline Character(quint16 _c = ' ',
+            CharacterColor  _f = CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR),
+            CharacterColor  _b = CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR),
+            quint8  _r = DEFAULT_RENDITION)
+       : character(_c), rendition(_r), foregroundColor(_f), backgroundColor(_b) {}
+
+  union
+  {
+    /** The unicode character value for this character. */
+    quint16 character;
+    /** 
+     * Experimental addition which allows a single Character instance to contain more than
+     * one unicode character.
+     *
+     * charSequence is a hash code which can be used to look up the unicode
+     * character sequence in the ExtendedCharTable used to create the sequence.
+     */
+    quint16 charSequence; 
+  };
+
+  /** A combination of RENDITION flags which specify options for drawing the character. */
+  quint8  rendition;
+
+  /** The foreground color used to draw this character. */
+  CharacterColor  foregroundColor; 
+  /** The color used to draw this character's background. */
+  CharacterColor  backgroundColor;
+
+  /** 
+   * Returns true if this character has a transparent background when
+   * it is drawn with the specified @p palette.
+   */
+  bool   isTransparent(const ColorEntry* palette) const;
+  /**
+   * Returns true if this character should always be drawn in bold when
+   * it is drawn with the specified @p palette, independent of whether
+   * or not the character has the RE_BOLD rendition flag. 
+   */
+  bool   isBold(const ColorEntry* base) const;
+  
+  /** 
+   * Compares two characters and returns true if they have the same unicode character value,
+   * rendition and colors.
+   */
+  friend bool operator == (const Character& a, const Character& b);
+  /**
+   * Compares two characters and returns true if they have different unicode character values,
+   * renditions or colors.
+   */
+  friend bool operator != (const Character& a, const Character& b);
+};
+
+inline bool operator == (const Character& a, const Character& b)
+{ 
+  return a.character == b.character && 
+         a.rendition == b.rendition && 
+         a.foregroundColor == b.foregroundColor && 
+         a.backgroundColor == b.backgroundColor;
+}
+
+inline bool operator != (const Character& a, const Character& b)
+{
+  return    a.character != b.character || 
+            a.rendition != b.rendition || 
+            a.foregroundColor != b.foregroundColor || 
+            a.backgroundColor != b.backgroundColor;
+}
+
+inline bool Character::isTransparent(const ColorEntry* base) const
+{
+  return ((backgroundColor._colorSpace == COLOR_SPACE_DEFAULT) && 
+          base[backgroundColor._u+0+(backgroundColor._v?BASE_COLORS:0)].transparent)
+      || ((backgroundColor._colorSpace == COLOR_SPACE_SYSTEM) && 
+          base[backgroundColor._u+2+(backgroundColor._v?BASE_COLORS:0)].transparent);
+}
+
+inline bool Character::isBold(const ColorEntry* base) const
+{
+  return ((backgroundColor._colorSpace == COLOR_SPACE_DEFAULT) &&
+            base[backgroundColor._u+0+(backgroundColor._v?BASE_COLORS:0)].bold)
+      || ((backgroundColor._colorSpace == COLOR_SPACE_SYSTEM) &&
+            base[backgroundColor._u+2+(backgroundColor._v?BASE_COLORS:0)].bold);
+}
+
+extern unsigned short vt100_graphics[32];
+
+
+/**
+ * A table which stores sequences of unicode characters, referenced
+ * by hash keys.  The hash key itself is the same size as a unicode
+ * character ( ushort ) so that it can occupy the same space in
+ * a structure.
+ */
+class ExtendedCharTable
+{
+public:
+    /** Constructs a new character table. */
+    ExtendedCharTable();
+    ~ExtendedCharTable();
+
+    /**
+     * Adds a sequences of unicode characters to the table and returns
+     * a hash code which can be used later to look up the sequence
+     * using lookupExtendedChar()
+     *
+     * If the same sequence already exists in the table, the hash
+     * of the existing sequence will be returned.
+     *
+     * @param unicodePoints An array of unicode character points
+     * @param length Length of @p unicodePoints
+     */
+    ushort createExtendedChar(ushort* unicodePoints , ushort length);
+    /**
+     * Looks up and returns a pointer to a sequence of unicode characters
+     * which was added to the table using createExtendedChar().
+     *
+     * @param hash The hash key returned by createExtendedChar()
+     * @param length This variable is set to the length of the 
+     * character sequence.
+     *
+     * @return A unicode character sequence of size @p length.
+     */
+    ushort* lookupExtendedChar(ushort hash , ushort& length) const;
+
+    /** The global ExtendedCharTable instance. */
+    static ExtendedCharTable instance;
+private:
+    // calculates the hash key of a sequence of unicode points of size 'length'
+    ushort extendedCharHash(ushort* unicodePoints , ushort length) const;
+    // tests whether the entry in the table specified by 'hash' matches the 
+    // character sequence 'unicodePoints' of size 'length'
+    bool extendedCharMatch(ushort hash , ushort* unicodePoints , ushort length) const;
+    // internal, maps hash keys to character sequence buffers.  The first ushort
+    // in each value is the length of the buffer, followed by the ushorts in the buffer
+    // themselves.
+    QHash<ushort,ushort*> extendedCharTable;
+};
+
+#endif // CHARACTER_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/CharacterColor.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,292 @@
+/*
+    This file is part of Konsole, KDE's terminal.
+    
+    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
+    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+#ifndef CHARACTERCOLOR_H
+#define CHARACTERCOLOR_H
+
+// Qt
+#include <QtGui/QColor>
+
+/** 
+ * An entry in a terminal display's color palette. 
+ *
+ * A color palette is an array of 16 ColorEntry instances which map
+ * system color indexes (from 0 to 15) into actual colors.
+ *
+ * Each entry can be set as bold, in which case any text
+ * drawn using the color should be drawn in bold.  
+ *
+ * Each entry can also be transparent, in which case the terminal
+ * display should avoid drawing the background for any characters
+ * using the entry as a background.
+ */
+class ColorEntry
+{
+public:
+  /** 
+   * Constructs a new color palette entry.
+   *
+   * @param c The color value for this entry.
+   * @param tr Specifies that the color should be transparent when used as a background color.
+   * @param b Specifies that text drawn with this color should be bold.
+   */
+  ColorEntry(QColor c, bool tr, bool b) : color(c), transparent(tr), bold(b) {}
+
+  /**
+   * Constructs a new color palette entry with an undefined color, and
+   * with the transparent and bold flags set to false.
+   */ 
+  ColorEntry() : transparent(false), bold(false) {} 
+ 
+  /**
+   * Sets the color, transparency and boldness of this color to those of @p rhs.
+   */ 
+  void operator=(const ColorEntry& rhs) 
+  { 
+       color = rhs.color; 
+       transparent = rhs.transparent; 
+       bold = rhs.bold; 
+  }
+
+  /** The color value of this entry for display. */
+  QColor color;
+
+  /** 
+   * If true character backgrounds using this color should be transparent. 
+   * This is not applicable when the color is used to render text.
+   */
+  bool   transparent;
+  /**
+   * If true characters drawn using this color should be bold.
+   * This is not applicable when the color is used to draw a character's background.
+   */
+  bool   bold;        
+};
+
+
+// Attributed Character Representations ///////////////////////////////
+
+// Colors
+
+#define BASE_COLORS   (2+8)
+#define INTENSITIES   2
+#define TABLE_COLORS  (INTENSITIES*BASE_COLORS)
+
+#define DEFAULT_FORE_COLOR 0
+#define DEFAULT_BACK_COLOR 1
+
+//a standard set of colors using black text on a white background.
+//defined in TerminalDisplay.cpp
+
+static const ColorEntry base_color_table[TABLE_COLORS] =
+{
+    // normal
+    ColorEntry(QColor(0x00,0x00,0x00), 1, 0 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 0, 0 ), // Dfore, Dback
+    ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0x18), 0, 0 ), // Black, Red
+    ColorEntry(QColor(0x18,0xB2,0x18), 0, 0 ), ColorEntry( QColor(0xB2,0x68,0x18), 0, 0 ), // Green, Yellow
+    ColorEntry(QColor(0x18,0x18,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0xB2), 0, 0 ), // Blue, Magenta
+    ColorEntry(QColor(0x18,0xB2,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 0, 0 ), // Cyan, White
+    // intensiv
+    ColorEntry(QColor(0x00,0x00,0x00), 0, 1 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 1, 0 ),
+    ColorEntry(QColor(0x68,0x68,0x68), 0, 0 ), ColorEntry( QColor(0xFF,0x54,0x54), 0, 0 ),
+    ColorEntry(QColor(0x54,0xFF,0x54), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0x54), 0, 0 ),
+    ColorEntry(QColor(0x54,0x54,0xFF), 0, 0 ), ColorEntry( QColor(0xFF,0x54,0xFF), 0, 0 ),
+    ColorEntry(QColor(0x54,0xFF,0xFF), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 0, 0 )
+};
+
+/* CharacterColor is a union of the various color spaces.
+
+   Assignment is as follows:
+
+   Type  - Space        - Values
+
+   0     - Undefined   - u:  0,      v:0        w:0
+   1     - Default     - u:  0..1    v:intense  w:0
+   2     - System      - u:  0..7    v:intense  w:0
+   3     - Index(256)  - u: 16..255  v:0        w:0
+   4     - RGB         - u:  0..255  v:0..256   w:0..256
+
+   Default colour space has two separate colours, namely
+   default foreground and default background colour.
+*/
+
+#define COLOR_SPACE_UNDEFINED   0
+#define COLOR_SPACE_DEFAULT     1
+#define COLOR_SPACE_SYSTEM      2
+#define COLOR_SPACE_256         3
+#define COLOR_SPACE_RGB         4
+
+/**
+ * Describes the color of a single character in the terminal.
+ */
+class CharacterColor
+{
+    friend class Character;
+
+public:
+  /** Constructs a new CharacterColor whoose color and color space are undefined. */
+  CharacterColor() 
+      : _colorSpace(COLOR_SPACE_UNDEFINED), 
+        _u(0), 
+        _v(0), 
+        _w(0) 
+  {}
+
+  /** 
+   * Constructs a new CharacterColor using the specified @p colorSpace and with 
+   * color value @p co
+   *
+   * The meaning of @p co depends on the @p colorSpace used.
+   *
+   * TODO : Document how @p co relates to @p colorSpace
+   *
+   * TODO : Add documentation about available color spaces.
+   */
+  CharacterColor(quint8 colorSpace, int co) 
+      : _colorSpace(colorSpace), 
+        _u(0), 
+        _v(0), 
+        _w(0)
+  {
+    switch (colorSpace)
+    {
+        case COLOR_SPACE_DEFAULT:
+            _u = co & 1;
+            break;
+        case COLOR_SPACE_SYSTEM:
+            _u = co & 7;
+            _v = (co >> 3) & 1;
+            break;
+        case COLOR_SPACE_256:  
+            _u = co & 255;
+            break;
+        case COLOR_SPACE_RGB:
+            _u = co >> 16;
+            _v = co >> 8;
+            _w = co;
+            break;
+        default:
+            _colorSpace = COLOR_SPACE_UNDEFINED;
+    }
+  }
+
+  /** 
+   * Returns true if this character color entry is valid.
+   */
+  bool isValid() 
+  {
+        return _colorSpace != COLOR_SPACE_UNDEFINED;
+  }
+    
+  /** 
+   * Toggles the value of this color between a normal system color and the corresponding intensive
+   * system color.
+   * 
+   * This is only applicable if the color is using the COLOR_SPACE_DEFAULT or COLOR_SPACE_SYSTEM
+   * color spaces.
+   */
+  void toggleIntensive();
+
+  /** 
+   * Returns the color within the specified color @palette
+   *
+   * The @p palette is only used if this color is one of the 16 system colors, otherwise
+   * it is ignored.
+   */
+  QColor color(const ColorEntry* palette) const;
+ 
+  /** 
+   * Compares two colors and returns true if they represent the same color value and
+   * use the same color space.
+   */
+  friend bool operator == (const CharacterColor& a, const CharacterColor& b);
+  /**
+   * Compares two colors and returns true if they represent different color values
+   * or use different color spaces.
+   */
+  friend bool operator != (const CharacterColor& a, const CharacterColor& b);
+
+private:
+  quint8 _colorSpace;
+
+  // bytes storing the character color 
+  quint8 _u; 
+  quint8 _v; 
+  quint8 _w; 
+};
+
+inline bool operator == (const CharacterColor& a, const CharacterColor& b)
+{ 
+    return a._colorSpace == b._colorSpace &&
+	       a._u == b._u &&
+	       a._v == b._v &&
+           a._w == b._w;
+}
+
+inline bool operator != (const CharacterColor& a, const CharacterColor& b)
+{
+    return !operator==(a,b);
+}
+
+inline const QColor color256(quint8 u, const ColorEntry* base)
+{
+  //   0.. 16: system colors
+  if (u <   8) return base[u+2            ].color; u -= 8;
+  if (u <   8) return base[u+2+BASE_COLORS].color; u -= 8;
+
+  //  16..231: 6x6x6 rgb color cube
+  if (u < 216) return QColor(255*((u/36)%6)/5,
+                             255*((u/ 6)%6)/5,
+                             255*((u/ 1)%6)/5); u -= 216;
+  
+  // 232..255: gray, leaving out black and white
+  int gray = u*10+8; return QColor(gray,gray,gray);
+}
+
+inline QColor CharacterColor::color(const ColorEntry* base) const
+{
+  switch (_colorSpace)
+  {
+    case COLOR_SPACE_DEFAULT: return base[_u+0+(_v?BASE_COLORS:0)].color;
+    case COLOR_SPACE_SYSTEM: return base[_u+2+(_v?BASE_COLORS:0)].color;
+    case COLOR_SPACE_256: return color256(_u,base);
+    case COLOR_SPACE_RGB: return QColor(_u,_v,_w);
+    case COLOR_SPACE_UNDEFINED: return QColor();
+  }
+
+  Q_ASSERT(false); // invalid color space
+
+  return QColor();
+}
+
+inline void CharacterColor::toggleIntensive()
+{
+  if (_colorSpace == COLOR_SPACE_SYSTEM || _colorSpace == COLOR_SPACE_DEFAULT)
+  {
+    _v = !_v;
+  }
+}
+
+#endif // CHARACTERCOLOR_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/Emulation.cpp	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,426 @@
+/*
+    This file is part of Konsole, an X terminal.
+
+    Copyright (C) 2007 Robert Knight <robertknight@gmail.com> 
+    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
+    Copyright (C) 1996 by Matthias Ettrich <ettrich@kde.org>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+// Own
+#include "unix/Emulation.h"
+
+// System
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+// Qt
+#include <QtGui/QApplication>
+#include <QtGui/QClipboard>
+#include <QtCore/QHash>
+#include <QtGui/QKeyEvent>
+#include <QtCore/QRegExp>
+#include <QtCore/QTextStream>
+#include <QtCore/QThread>
+
+#include <QtCore/QTime>
+
+// Konsole
+#include "unix/KeyboardTranslator.h"
+#include "unix/Screen.h"
+#include "unix/TerminalCharacterDecoder.h"
+#include "unix/ScreenWindow.h"
+
+Emulation::Emulation() :
+  _currentScreen(0),
+  _codec(0),
+  _decoder(0),
+  _keyTranslator(0),
+  _usesMouse(false)
+{
+
+  // create screens with a default size
+  _screen[0] = new Screen(40,80);
+  _screen[1] = new Screen(40,80);
+  _currentScreen = _screen[0];
+
+  QObject::connect(&_bulkTimer1, SIGNAL(timeout()), this, SLOT(showBulk()) );
+  QObject::connect(&_bulkTimer2, SIGNAL(timeout()), this, SLOT(showBulk()) );
+   
+  // listen for mouse status changes
+  connect( this , SIGNAL(programUsesMouseChanged(bool)) , 
+           SLOT(usesMouseChanged(bool)) );
+}
+
+bool Emulation::programUsesMouse() const
+{
+    return _usesMouse;
+}
+
+void Emulation::usesMouseChanged(bool usesMouse)
+{
+    _usesMouse = usesMouse;
+}
+
+ScreenWindow* Emulation::createWindow()
+{
+    ScreenWindow* window = new ScreenWindow();
+    window->setScreen(_currentScreen);
+    _windows << window;
+
+    connect(window , SIGNAL(selectionChanged()),
+            this , SLOT(bufferedUpdate()));
+
+    connect(this , SIGNAL(outputChanged()),
+            window , SLOT(notifyOutputChanged()) );
+    return window;
+}
+
+/*!
+*/
+
+Emulation::~Emulation()
+{
+  QListIterator<ScreenWindow*> windowIter(_windows);
+
+  while (windowIter.hasNext())
+  {
+    delete windowIter.next();
+  }
+
+  delete _screen[0];
+  delete _screen[1];
+  delete _decoder;
+}
+
+/*! change between primary and alternate _screen
+*/
+
+void Emulation::setScreen(int n)
+{
+  Screen *old = _currentScreen;
+  _currentScreen = _screen[n&1];
+  if (_currentScreen != old) 
+  {
+     old->setBusySelecting(false);
+
+     // tell all windows onto this emulation to switch to the newly active _screen
+     QListIterator<ScreenWindow*> windowIter(_windows);
+     while ( windowIter.hasNext() )
+     {
+         windowIter.next()->setScreen(_currentScreen);
+     }
+  }
+}
+
+void Emulation::clearHistory()
+{
+    _screen[0]->setScroll( _screen[0]->getScroll() , false );
+}
+void Emulation::setHistory(const HistoryType& t)
+{
+  _screen[0]->setScroll(t);
+
+  showBulk();
+}
+
+const HistoryType& Emulation::history()
+{
+  return _screen[0]->getScroll();
+}
+
+void Emulation::setCodec(const QTextCodec * qtc)
+{
+  Q_ASSERT( qtc );
+
+  _codec = qtc;
+  delete _decoder;
+  _decoder = _codec->makeDecoder();
+
+  emit useUtf8Request(utf8());
+}
+
+void Emulation::setCodec(EmulationCodec codec)
+{
+    if ( codec == Utf8Codec )
+        setCodec( QTextCodec::codecForName("utf8") );
+    else if ( codec == LocaleCodec )
+        setCodec( QTextCodec::codecForLocale() );
+}
+
+void Emulation::setKeyBindings(const QString& name)
+{
+  _keyTranslator = KeyboardTranslatorManager::instance()->findTranslator(name);
+}
+
+QString Emulation::keyBindings()
+{
+  return _keyTranslator->name();
+}
+
+
+// Interpreting Codes ---------------------------------------------------------
+
+/*
+   This section deals with decoding the incoming character stream.
+   Decoding means here, that the stream is first separated into `tokens'
+   which are then mapped to a `meaning' provided as operations by the
+   `Screen' class.
+*/
+
+/*!
+*/
+
+void Emulation::receiveChar(int c)
+// process application unicode input to terminal
+// this is a trivial scanner
+{
+  c &= 0xff;
+  switch (c)
+  {
+    case '\b'      : _currentScreen->BackSpace();                 break;
+    case '\t'      : _currentScreen->Tabulate();                  break;
+    case '\n'      : _currentScreen->NewLine();                   break;
+    case '\r'      : _currentScreen->Return();                    break;
+    case 0x07      : emit stateSet(NOTIFYBELL);
+                     break;
+    default        : _currentScreen->ShowCharacter(c);            break;
+  };
+}
+
+/* ------------------------------------------------------------------------- */
+/*                                                                           */
+/*                             Keyboard Handling                             */
+/*                                                                           */
+/* ------------------------------------------------------------------------- */
+
+/*!
+*/
+
+void Emulation::sendKeyEvent( QKeyEvent* ev )
+{
+  emit stateSet(NOTIFYNORMAL);
+  
+  if (!ev->text().isEmpty())
+  { // A block of text
+    // Note that the text is proper unicode.
+    // We should do a conversion here, but since this
+    // routine will never be used, we simply emit plain ascii.
+    //emit sendBlock(ev->text().toAscii(),ev->text().length());
+    emit sendData(ev->text().toUtf8(),ev->text().length());
+  }
+}
+
+void Emulation::sendString(const char*,int)
+{
+    // default implementation does nothing
+}
+
+void Emulation::sendMouseEvent(int /*buttons*/, int /*column*/, int /*row*/, int /*eventType*/)
+{
+    // default implementation does nothing
+}
+
+// Unblocking, Byte to Unicode translation --------------------------------- --
+
+/*
+   We are doing code conversion from locale to unicode first.
+TODO: Character composition from the old code.  See #96536
+*/
+
+void Emulation::receiveData(const char* text, int length)
+{
+	emit stateSet(NOTIFYACTIVITY);
+
+	bufferedUpdate();
+    	
+        QString unicodeText = _decoder->toUnicode(text,length);
+
+	//send characters to terminal emulator
+        for (int i=0;i<unicodeText.length();i++)
+	{
+                receiveChar(unicodeText[i].unicode());
+	}
+}
+
+// Selection --------------------------------------------------------------- --
+
+void Emulation::writeToStream( TerminalCharacterDecoder* _decoder , 
+                               int startLine ,
+                               int endLine) 
+{
+  _currentScreen->writeToStream(_decoder,startLine,endLine);
+}
+
+int Emulation::lineCount()
+{
+    // sum number of lines currently on _screen plus number of lines in history
+    return _currentScreen->getLines() + _currentScreen->getHistLines();
+}
+
+// Refreshing -------------------------------------------------------------- --
+
+#define BULK_TIMEOUT1 10
+#define BULK_TIMEOUT2 40
+
+/*!
+*/
+void Emulation::showBulk()
+{
+    _bulkTimer1.stop();
+    _bulkTimer2.stop();
+
+    emit outputChanged();
+
+    _currentScreen->resetScrolledLines();
+    _currentScreen->resetDroppedLines();
+}
+
+void Emulation::bufferedUpdate()
+{
+   _bulkTimer1.setSingleShot(true);
+   _bulkTimer1.start(BULK_TIMEOUT1);
+   if (!_bulkTimer2.isActive())
+   {
+      _bulkTimer2.setSingleShot(true);
+      _bulkTimer2.start(BULK_TIMEOUT2);
+   }
+}
+
+char Emulation::getErase() const
+{
+  return '\b';
+}
+
+void Emulation::setImageSize(int lines, int columns)
+{
+  //kDebug() << "Resizing image to: " << lines << "by" << columns << QTime::currentTime().msec();
+  Q_ASSERT( lines > 0 );
+  Q_ASSERT( columns > 0 );
+
+  _screen[0]->resizeImage(lines,columns);
+  _screen[1]->resizeImage(lines,columns);
+
+  emit imageSizeChanged(lines,columns);
+
+  bufferedUpdate();
+}
+
+QSize Emulation::imageSize()
+{
+  return QSize(_currentScreen->getColumns(), _currentScreen->getLines());
+}
+
+ushort ExtendedCharTable::extendedCharHash(ushort* unicodePoints , ushort length) const
+{
+    ushort hash = 0;
+    for ( ushort i = 0 ; i < length ; i++ )
+    {
+        hash = 31*hash + unicodePoints[i];
+    }
+    return hash;
+}
+bool ExtendedCharTable::extendedCharMatch(ushort hash , ushort* unicodePoints , ushort length) const
+{
+    ushort* entry = extendedCharTable[hash];
+
+    // compare given length with stored sequence length ( given as the first ushort in the 
+    // stored buffer ) 
+    if ( entry == 0 || entry[0] != length ) 
+       return false;
+    // if the lengths match, each character must be checked.  the stored buffer starts at
+    // entry[1]
+    for ( int i = 0 ; i < length ; i++ )
+    {
+        if ( entry[i+1] != unicodePoints[i] )
+           return false; 
+    } 
+    return true;
+}
+ushort ExtendedCharTable::createExtendedChar(ushort* unicodePoints , ushort length)
+{
+    // look for this sequence of points in the table
+    ushort hash = extendedCharHash(unicodePoints,length);
+
+    // check existing entry for match
+    while ( extendedCharTable.contains(hash) )
+    {
+        if ( extendedCharMatch(hash,unicodePoints,length) )
+        {
+            // this sequence already has an entry in the table, 
+            // return its hash
+            return hash;
+        }
+        else
+        {
+            // if hash is already used by another, different sequence of unicode character
+            // points then try next hash
+            hash++;
+        }
+    }    
+
+    
+     // add the new sequence to the table and
+     // return that index
+    ushort* buffer = new ushort[length+1];
+    buffer[0] = length;
+    for ( int i = 0 ; i < length ; i++ )
+       buffer[i+1] = unicodePoints[i]; 
+    
+    extendedCharTable.insert(hash,buffer);
+
+    return hash;
+}
+
+ushort* ExtendedCharTable::lookupExtendedChar(ushort hash , ushort& length) const
+{
+    // lookup index in table and if found, set the length
+    // argument and return a pointer to the character sequence
+
+    ushort* buffer = extendedCharTable[hash];
+    if ( buffer )
+    {
+        length = buffer[0];
+        return buffer+1;
+    }
+    else
+    {
+        length = 0;
+        return 0;
+    }
+}
+
+ExtendedCharTable::ExtendedCharTable()
+{
+}
+ExtendedCharTable::~ExtendedCharTable()
+{
+    // free all allocated character buffers
+    QHashIterator<ushort,ushort*> iter(extendedCharTable);
+    while ( iter.hasNext() )
+    {
+        iter.next();
+        delete[] iter.value();
+    }
+}
+
+// global instance
+ExtendedCharTable ExtendedCharTable::instance;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/Emulation.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,456 @@
+/*
+    This file is part of Konsole, an X terminal.
+    
+    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
+    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+#ifndef EMULATION_H
+#define EMULATION_H
+
+// System
+#include <stdio.h>
+
+// Qt 
+#include <QtGui/QKeyEvent>
+
+#include <QtCore/QTextCodec>
+#include <QtCore/QTextStream>
+#include <QtCore/QTimer>
+
+class KeyboardTranslator;
+class HistoryType;
+class Screen;
+class ScreenWindow;
+class TerminalCharacterDecoder;
+
+/** 
+ * This enum describes the available states which 
+ * the terminal emulation may be set to.
+ *
+ * These are the values used by Emulation::stateChanged() 
+ */
+enum 
+{ 
+    /** The emulation is currently receiving user input. */
+    NOTIFYNORMAL=0, 
+    /** 
+     * The terminal program has triggered a bell event
+     * to get the user's attention.
+     */
+    NOTIFYBELL=1, 
+    /** 
+     * The emulation is currently receiving data from its 
+     * terminal input.
+     */
+    NOTIFYACTIVITY=2,
+
+    // unused here? 
+    NOTIFYSILENCE=3 
+};
+
+/**
+ * Base class for terminal emulation back-ends.
+ *
+ * The back-end is responsible for decoding an incoming character stream and 
+ * producing an output image of characters.
+ *
+ * When input from the terminal is received, the receiveData() slot should be called with
+ * the data which has arrived.  The emulation will process the data and update the 
+ * screen image accordingly.  The codec used to decode the incoming character stream
+ * into the unicode characters used internally can be specified using setCodec() 
+ *
+ * The size of the screen image can be specified by calling setImageSize() with the 
+ * desired number of lines and columns.  When new lines are added, old content
+ * is moved into a history store, which can be set by calling setHistory(). 
+ *
+ * The screen image can be accessed by creating a ScreenWindow onto this emulation 
+ * by calling createWindow().  Screen windows provide access to a section of the 
+ * output.  Each screen window covers the same number of lines and columns as the 
+ * image size returned by imageSize().  The screen window can be moved up and down
+ * and provides transparent access to both the current on-screen image and the 
+ * previous output.  The screen windows emit an outputChanged signal
+ * when the section of the image they are looking at changes.
+ * Graphical views can then render the contents of a screen window, listening for notifications
+ * of output changes from the screen window which they are associated with and updating 
+ * accordingly. 
+ *
+ * The emulation also is also responsible for converting input from the connected views such
+ * as keypresses and mouse activity into a character string which can be sent
+ * to the terminal program.  Key presses can be processed by calling the sendKeyEvent() slot,
+ * while mouse events can be processed using the sendMouseEvent() slot.  When the character
+ * stream has been produced, the emulation will emit a sendData() signal with a pointer
+ * to the character buffer.  This data should be fed to the standard input of the terminal
+ * process.  The translation of key presses into an output character stream is performed
+ * using a lookup in a set of key bindings which map key sequences to output
+ * character sequences.  The name of the key bindings set used can be specified using
+ * setKeyBindings()
+ *
+ * The emulation maintains certain state information which changes depending on the 
+ * input received.  The emulation can be reset back to its starting state by calling 
+ * reset().  
+ *
+ * The emulation also maintains an activity state, which specifies whether
+ * terminal is currently active ( when data is received ), normal
+ * ( when the terminal is idle or receiving user input ) or trying
+ * to alert the user ( also known as a "Bell" event ).  The stateSet() signal
+ * is emitted whenever the activity state is set.  This can be used to determine
+ * how long the emulation has been active/idle for and also respond to
+ * a 'bell' event in different ways.
+ */
+class Emulation : public QObject
+{ 
+Q_OBJECT
+
+public:
+ 
+   /** Constructs a new terminal emulation */ 
+   Emulation();
+  ~Emulation();
+
+  /**
+   * Creates a new window onto the output from this emulation.  The contents
+   * of the window are then rendered by views which are set to use this window using the
+   * TerminalDisplay::setScreenWindow() method.
+   */
+  ScreenWindow* createWindow();
+
+  /** Returns the size of the screen image which the emulation produces */
+  QSize imageSize();
+
+  /**
+   * Returns the total number of lines, including those stored in the history.
+   */ 
+  int lineCount();
+
+  
+  /** 
+   * Sets the history store used by this emulation.  When new lines
+   * are added to the output, older lines at the top of the screen are transferred to a history
+   * store.   
+   *
+   * The number of lines which are kept and the storage location depend on the 
+   * type of store.
+   */
+  void setHistory(const HistoryType&);
+  /** Returns the history store used by this emulation.  See setHistory() */
+  const HistoryType& history();
+  /** Clears the history scroll. */
+  void clearHistory();
+
+  /** 
+   * Copies the output history from @p startLine to @p endLine 
+   * into @p stream, using @p decoder to convert the terminal
+   * characters into text. 
+   *
+   * @param decoder A decoder which converts lines of terminal characters with 
+   * appearance attributes into output text.  PlainTextDecoder is the most commonly
+   * used decoder.
+   * @param startLine The first
+   */
+  virtual void writeToStream(TerminalCharacterDecoder* decoder,int startLine,int endLine);
+  
+  
+  /** Returns the codec used to decode incoming characters.  See setCodec() */
+  const QTextCodec* codec() { return _codec; }
+  /** Sets the codec used to decode incoming characters.  */
+  void setCodec(const QTextCodec*);
+
+  /** 
+   * Convenience method.  
+   * Returns true if the current codec used to decode incoming
+   * characters is UTF-8
+   */
+  bool utf8() { Q_ASSERT(_codec); return _codec->mibEnum() == 106; }
+  
+
+  /** TODO Document me */
+  virtual char getErase() const;
+
+  /** 
+   * Sets the key bindings used to key events
+   * ( received through sendKeyEvent() ) into character
+   * streams to send to the terminal.
+   */
+  void setKeyBindings(const QString& name);
+  /** 
+   * Returns the name of the emulation's current key bindings.
+   * See setKeyBindings()
+   */
+  QString keyBindings();
+
+  /** 
+   * Copies the current image into the history and clears the screen.
+   */
+  virtual void clearEntireScreen() =0;
+
+  /** Resets the state of the terminal. */
+  virtual void reset() =0;
+
+  /** 
+   * Returns true if the active terminal program wants
+   * mouse input events.
+   *
+   * The programUsesMouseChanged() signal is emitted when this
+   * changes.
+   */
+  bool programUsesMouse() const;
+
+public slots: 
+
+  /** Change the size of the emulation's image */
+  virtual void setImageSize(int lines, int columns);
+  
+  /** 
+   * Interprets a sequence of characters and sends the result to the terminal.
+   * This is equivalent to calling sendKeyEvent() for each character in @p text in succession.
+   */
+  virtual void sendText(const QString& text) = 0;
+
+  /** 
+   * Interprets a key press event and emits the sendData() signal with
+   * the resulting character stream. 
+   */
+  virtual void sendKeyEvent(QKeyEvent*);
+ 
+  /** 
+   * Converts information about a mouse event into an xterm-compatible escape
+   * sequence and emits the character sequence via sendData()
+   */
+  virtual void sendMouseEvent(int buttons, int column, int line, int eventType);
+  
+  /**
+   * Sends a string of characters to the foreground terminal process. 
+   *
+   * @param string The characters to send.  
+   * @param length Length of @p string or if set to a negative value, @p string will
+   * be treated as a null-terminated string and its length will be determined automatically.
+   */
+  virtual void sendString(const char* string, int length = -1) = 0;
+
+  /** 
+   * Processes an incoming stream of characters.  receiveData() decodes the incoming
+   * character buffer using the current codec(), and then calls receiveChar() for
+   * each unicode character in the resulting buffer.  
+   *
+   * receiveData() also starts a timer which causes the outputChanged() signal
+   * to be emitted when it expires.  The timer allows multiple updates in quick
+   * succession to be buffered into a single outputChanged() signal emission.
+   *
+   * @param buffer A string of characters received from the terminal program.
+   * @param len The length of @p buffer
+   */
+  void receiveData(const char* buffer,int len);
+
+signals:
+
+  /** 
+   * Emitted when a buffer of data is ready to send to the 
+   * standard input of the terminal.
+   *
+   * @param data The buffer of data ready to be sent
+   * @paran len The length of @p data in bytes
+   */
+  void sendData(const char* data,int len);
+
+  /** 
+   * Requests that sending of input to the emulation
+   * from the terminal process be suspended or resumed.
+   *
+   * @param suspend If true, requests that sending of 
+   * input from the terminal process' stdout be 
+   * suspended.  Otherwise requests that sending of
+   * input be resumed. 
+   */
+  void lockPtyRequest(bool suspend);
+
+  /**
+   * Requests that the pty used by the terminal process
+   * be set to UTF 8 mode.  
+   *
+   * TODO: More documentation
+   */
+  void useUtf8Request(bool);
+
+  /**
+   * Emitted when the activity state of the emulation is set.
+   *
+   * @param state The new activity state, one of NOTIFYNORMAL, NOTIFYACTIVITY
+   * or NOTIFYBELL
+   */
+  void stateSet(int state);
+
+
+  /**
+   * Requests that the color of the text used
+   * to represent the tabs associated with this
+   * emulation be changed.  This is a Konsole-specific
+   * extension from pre-KDE 4 times.
+   *
+   * TODO: Document how the parameter works.
+   */
+  void changeTabTextColorRequest(int color);
+
+  /** 
+   * This is emitted when the program running in the shell indicates whether or
+   * not it is interested in mouse events.
+   *
+   * @param usesMouse This will be true if the program wants to be informed about
+   * mouse events or false otherwise.
+   */
+  void programUsesMouseChanged(bool usesMouse);
+
+  /** 
+   * Emitted when the contents of the screen image change.
+   * The emulation buffers the updates from successive image changes,
+   * and only emits outputChanged() at sensible intervals when
+   * there is a lot of terminal activity.
+   *
+   * Normally there is no need for objects other than the screen windows
+   * created with createWindow() to listen for this signal.
+   *
+   * ScreenWindow objects created using createWindow() will emit their
+   * own outputChanged() signal in response to this signal. 
+   */
+  void outputChanged();
+
+  /**
+   * Emitted when the program running in the terminal wishes to update the 
+   * session's title.  This also allows terminal programs to customize other
+   * aspects of the terminal emulation display. 
+   *
+   * This signal is emitted when the escape sequence "\033]ARG;VALUE\007"
+   * is received in the input string, where ARG is a number specifying what
+   * should change and VALUE is a string specifying the new value.
+   *
+   * TODO:  The name of this method is not very accurate since this method
+   * is used to perform a whole range of tasks besides just setting
+   * the user-title of the session.    
+   *
+   * @param title Specifies what to change.
+   * <ul>
+   * <li>0 - Set window icon text and session title to @p newTitle</li>
+   * <li>1 - Set window icon text to @p newTitle</li>
+   * <li>2 - Set session title to @p newTitle</li>
+   * <li>11 - Set the session's default background color to @p newTitle,
+   *         where @p newTitle can be an HTML-style string (#RRGGBB) or a named
+   *         color (eg 'red', 'blue').  
+   *         See http://doc.trolltech.com/4.2/qcolor.html#setNamedColor for more
+   *         details.
+   * </li>
+   * <li>31 - Supposedly treats @p newTitle as a URL and opens it (NOT IMPLEMENTED)</li>
+   * <li>32 - Sets the icon associated with the session.  @p newTitle is the name 
+   *    of the icon to use, which can be the name of any icon in the current KDE icon
+   *    theme (eg: 'konsole', 'kate', 'folder_home')</li>
+   * </ul>
+   * @param newTitle Specifies the new title 
+   */
+
+  void titleChanged(int title,const QString& newTitle);
+
+  /**
+   * Emitted when the program running in the terminal changes the
+   * screen size.
+   */
+  void imageSizeChanged(int lineCount , int columnCount);
+
+  /** 
+   * Emitted when the terminal program requests to change various properties
+   * of the terminal display.  
+   *
+   * A profile change command occurs when a special escape sequence, followed
+   * by a string containing a series of name and value pairs is received.
+   * This string can be parsed using a ProfileCommandParser instance.
+   *
+   * @param text A string expected to contain a series of key and value pairs in
+   * the form:  name=value;name2=value2 ...
+   */
+  void profileChangeCommandReceived(const QString& text);
+
+protected:
+  virtual void setMode  (int mode) = 0;
+  virtual void resetMode(int mode) = 0;
+   
+ /** 
+   * Processes an incoming character.  See receiveData()
+   * @p ch A unicode character code. 
+   */
+  virtual void receiveChar(int ch);
+
+  /** 
+   * Sets the active screen.  The terminal has two screens, primary and alternate.
+   * The primary screen is used by default.  When certain interactive programs such
+   * as Vim are run, they trigger a switch to the alternate screen.
+   *
+   * @param index 0 to switch to the primary screen, or 1 to switch to the alternate screen
+   */
+  void setScreen(int index); 
+
+  enum EmulationCodec
+  {
+      LocaleCodec = 0,
+      Utf8Codec   = 1
+  };
+  void setCodec(EmulationCodec codec); // codec number, 0 = locale, 1=utf8
+
+
+  QList<ScreenWindow*> _windows;
+  
+  Screen* _currentScreen;  // pointer to the screen which is currently active, 
+                            // this is one of the elements in the screen[] array
+
+  Screen* _screen[2];      // 0 = primary screen ( used by most programs, including the shell
+                            //                      scrollbars are enabled in this mode )
+                            // 1 = alternate      ( used by vi , emacs etc.
+                            //                      scrollbars are not enabled in this mode )
+                            
+  
+  //decodes an incoming C-style character stream into a unicode QString using 
+  //the current text codec.  (this allows for rendering of non-ASCII characters in text files etc.)
+  const QTextCodec* _codec;
+  QTextDecoder* _decoder;
+
+  const KeyboardTranslator* _keyTranslator; // the keyboard layout
+
+protected slots:
+  /** 
+   * Schedules an update of attached views.
+   * Repeated calls to bufferedUpdate() in close succession will result in only a single update,
+   * much like the Qt buffered update of widgets. 
+   */
+  void bufferedUpdate();
+
+private slots: 
+
+  // triggered by timer, causes the emulation to send an updated screen image to each
+  // view
+  void showBulk(); 
+
+  void usesMouseChanged(bool usesMouse);
+
+private:
+
+  bool _usesMouse;
+  QTimer _bulkTimer1;
+  QTimer _bulkTimer2;
+  
+};
+
+#endif // ifndef EMULATION_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/ExtendedDefaultTranslator.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,74 @@
+"keyboard \"Default (XFree 4)\""
+"key Escape             : \"\\E\""
+"key Tab   -Shift       : \"\\t\"\n"
+"key Tab   +Shift+Ansi  : \"\\E[Z\"\n"
+"key Tab   +Shift-Ansi  : \"\\t\"\n"
+"key Backtab     +Ansi  : \"\\E[Z\"\n"
+"key Backtab     -Ansi  : \"\\t\"\n"
+"key Return-Shift-NewLine : \"\\r\"\n"
+"key Return-Shift+NewLine : \"\\r\\n\"\n"
+"key Return+Shift         : \"\\EOM\"\n"
+"key Backspace      : \"\\x7f\"\n"
+"key Up   -Shift-Ansi : \"\\EA\"\n"
+"key Down -Shift-Ansi : \"\\EB\"\n"
+"key Right-Shift-Ansi : \"\\EC\"\n"
+"key Left -Shift-Ansi : \"\\ED\"\n"
+"key Up    -Shift-AnyMod+Ansi+AppCuKeys           : \"\\EOA\"\n"
+"key Down  -Shift-AnyMod+Ansi+AppCuKeys           : \"\\EOB\"\n"
+"key Right -Shift-AnyMod+Ansi+AppCuKeys           : \"\\EOC\"\n"
+"key Left  -Shift-AnyMod+Ansi+AppCuKeys           : \"\\EOD\"\n"
+"key Up    -Shift-AnyMod+Ansi-AppCuKeys           : \"\\E[A\"\n"
+"key Down  -Shift-AnyMod+Ansi-AppCuKeys           : \"\\E[B\"\n"
+"key Right -Shift-AnyMod+Ansi-AppCuKeys           : \"\\E[C\"\n"
+"key Left  -Shift-AnyMod+Ansi-AppCuKeys           : \"\\E[D\"\n"
+"key Up    -Shift+AnyMod+Ansi                     : \"\\E[1;*A\"\n"
+"key Down  -Shift+AnyMod+Ansi                     : \"\\E[1;*B\"\n"
+"key Right -Shift+AnyMod+Ansi                     : \"\\E[1;*C\"\n"
+"key Left  -Shift+AnyMod+Ansi                     : \"\\E[1;*D\"\n"
+"key Enter+NewLine : \"\\r\\n\"\n"
+"key Enter-NewLine : \"\\r\"\n"
+"key Home        -AnyMod     -AppCuKeys           : \"\\E[H\"  \n"
+"key End         -AnyMod     -AppCuKeys           : \"\\E[F\"  \n"
+"key Home        -AnyMod     +AppCuKeys           : \"\\EOH\"  \n"
+"key End         -AnyMod     +AppCuKeys           : \"\\EOF\"  \n"
+"key Home        +AnyMod                          : \"\\E[1;*H\"\n"
+"key End         +AnyMod                          : \"\\E[1;*F\"\n"
+"key Insert      -AnyMod                          : \"\\E[2~\"\n"
+"key Delete      -AnyMod                          : \"\\E[3~\"\n"
+"key Insert      +AnyMod                          : \"\\E[2;*~\"\n"
+"key Delete      +AnyMod                          : \"\\E[3;*~\"\n"
+"key Prior -Shift-AnyMod                          : \"\\E[5~\"\n"
+"key Next  -Shift-AnyMod                          : \"\\E[6~\"\n"
+"key Prior -Shift+AnyMod                          : \"\\E[5;*~\"\n"
+"key Next  -Shift+AnyMod                          : \"\\E[6;*~\"\n"
+"key F1          -AnyMod                          : \"\\EOP\"\n"
+"key F2          -AnyMod                          : \"\\EOQ\"\n"
+"key F3          -AnyMod                          : \"\\EOR\"\n"
+"key F4          -AnyMod                          : \"\\EOS\"\n"
+"key F5          -AnyMod                          : \"\\E[15~\"\n"
+"key F6          -AnyMod                          : \"\\E[17~\"\n"
+"key F7          -AnyMod                          : \"\\E[18~\"\n"
+"key F8          -AnyMod                          : \"\\E[19~\"\n"
+"key F9          -AnyMod                          : \"\\E[20~\"\n"
+"key F10         -AnyMod                          : \"\\E[21~\"\n"
+"key F11         -AnyMod                          : \"\\E[23~\"\n"
+"key F12         -AnyMod                          : \"\\E[24~\"\n"
+"key F1          +AnyMod                          : \"\\EO*P\"\n"
+"key F2          +AnyMod                          : \"\\EO*Q\"\n"
+"key F3          +AnyMod                          : \"\\EO*R\"\n"
+"key F4          +AnyMod                          : \"\\EO*S\"\n"
+"key F5          +AnyMod                          : \"\\E[15;*~\"\n"
+"key F6          +AnyMod                          : \"\\E[17;*~\"\n"
+"key F7          +AnyMod                          : \"\\E[18;*~\"\n"
+"key F8          +AnyMod                          : \"\\E[19;*~\"\n"
+"key F9          +AnyMod                          : \"\\E[20;*~\"\n"
+"key F10         +AnyMod                          : \"\\E[21;*~\"\n"
+"key F11         +AnyMod                          : \"\\E[23;*~\"\n"
+"key F12         +AnyMod                          : \"\\E[24;*~\"\n"
+"key Space +Control : \"\\x00\"\n"
+"key Up    +Shift-AppScreen  : scrollLineUp\n"
+"key Prior +Shift-AppScreen  : scrollPageUp\n"
+"key Down  +Shift-AppScreen  : scrollLineDown\n"
+"key Next  +Shift-AppScreen  : scrollPageDown\n"
+"key ScrollLock     : scrollLock\n"
+"\0"
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/Filter.cpp	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,555 @@
+/*
+    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+// Own
+#include "unix/Filter.h"
+
+// System
+#include <iostream>
+
+// Qt
+#include <QtGui/QAction>
+#include <QtGui/QApplication>
+#include <QtGui/QClipboard>
+#include <QtCore/QString>
+
+#include <QtCore/QSharedData>
+#include <QtCore>
+
+// Konsole
+#include "unix/TerminalCharacterDecoder.h"
+
+FilterChain::~FilterChain()
+{
+    QMutableListIterator<Filter*> iter(*this);
+    
+    while ( iter.hasNext() )
+    {
+        Filter* filter = iter.next();
+        iter.remove();
+        delete filter;
+    }
+}
+
+void FilterChain::addFilter(Filter* filter)
+{
+    append(filter);
+}
+void FilterChain::removeFilter(Filter* filter)
+{
+    removeAll(filter);
+}
+bool FilterChain::containsFilter(Filter* filter)
+{
+    return contains(filter);
+}
+void FilterChain::reset()
+{
+    QListIterator<Filter*> iter(*this);
+    while (iter.hasNext())
+        iter.next()->reset();
+}
+void FilterChain::setBuffer(const QString* buffer , const QList<int>* linePositions)
+{
+    QListIterator<Filter*> iter(*this);
+    while (iter.hasNext())
+        iter.next()->setBuffer(buffer,linePositions);
+}
+void FilterChain::process()
+{
+    QListIterator<Filter*> iter(*this);
+    while (iter.hasNext())
+        iter.next()->process();
+}
+void FilterChain::clear()
+{
+    QList<Filter*>::clear();
+}
+Filter::HotSpot* FilterChain::hotSpotAt(int line , int column) const
+{
+    QListIterator<Filter*> iter(*this);
+    while (iter.hasNext())
+    {
+        Filter* filter = iter.next();
+        Filter::HotSpot* spot = filter->hotSpotAt(line,column);
+        if ( spot != 0 )
+        {
+            return spot;
+        }
+    }
+
+    return 0;
+}
+
+QList<Filter::HotSpot*> FilterChain::hotSpots() const
+{
+    QList<Filter::HotSpot*> list;
+    QListIterator<Filter*> iter(*this);
+    while (iter.hasNext())
+    {
+        Filter* filter = iter.next();
+        list << filter->hotSpots();
+    }
+    return list;
+}
+
+TerminalImageFilterChain::TerminalImageFilterChain()
+: _buffer(0)
+, _linePositions(0)
+{
+}
+
+TerminalImageFilterChain::~TerminalImageFilterChain()
+{
+    delete _buffer;
+    delete _linePositions;
+}
+
+void TerminalImageFilterChain::setImage(const Character* const image , int lines , int columns, const QVector<LineProperty>& lineProperties)
+{
+//qDebug("%s %d", __FILE__, __LINE__);
+    if (empty())
+        return;
+//qDebug("%s %d", __FILE__, __LINE__);
+
+    // reset all filters and hotspots
+    reset();
+//qDebug("%s %d", __FILE__, __LINE__);
+
+    PlainTextDecoder decoder;
+    decoder.setTrailingWhitespace(false);
+    
+//qDebug("%s %d", __FILE__, __LINE__);
+    // setup new shared buffers for the filters to process on
+    QString* newBuffer = new QString();
+    QList<int>* newLinePositions = new QList<int>();
+    setBuffer( newBuffer , newLinePositions );
+
+    // free the old buffers
+    delete _buffer;
+    delete _linePositions;
+
+    _buffer = newBuffer;
+    _linePositions = newLinePositions;
+
+    QTextStream lineStream(_buffer);
+    decoder.begin(&lineStream);
+
+    for (int i=0 ; i < lines ; i++)
+    {
+        _linePositions->append(_buffer->length());
+        decoder.decodeLine(image + i*columns,columns,LINE_DEFAULT);
+
+        // pretend that each line ends with a newline character.
+        // this prevents a link that occurs at the end of one line
+        // being treated as part of a link that occurs at the start of the next line
+        //
+        // the downside is that links which are spread over more than one line are not
+        // highlighted.  
+        //
+        // TODO - Use the "line wrapped" attribute associated with lines in a
+        // terminal image to avoid adding this imaginary character for wrapped
+        // lines
+        if ( !(lineProperties.value(i,LINE_DEFAULT) & LINE_WRAPPED) )
+        	lineStream << QChar('\n');
+    }
+    decoder.end();
+//    qDebug("%s %d", __FILE__, __LINE__);
+}
+
+Filter::Filter() :
+_linePositions(0),
+_buffer(0)
+{
+}
+
+Filter::~Filter()
+{
+    QListIterator<HotSpot*> iter(_hotspotList);
+    while (iter.hasNext())
+    {
+        delete iter.next();
+    }
+}
+void Filter::reset()
+{
+    _hotspots.clear();
+    _hotspotList.clear();
+}
+
+void Filter::setBuffer(const QString* buffer , const QList<int>* linePositions)
+{
+    _buffer = buffer;
+    _linePositions = linePositions;
+}
+
+void Filter::getLineColumn(int position , int& startLine , int& startColumn)
+{
+    Q_ASSERT( _linePositions );
+    Q_ASSERT( _buffer );
+
+
+    for (int i = 0 ; i < _linePositions->count() ; i++)
+    {
+        //kDebug() << "line position at " << i << " = " << _linePositions[i];
+        int nextLine = 0;
+
+        if ( i == _linePositions->count()-1 )
+        {
+            nextLine = _buffer->length() + 1;
+        }
+        else
+        {
+            nextLine = _linePositions->value(i+1);
+        }
+
+       // kDebug() << "pos - " << position << " line pos(" << i<< ") " << _linePositions->value(i) << 
+       //     " next = " << nextLine << " buffer len = " << _buffer->length();
+
+        if ( _linePositions->value(i) <= position && position < nextLine ) 
+        {
+            startLine = i;
+            startColumn = position - _linePositions->value(i);
+            return;
+        }
+    }
+}
+    
+
+/*void Filter::addLine(const QString& text)
+{
+    _linePositions << _buffer.length();
+    _buffer.append(text);
+}*/
+
+const QString* Filter::buffer()
+{
+    return _buffer;
+}
+Filter::HotSpot::~HotSpot()
+{
+}
+void Filter::addHotSpot(HotSpot* spot)
+{
+    _hotspotList << spot;
+
+    for (int line = spot->startLine() ; line <= spot->endLine() ; line++)
+    {
+        _hotspots.insert(line,spot);
+    }    
+}
+QList<Filter::HotSpot*> Filter::hotSpots() const
+{
+    return _hotspotList;
+}
+QList<Filter::HotSpot*> Filter::hotSpotsAtLine(int line) const
+{
+    return _hotspots.values(line);
+}
+
+Filter::HotSpot* Filter::hotSpotAt(int line , int column) const
+{
+    QListIterator<HotSpot*> spotIter(_hotspots.values(line));
+
+    while (spotIter.hasNext())
+    {
+        HotSpot* spot = spotIter.next();
+        
+        if ( spot->startLine() == line && spot->startColumn() > column )
+            continue;
+        if ( spot->endLine() == line && spot->endColumn() < column )
+            continue;
+       
+        return spot;
+    }
+
+    return 0;
+}
+
+Filter::HotSpot::HotSpot(int startLine , int startColumn , int endLine , int endColumn)
+    : _startLine(startLine)
+    , _startColumn(startColumn)
+    , _endLine(endLine)
+    , _endColumn(endColumn)
+    , _type(NotSpecified)
+{
+}
+QString Filter::HotSpot::tooltip() const
+{
+    return QString();
+}
+QList<QAction*> Filter::HotSpot::actions()
+{
+    return QList<QAction*>();
+}
+int Filter::HotSpot::startLine() const
+{
+    return _startLine;
+}
+int Filter::HotSpot::endLine() const
+{
+    return _endLine;
+}
+int Filter::HotSpot::startColumn() const
+{
+    return _startColumn;
+}
+int Filter::HotSpot::endColumn() const
+{
+    return _endColumn;
+}
+Filter::HotSpot::Type Filter::HotSpot::type() const
+{
+    return _type;
+}
+void Filter::HotSpot::setType(Type type)
+{
+    _type = type;
+}
+
+RegExpFilter::RegExpFilter()
+{
+}
+
+RegExpFilter::HotSpot::HotSpot(int startLine,int startColumn,int endLine,int endColumn)
+    : Filter::HotSpot(startLine,startColumn,endLine,endColumn)
+{
+    setType(Marker);
+}
+
+void RegExpFilter::HotSpot::activate(QObject*)
+{
+}
+
+void RegExpFilter::HotSpot::setCapturedTexts(const QStringList& texts)
+{
+    _capturedTexts = texts;
+}
+QStringList RegExpFilter::HotSpot::capturedTexts() const
+{
+    return _capturedTexts;
+}
+
+void RegExpFilter::setRegExp(const QRegExp& regExp) 
+{
+    _searchText = regExp;
+}
+QRegExp RegExpFilter::regExp() const
+{
+    return _searchText;
+}
+/*void RegExpFilter::reset(int)
+{
+    _buffer = QString();
+}*/
+void RegExpFilter::process()
+{
+    int pos = 0;
+    const QString* text = buffer();
+
+    Q_ASSERT( text );
+
+    // ignore any regular expressions which match an empty string.
+    // otherwise the while loop below will run indefinitely
+    static const QString emptyString("");
+    if ( _searchText.exactMatch(emptyString) )
+        return;
+
+    while(pos >= 0)
+    {
+        pos = _searchText.indexIn(*text,pos);
+
+        if ( pos >= 0 )
+        {
+
+            int startLine = 0;
+            int endLine = 0;
+            int startColumn = 0;
+            int endColumn = 0;
+
+            
+            //kDebug() << "pos from " << pos << " to " << pos + _searchText.matchedLength();
+            
+            getLineColumn(pos,startLine,startColumn);
+            getLineColumn(pos + _searchText.matchedLength(),endLine,endColumn);
+
+            //kDebug() << "start " << startLine << " / " << startColumn;
+            //kDebug() << "end " << endLine << " / " << endColumn;
+
+            RegExpFilter::HotSpot* spot = newHotSpot(startLine,startColumn,
+                                           endLine,endColumn);
+            spot->setCapturedTexts(_searchText.capturedTexts());
+
+            addHotSpot( spot );  
+            pos += _searchText.matchedLength();
+
+            // if matchedLength == 0, the program will get stuck in an infinite loop
+            Q_ASSERT( _searchText.matchedLength() > 0 );
+        }
+    }    
+}
+
+RegExpFilter::HotSpot* RegExpFilter::newHotSpot(int startLine,int startColumn,
+                                                int endLine,int endColumn)
+{
+    return new RegExpFilter::HotSpot(startLine,startColumn,
+                                                  endLine,endColumn);
+}
+RegExpFilter::HotSpot* UrlFilter::newHotSpot(int startLine,int startColumn,int endLine,
+                                                    int endColumn)
+{
+    return new UrlFilter::HotSpot(startLine,startColumn,
+                                               endLine,endColumn);
+}
+UrlFilter::HotSpot::HotSpot(int startLine,int startColumn,int endLine,int endColumn)
+: RegExpFilter::HotSpot(startLine,startColumn,endLine,endColumn)
+, _urlObject(new FilterObject(this))
+{
+    setType(Link);
+}
+QString UrlFilter::HotSpot::tooltip() const
+{
+    QString url = capturedTexts().first();
+
+    const UrlType kind = urlType();
+
+    if ( kind == StandardUrl )
+        return QString(); 
+    else if ( kind == Email )
+        return QString(); 
+    else
+        return QString();
+}
+UrlFilter::HotSpot::UrlType UrlFilter::HotSpot::urlType() const
+{
+    QString url = capturedTexts().first();
+    
+    if ( FullUrlRegExp.exactMatch(url) )
+        return StandardUrl;
+    else if ( EmailAddressRegExp.exactMatch(url) )
+        return Email;
+    else
+        return Unknown;
+}
+
+void UrlFilter::HotSpot::activate(QObject* object)
+{
+    QString url = capturedTexts().first();
+
+    const UrlType kind = urlType();
+
+    const QString& actionName = object ? object->objectName() : QString();
+
+    if ( actionName == "copy-action" )
+    {
+        //kDebug() << "Copying url to clipboard:" << url;
+
+        QApplication::clipboard()->setText(url);
+        return;
+    }
+
+    if ( !object || actionName == "open-action" )
+    {
+        if ( kind == StandardUrl )
+        {
+            // if the URL path does not include the protocol ( eg. "www.kde.org" ) then
+            // prepend http:// ( eg. "www.kde.org" --> "http://www.kde.org" )
+            if (!url.contains("://"))
+            {
+                url.prepend("http://");
+            }
+        } 
+        else if ( kind == Email )
+        {
+            url.prepend("mailto:");
+        }
+    
+//        new KRun(url,QApplication::activeWindow());
+    }
+}
+
+// Note:  Altering these regular expressions can have a major effect on the performance of the filters 
+// used for finding URLs in the text, especially if they are very general and could match very long
+// pieces of text.
+// Please be careful when altering them.
+
+//regexp matches:
+// full url:  
+// protocolname:// or www. followed by anything other than whitespaces, <, >, ' or ", and ends before whitespaces, <, >, ', ", ], !, comma and dot
+const QRegExp UrlFilter::FullUrlRegExp("(www\\.(?!\\.)|[a-z][a-z0-9+.-]*://)[^\\s<>'\"]+[^!,\\.\\s<>'\"\\]]");
+// email address:
+// [word chars, dots or dashes]@[word chars, dots or dashes].[word chars]
+const QRegExp UrlFilter::EmailAddressRegExp("\\b(\\w|\\.|-)+@(\\w|\\.|-)+\\.\\w+\\b");
+
+// matches full url or email address
+const QRegExp UrlFilter::CompleteUrlRegExp('('+FullUrlRegExp.pattern()+'|'+
+                                            EmailAddressRegExp.pattern()+')');
+
+UrlFilter::UrlFilter()
+{
+    setRegExp( CompleteUrlRegExp );
+}
+UrlFilter::HotSpot::~HotSpot()
+{
+    delete _urlObject;
+}
+void FilterObject::activated()
+{
+    _filter->activate(sender());
+}
+QList<QAction*> UrlFilter::HotSpot::actions()
+{
+    QList<QAction*> list;
+
+    const UrlType kind = urlType();
+
+    QAction* openAction = new QAction(_urlObject);
+    QAction* copyAction = new QAction(_urlObject);;
+
+    Q_ASSERT( kind == StandardUrl || kind == Email );
+
+    if ( kind == StandardUrl )
+    {
+        openAction->setText(("Open Link"));
+        copyAction->setText(("Copy Link Address"));
+    }
+    else if ( kind == Email )
+    {
+        openAction->setText(("Send Email To..."));
+        copyAction->setText(("Copy Email Address"));
+    }
+
+    // object names are set here so that the hotspot performs the
+    // correct action when activated() is called with the triggered
+    // action passed as a parameter.
+    openAction->setObjectName("open-action");
+    copyAction->setObjectName("copy-action");
+
+    QObject::connect( openAction , SIGNAL(triggered()) , _urlObject , SLOT(activated()) );
+    QObject::connect( copyAction , SIGNAL(triggered()) , _urlObject , SLOT(activated()) );
+
+    list << openAction;
+    list << copyAction;
+
+    return list; 
+}
+
+//#include "moc_Filter.cpp"
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/Filter.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,379 @@
+/*
+    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+#ifndef FILTER_H
+#define FILTER_H
+
+// Qt
+#include <QtGui/QAction>
+#include <QtCore/QList>
+#include <QtCore/QObject>
+#include <QtCore/QStringList>
+#include <QtCore/QHash>
+#include <QtCore/QRegExp>
+
+// Local
+#include "unix/Character.h"
+
+/**
+ * A filter processes blocks of text looking for certain patterns (such as URLs or keywords from a list)
+ * and marks the areas which match the filter's patterns as 'hotspots'.
+ *
+ * Each hotspot has a type identifier associated with it ( such as a link or a highlighted section ),
+ * and an action.  When the user performs some activity such as a mouse-click in a hotspot area ( the exact
+ * action will depend on what is displaying the block of text which the filter is processing ), the hotspot's
+ * activate() method should be called.  Depending on the type of hotspot this will trigger a suitable response.
+ *
+ * For example, if a hotspot represents a URL then a suitable action would be opening that URL in a web browser.
+ * Hotspots may have more than one action, in which case the list of actions can be obtained using the 
+ * actions() method.
+ *
+ * Different subclasses of filter will return different types of hotspot.
+ * Subclasses must reimplement the process() method to examine a block of text and identify sections of interest.
+ * When processing the text they should create instances of Filter::HotSpot subclasses for sections of interest
+ * and add them to the filter's list of hotspots using addHotSpot()
+ */
+class Filter
+{
+public:
+    /**
+    * Represents an area of text which matched the pattern a particular filter has been looking for.
+    *
+    * Each hotspot has a type identifier associated with it ( such as a link or a highlighted section ),
+    * and an action.  When the user performs some activity such as a mouse-click in a hotspot area ( the exact
+    * action will depend on what is displaying the block of text which the filter is processing ), the hotspot's
+    * activate() method should be called.  Depending on the type of hotspot this will trigger a suitable response.
+    *
+    * For example, if a hotspot represents a URL then a suitable action would be opening that URL in a web browser.
+    * Hotspots may have more than one action, in which case the list of actions can be obtained using the 
+    * actions() method.  These actions may then be displayed in a popup menu or toolbar for example. 
+    */
+    class HotSpot
+    {
+    public:
+       /** 
+        * Constructs a new hotspot which covers the area from (@p startLine,@p startColumn) to (@p endLine,@p endColumn)
+        * in a block of text.
+        */
+       HotSpot(int startLine , int startColumn , int endLine , int endColumn);
+       virtual ~HotSpot();
+
+       enum Type
+       {
+            // the type of the hotspot is not specified
+            NotSpecified,
+            // this hotspot represents a clickable link
+            Link,
+            // this hotspot represents a marker
+            Marker
+       }; 
+
+       /** Returns the line when the hotspot area starts */
+       int startLine() const;
+       /** Returns the line where the hotspot area ends */
+       int endLine() const;
+       /** Returns the column on startLine() where the hotspot area starts */
+       int startColumn() const;
+       /** Returns the column on endLine() where the hotspot area ends */
+       int endColumn() const;
+       /** 
+        * Returns the type of the hotspot.  This is usually used as a hint for views on how to represent
+        * the hotspot graphically.  eg.  Link hotspots are typically underlined when the user mouses over them
+        */
+       Type type() const;
+       /** 
+        * Causes the an action associated with a hotspot to be triggered. 
+        *
+        * @param object The object which caused the hotspot to be triggered.  This is
+        * typically null ( in which case the default action should be performed ) or
+        * one of the objects from the actions() list.  In which case the associated
+        * action should be performed. 
+        */
+       virtual void activate(QObject* object = 0) = 0; 
+       /** 
+        * Returns a list of actions associated with the hotspot which can be used in a 
+        * menu or toolbar 
+        */
+       virtual QList<QAction*> actions();
+
+       /** 
+        * Returns the text of a tooltip to be shown when the mouse moves over the hotspot, or
+        * an empty string if there is no tooltip associated with this hotspot.
+        *
+        * The default implementation returns an empty string. 
+        */
+       virtual QString tooltip() const;
+
+    protected:
+       /** Sets the type of a hotspot.  This should only be set once */
+       void setType(Type type);
+
+    private:
+       int    _startLine;
+       int    _startColumn;
+       int    _endLine;
+       int    _endColumn;
+       Type _type;
+    
+    };
+
+    /** Constructs a new filter. */
+    Filter();
+    virtual ~Filter();
+
+    /** Causes the filter to process the block of text currently in its internal buffer */
+    virtual void process() = 0;
+
+    /** 
+     * Empties the filters internal buffer and resets the line count back to 0.
+     * All hotspots are deleted. 
+     */
+    void reset();
+
+    /** Adds a new line of text to the filter and increments the line count */
+    //void addLine(const QString& string);
+
+    /** Returns the hotspot which covers the given @p line and @p column, or 0 if no hotspot covers that area */
+    HotSpot* hotSpotAt(int line , int column) const;
+
+    /** Returns the list of hotspots identified by the filter */
+    QList<HotSpot*> hotSpots() const;
+
+    /** Returns the list of hotspots identified by the filter which occur on a given line */
+    QList<HotSpot*> hotSpotsAtLine(int line) const;
+
+    /** 
+     * TODO: Document me
+     */
+    void setBuffer(const QString* buffer , const QList<int>* linePositions);
+
+protected:
+    /** Adds a new hotspot to the list */
+    void addHotSpot(HotSpot*);
+    /** Returns the internal buffer */
+    const QString* buffer();
+    /** Converts a character position within buffer() to a line and column */
+    void getLineColumn(int position , int& startLine , int& startColumn);
+
+private:
+    QMultiHash<int,HotSpot*> _hotspots;
+    QList<HotSpot*> _hotspotList;
+    
+    const QList<int>* _linePositions;
+    const QString* _buffer;
+};
+
+/** 
+ * A filter which searches for sections of text matching a regular expression and creates a new RegExpFilter::HotSpot 
+ * instance for them.
+ *
+ * Subclasses can reimplement newHotSpot() to return custom hotspot types when matches for the regular expression
+ * are found. 
+ */
+class RegExpFilter : public Filter
+{
+public:
+    /** 
+     * Type of hotspot created by RegExpFilter.  The capturedTexts() method can be used to find the text
+     * matched by the filter's regular expression.
+     */
+    class HotSpot : public Filter::HotSpot
+    {
+    public:
+        HotSpot(int startLine, int startColumn, int endLine , int endColumn);
+        virtual void activate(QObject* object = 0);
+
+        /** Sets the captured texts associated with this hotspot */
+        void setCapturedTexts(const QStringList& texts);
+        /** Returns the texts found by the filter when matching the filter's regular expression */
+        QStringList capturedTexts() const;
+    private:
+        QStringList _capturedTexts;
+    };
+
+    /** Constructs a new regular expression filter */
+    RegExpFilter();
+
+    /** 
+     * Sets the regular expression which the filter searches for in blocks of text. 
+     *
+     * Regular expressions which match the empty string are treated as not matching
+     * anything. 
+     */
+    void setRegExp(const QRegExp& text);
+    /** Returns the regular expression which the filter searches for in blocks of text */
+    QRegExp regExp() const;
+
+    /** 
+     * Reimplemented to search the filter's text buffer for text matching regExp() 
+     *
+     * If regexp matches the empty string, then process() will return immediately
+     * without finding results. 
+     */
+    virtual void process();
+
+protected:
+    /** 
+     * Called when a match for the regular expression is encountered.  Subclasses should reimplement this
+     * to return custom hotspot types
+     */
+    virtual RegExpFilter::HotSpot* newHotSpot(int startLine,int startColumn,
+                                    int endLine,int endColumn);
+
+private:
+    QRegExp _searchText;
+};
+
+class FilterObject;
+
+/** A filter which matches URLs in blocks of text */
+class UrlFilter : public RegExpFilter 
+{
+public:
+    /** 
+     * Hotspot type created by UrlFilter instances.  The activate() method opens a web browser 
+     * at the given URL when called.
+     */
+    class HotSpot : public RegExpFilter::HotSpot 
+    {
+    public:
+        HotSpot(int startLine,int startColumn,int endLine,int endColumn);
+        virtual ~HotSpot();
+
+        virtual QList<QAction*> actions();
+
+        /** 
+         * Open a web browser at the current URL.  The url itself can be determined using
+         * the capturedTexts() method.
+         */
+        virtual void activate(QObject* object = 0);
+
+        virtual QString tooltip() const;
+    private:
+        enum UrlType
+        {
+            StandardUrl,
+            Email,
+            Unknown
+        };
+        UrlType urlType() const;
+
+        FilterObject* _urlObject;
+    };
+
+    UrlFilter();
+
+protected:
+    virtual RegExpFilter::HotSpot* newHotSpot(int,int,int,int);
+
+private:
+    
+    static const QRegExp FullUrlRegExp;
+    static const QRegExp EmailAddressRegExp;
+
+    // combined OR of FullUrlRegExp and EmailAddressRegExp
+    static const QRegExp CompleteUrlRegExp; 
+};
+
+class FilterObject : public QObject
+{
+Q_OBJECT
+public:
+    FilterObject(Filter::HotSpot* filter) : _filter(filter) {}
+private slots:
+    void activated();
+private:
+    Filter::HotSpot* _filter;
+};
+
+/** 
+ * A chain which allows a group of filters to be processed as one. 
+ * The chain owns the filters added to it and deletes them when the chain itself is destroyed.
+ *
+ * Use addFilter() to add a new filter to the chain.  
+ * When new text to be filtered arrives, use addLine() to add each additional
+ * line of text which needs to be processed and then after adding the last line, use
+ * process() to cause each filter in the chain to process the text.
+ *
+ * After processing a block of text, the reset() method can be used to set the filter chain's
+ * internal cursor back to the first line.
+ *
+ * The hotSpotAt() method will return the first hotspot which covers a given position.
+ *
+ * The hotSpots() and hotSpotsAtLine() method return all of the hotspots in the text and on
+ * a given line respectively.
+ */
+class FilterChain : protected QList<Filter*>
+{
+public:
+    virtual ~FilterChain();
+
+    /** Adds a new filter to the chain.  The chain will delete this filter when it is destroyed */
+    void addFilter(Filter* filter);
+    /** Removes a filter from the chain.  The chain will no longer delete the filter when destroyed */
+    void removeFilter(Filter* filter);
+    /** Returns true if the chain contains @p filter */
+    bool containsFilter(Filter* filter);
+    /** Removes all filters from the chain */
+    void clear();
+
+    /** Resets each filter in the chain */
+    void reset();
+    /**
+     * Processes each filter in the chain 
+     */
+    void process();
+
+    /** Sets the buffer for each filter in the chain to process. */
+    void setBuffer(const QString* buffer , const QList<int>* linePositions); 
+
+    /** Returns the first hotspot which occurs at @p line, @p column or 0 if no hotspot was found */
+    Filter::HotSpot* hotSpotAt(int line , int column) const;
+    /** Returns a list of all the hotspots in all the chain's filters */
+    QList<Filter::HotSpot*> hotSpots() const;
+    /** Returns a list of all hotspots at the given line in all the chain's filters */
+    QList<Filter::HotSpot> hotSpotsAtLine(int line) const;
+
+};
+
+/** A filter chain which processes character images from terminal displays */
+class TerminalImageFilterChain : public FilterChain
+{
+public:
+    TerminalImageFilterChain();
+    virtual ~TerminalImageFilterChain();
+
+    /**
+     * Set the current terminal image to @p image.
+     *
+     * @param image The terminal image
+     * @param lines The number of lines in the terminal image
+     * @param columns The number of columns in the terminal image
+     */
+    void setImage(const Character* const image , int lines , int columns,
+				  const QVector<LineProperty>& lineProperties);  
+
+private:
+    QString* _buffer;
+    QList<int>* _linePositions;
+};
+
+#endif //FILTER_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/History.cpp	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,696 @@
+/*
+    This file is part of Konsole, an X terminal.
+    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+// Own
+#include "unix/History.h"
+
+// System
+#include <iostream>
+#include <stdlib.h>
+#include <assert.h>
+#include <stdio.h>
+#include <sys/types.h>
+#include <sys/mman.h>
+#include <unistd.h>
+#include <errno.h>
+
+
+// Reasonable line size
+#define LINE_SIZE	1024
+
+/*
+   An arbitrary long scroll.
+
+   One can modify the scroll only by adding either cells
+   or newlines, but access it randomly.
+
+   The model is that of an arbitrary wide typewriter scroll
+   in that the scroll is a serie of lines and each line is
+   a serie of cells with no overwriting permitted.
+
+   The implementation provides arbitrary length and numbers
+   of cells and line/column indexed read access to the scroll
+   at constant costs.
+
+KDE4: Can we use QTemporaryFile here, instead of KTempFile?
+
+FIXME: some complain about the history buffer comsuming the
+       memory of their machines. This problem is critical
+       since the history does not behave gracefully in cases
+       where the memory is used up completely.
+
+       I put in a workaround that should handle it problem
+       now gracefully. I'm not satisfied with the solution.
+
+FIXME: Terminating the history is not properly indicated
+       in the menu. We should throw a signal.
+
+FIXME: There is noticeable decrease in speed, also. Perhaps,
+       there whole feature needs to be revisited therefore.
+       Disadvantage of a more elaborated, say block-oriented
+       scheme with wrap around would be it's complexity.
+*/
+
+//FIXME: tempory replacement for tmpfile
+//       this is here one for debugging purpose.
+
+//#define tmpfile xTmpFile
+
+// History File ///////////////////////////////////////////
+
+/*
+  A Row(X) data type which allows adding elements to the end.
+*/
+
+HistoryFile::HistoryFile()
+  : ion(-1),
+    length(0),
+	fileMap(0)
+{
+  if (tmpFile.open())
+  { 
+    tmpFile.setAutoRemove(true);
+    ion = tmpFile.handle();
+  }
+}
+
+HistoryFile::~HistoryFile()
+{
+	if (fileMap)
+		unmap();
+}
+
+//TODO:  Mapping the entire file in will cause problems if the history file becomes exceedingly large,
+//(ie. larger than available memory).  HistoryFile::map() should only map in sections of the file at a time,
+//to avoid this.
+void HistoryFile::map()
+{
+	assert( fileMap == 0 );
+
+	fileMap = (char*)mmap( 0 , length , PROT_READ , MAP_PRIVATE , ion , 0 );
+
+    //if mmap'ing fails, fall back to the read-lseek combination
+    if ( fileMap == MAP_FAILED )
+    {
+            readWriteBalance = 0; 
+            fileMap = 0;
+            qDebug() << ": mmap'ing history failed.  errno = " << errno;
+    }
+}
+
+void HistoryFile::unmap()
+{
+	int result = munmap( fileMap , length );
+	assert( result == 0 );
+
+	fileMap = 0;
+}
+
+bool HistoryFile::isMapped()
+{
+	return (fileMap != 0);
+}
+
+void HistoryFile::add(const unsigned char* bytes, int len)
+{
+  if ( fileMap )
+		  unmap();
+		
+  readWriteBalance++;
+
+  int rc = 0;
+
+  rc = lseek(ion,length,SEEK_SET); if (rc < 0) { perror("HistoryFile::add.seek"); return; }
+  rc = write(ion,bytes,len);       if (rc < 0) { perror("HistoryFile::add.write"); return; }
+  length += rc;
+}
+
+void HistoryFile::get(unsigned char* bytes, int len, int loc)
+{
+  //count number of get() calls vs. number of add() calls.  
+  //If there are many more get() calls compared with add() 
+  //calls (decided by using MAP_THRESHOLD) then mmap the log
+  //file to improve performance.
+  readWriteBalance--;
+  if ( !fileMap && readWriteBalance < MAP_THRESHOLD )
+		  map();
+
+  if ( fileMap )
+  {
+	for (int i=0;i<len;i++)
+			bytes[i]=fileMap[loc+i];
+  }
+  else
+  {	
+  	int rc = 0;
+
+  	if (loc < 0 || len < 0 || loc + len > length)
+    	fprintf(stderr,"getHist(...,%d,%d): invalid args.\n",len,loc);
+  	rc = lseek(ion,loc,SEEK_SET); if (rc < 0) { perror("HistoryFile::get.seek"); return; }
+  	rc = read(ion,bytes,len);     if (rc < 0) { perror("HistoryFile::get.read"); return; }
+  }
+}
+
+int HistoryFile::len()
+{
+  return length;
+}
+
+
+// History Scroll abstract base class //////////////////////////////////////
+
+
+HistoryScroll::HistoryScroll(HistoryType* t)
+  : m_histType(t)
+{
+}
+
+HistoryScroll::~HistoryScroll()
+{
+  delete m_histType;
+}
+
+bool HistoryScroll::hasScroll()
+{
+  return true;
+}
+
+// History Scroll File //////////////////////////////////////
+
+/* 
+   The history scroll makes a Row(Row(Cell)) from
+   two history buffers. The index buffer contains
+   start of line positions which refere to the cells
+   buffer.
+
+   Note that index[0] addresses the second line
+   (line #1), while the first line (line #0) starts
+   at 0 in cells.
+*/
+
+HistoryScrollFile::HistoryScrollFile(const QString &logFileName)
+  : HistoryScroll(new HistoryTypeFile(logFileName)),
+  m_logFileName(logFileName)
+{
+}
+
+HistoryScrollFile::~HistoryScrollFile()
+{
+}
+ 
+int HistoryScrollFile::getLines()
+{
+  return index.len() / sizeof(int);
+}
+
+int HistoryScrollFile::getLineLen(int lineno)
+{
+  return (startOfLine(lineno+1) - startOfLine(lineno)) / sizeof(Character);
+}
+
+bool HistoryScrollFile::isWrappedLine(int lineno)
+{
+  if (lineno>=0 && lineno <= getLines()) {
+    unsigned char flag;
+    lineflags.get((unsigned char*)&flag,sizeof(unsigned char),(lineno)*sizeof(unsigned char));
+    return flag;
+  }
+  return false;
+}
+
+int HistoryScrollFile::startOfLine(int lineno)
+{
+  if (lineno <= 0) return 0;
+  if (lineno <= getLines())
+    { 
+	
+	if (!index.isMapped())
+			index.map();
+	
+	int res;
+    index.get((unsigned char*)&res,sizeof(int),(lineno-1)*sizeof(int));
+    return res;
+    }
+  return cells.len();
+}
+
+void HistoryScrollFile::getCells(int lineno, int colno, int count, Character res[])
+{
+  cells.get((unsigned char*)res,count*sizeof(Character),startOfLine(lineno)+colno*sizeof(Character));
+}
+
+void HistoryScrollFile::addCells(const Character text[], int count)
+{
+  cells.add((unsigned char*)text,count*sizeof(Character));
+}
+
+void HistoryScrollFile::addLine(bool previousWrapped)
+{
+  if (index.isMapped())
+		  index.unmap();
+
+  int locn = cells.len();
+  index.add((unsigned char*)&locn,sizeof(int));
+  unsigned char flags = previousWrapped ? 0x01 : 0x00;
+  lineflags.add((unsigned char*)&flags,sizeof(unsigned char));
+}
+
+
+// History Scroll Buffer //////////////////////////////////////
+HistoryScrollBuffer::HistoryScrollBuffer(unsigned int maxLineCount)
+  : HistoryScroll(new HistoryTypeBuffer(maxLineCount))
+   ,_historyBuffer()
+   ,_maxLineCount(0)
+   ,_usedLines(0)
+   ,_head(0)
+{
+  setMaxNbLines(maxLineCount);
+}
+
+HistoryScrollBuffer::~HistoryScrollBuffer()
+{
+    delete[] _historyBuffer;
+}
+
+void HistoryScrollBuffer::addCellsVector(const QVector<Character>& cells)
+{
+    _head++;
+    if ( _usedLines < _maxLineCount )
+        _usedLines++;
+
+    if ( _head >= _maxLineCount )
+    {
+        _head = 0;
+    }
+
+    _historyBuffer[bufferIndex(_usedLines-1)] = cells;
+    _wrappedLine[bufferIndex(_usedLines-1)] = false;
+}
+void HistoryScrollBuffer::addCells(const Character a[], int count)
+{
+  HistoryLine newLine(count);
+  qCopy(a,a+count,newLine.begin());
+
+  addCellsVector(newLine);
+}
+
+void HistoryScrollBuffer::addLine(bool previousWrapped)
+{
+    _wrappedLine[bufferIndex(_usedLines-1)] = previousWrapped;
+}
+
+int HistoryScrollBuffer::getLines()
+{
+    return _usedLines;
+}
+
+int HistoryScrollBuffer::getLineLen(int lineNumber)
+{
+  Q_ASSERT( lineNumber >= 0 && lineNumber < _maxLineCount );
+
+  if ( lineNumber < _usedLines )
+  {
+    return _historyBuffer[bufferIndex(lineNumber)].size();
+  }
+  else
+  {
+    return 0;
+  }
+}
+
+bool HistoryScrollBuffer::isWrappedLine(int lineNumber)
+{
+  Q_ASSERT( lineNumber >= 0 && lineNumber < _maxLineCount );
+    
+  if (lineNumber < _usedLines)
+  {
+    //kDebug() << "Line" << lineNumber << "wrapped is" << _wrappedLine[bufferIndex(lineNumber)];
+    return _wrappedLine[bufferIndex(lineNumber)];
+  }
+  else
+    return false;
+}
+
+void HistoryScrollBuffer::getCells(int lineNumber, int startColumn, int count, Character* buffer)
+{
+  if ( count == 0 ) return;
+
+  Q_ASSERT( lineNumber < _maxLineCount );
+
+  if (lineNumber >= _usedLines) 
+  {
+    memset(buffer, 0, count * sizeof(Character));
+    return;
+  }
+  
+  const HistoryLine& line = _historyBuffer[bufferIndex(lineNumber)];
+
+  //kDebug() << "startCol " << startColumn;
+  //kDebug() << "line.size() " << line.size();
+  //kDebug() << "count " << count;
+
+  Q_ASSERT( startColumn <= line.size() - count );
+    
+  memcpy(buffer, line.constData() + startColumn , count * sizeof(Character));
+}
+
+void HistoryScrollBuffer::setMaxNbLines(unsigned int lineCount)
+{
+    HistoryLine* oldBuffer = _historyBuffer;
+    HistoryLine* newBuffer = new HistoryLine[lineCount];
+    
+    for ( int i = 0 ; i < qMin(_usedLines,(int)lineCount) ; i++ )
+    {
+        newBuffer[i] = oldBuffer[bufferIndex(i)];
+    }
+    
+    _usedLines = qMin(_usedLines,(int)lineCount);
+    _maxLineCount = lineCount;
+    _head = ( _usedLines == _maxLineCount ) ? 0 : _usedLines-1;
+
+    _historyBuffer = newBuffer;
+    delete[] oldBuffer;
+
+    _wrappedLine.resize(lineCount);
+}
+
+int HistoryScrollBuffer::bufferIndex(int lineNumber)
+{
+    Q_ASSERT( lineNumber >= 0 );
+    Q_ASSERT( lineNumber < _maxLineCount );
+    Q_ASSERT( (_usedLines == _maxLineCount) || lineNumber <= _head );
+
+    if ( _usedLines == _maxLineCount )
+    {
+        return (_head+lineNumber+1) % _maxLineCount;
+    }
+    else
+    {   
+        return lineNumber;
+    }
+}
+
+
+// History Scroll None //////////////////////////////////////
+
+HistoryScrollNone::HistoryScrollNone()
+  : HistoryScroll(new HistoryTypeNone())
+{
+}
+
+HistoryScrollNone::~HistoryScrollNone()
+{
+}
+
+bool HistoryScrollNone::hasScroll()
+{
+  return false;
+}
+
+int  HistoryScrollNone::getLines()
+{
+  return 0;
+}
+
+int  HistoryScrollNone::getLineLen(int)
+{
+  return 0;
+}
+
+bool HistoryScrollNone::isWrappedLine(int /*lineno*/)
+{
+  return false;
+}
+
+void HistoryScrollNone::getCells(int, int, int, Character [])
+{
+}
+
+void HistoryScrollNone::addCells(const Character [], int)
+{
+}
+
+void HistoryScrollNone::addLine(bool)
+{
+}
+
+// History Scroll BlockArray //////////////////////////////////////
+
+HistoryScrollBlockArray::HistoryScrollBlockArray(size_t size)
+  : HistoryScroll(new HistoryTypeBlockArray(size))
+{
+  m_blockArray.setHistorySize(size); // nb. of lines.
+}
+
+HistoryScrollBlockArray::~HistoryScrollBlockArray()
+{
+}
+
+int  HistoryScrollBlockArray::getLines()
+{
+  return m_lineLengths.count();
+}
+
+int  HistoryScrollBlockArray::getLineLen(int lineno)
+{
+    if ( m_lineLengths.contains(lineno) )
+        return m_lineLengths[lineno];
+    else
+        return 0;
+}
+
+bool HistoryScrollBlockArray::isWrappedLine(int /*lineno*/)
+{
+  return false;
+}
+
+void HistoryScrollBlockArray::getCells(int lineno, int colno,
+                                       int count, Character res[])
+{
+  if (!count) return;
+
+  const Block *b = m_blockArray.at(lineno);
+
+  if (!b) {
+    memset(res, 0, count * sizeof(Character)); // still better than random data
+    return;
+  }
+
+  assert(((colno + count) * sizeof(Character)) < ENTRIES);
+  memcpy(res, b->data + (colno * sizeof(Character)), count * sizeof(Character));
+}
+
+void HistoryScrollBlockArray::addCells(const Character a[], int count)
+{
+  Block *b = m_blockArray.lastBlock();
+  
+  if (!b) return;
+
+  // put cells in block's data
+  assert((count * sizeof(Character)) < ENTRIES);
+
+  memset(b->data, 0, ENTRIES);
+
+  memcpy(b->data, a, count * sizeof(Character));
+  b->size = count * sizeof(Character);
+
+  size_t res = m_blockArray.newBlock();
+  assert (res > 0);
+  Q_UNUSED( res );
+
+  m_lineLengths.insert(m_blockArray.getCurrent(), count);
+}
+
+void HistoryScrollBlockArray::addLine(bool)
+{
+}
+
+//////////////////////////////////////////////////////////////////////
+// History Types
+//////////////////////////////////////////////////////////////////////
+
+HistoryType::HistoryType()
+{
+}
+
+HistoryType::~HistoryType()
+{
+}
+
+//////////////////////////////
+
+HistoryTypeNone::HistoryTypeNone()
+{
+}
+
+bool HistoryTypeNone::isEnabled() const
+{
+  return false;
+}
+
+HistoryScroll* HistoryTypeNone::scroll(HistoryScroll *old) const
+{
+  delete old;
+  return new HistoryScrollNone();
+}
+
+int HistoryTypeNone::maximumLineCount() const
+{
+  return 0;
+}
+
+//////////////////////////////
+
+HistoryTypeBlockArray::HistoryTypeBlockArray(size_t size)
+  : m_size(size)
+{
+}
+
+bool HistoryTypeBlockArray::isEnabled() const
+{
+  return true;
+}
+
+int HistoryTypeBlockArray::maximumLineCount() const
+{
+  return m_size;
+}
+
+HistoryScroll* HistoryTypeBlockArray::scroll(HistoryScroll *old) const
+{
+  delete old;
+  return new HistoryScrollBlockArray(m_size);
+}
+
+
+//////////////////////////////
+
+HistoryTypeBuffer::HistoryTypeBuffer(unsigned int nbLines)
+  : m_nbLines(nbLines)
+{
+}
+
+bool HistoryTypeBuffer::isEnabled() const
+{
+  return true;
+}
+
+int HistoryTypeBuffer::maximumLineCount() const
+{
+  return m_nbLines;
+}
+
+HistoryScroll* HistoryTypeBuffer::scroll(HistoryScroll *old) const
+{
+  if (old)
+  {
+    HistoryScrollBuffer *oldBuffer = dynamic_cast<HistoryScrollBuffer*>(old);
+    if (oldBuffer)
+    {
+       oldBuffer->setMaxNbLines(m_nbLines);
+       return oldBuffer;
+    }
+
+    HistoryScroll *newScroll = new HistoryScrollBuffer(m_nbLines);
+    int lines = old->getLines();
+    int startLine = 0;
+    if (lines > (int) m_nbLines)
+       startLine = lines - m_nbLines;
+
+    Character line[LINE_SIZE];
+    for(int i = startLine; i < lines; i++)
+    {
+       int size = old->getLineLen(i);
+       if (size > LINE_SIZE)
+       {
+          Character *tmp_line = new Character[size];
+          old->getCells(i, 0, size, tmp_line);
+          newScroll->addCells(tmp_line, size);
+          newScroll->addLine(old->isWrappedLine(i));
+          delete [] tmp_line;
+       }
+       else
+       {
+          old->getCells(i, 0, size, line);
+          newScroll->addCells(line, size);
+          newScroll->addLine(old->isWrappedLine(i));
+       }
+    }
+    delete old;
+    return newScroll;
+  }
+  return new HistoryScrollBuffer(m_nbLines);
+}
+
+//////////////////////////////
+
+HistoryTypeFile::HistoryTypeFile(const QString& fileName)
+  : m_fileName(fileName)
+{
+}
+
+bool HistoryTypeFile::isEnabled() const
+{
+  return true;
+}
+
+const QString& HistoryTypeFile::getFileName() const
+{
+  return m_fileName;
+}
+
+HistoryScroll* HistoryTypeFile::scroll(HistoryScroll *old) const
+{
+  if (dynamic_cast<HistoryFile *>(old)) 
+     return old; // Unchanged.
+
+  HistoryScroll *newScroll = new HistoryScrollFile(m_fileName);
+
+  Character line[LINE_SIZE];
+  int lines = (old != 0) ? old->getLines() : 0;
+  for(int i = 0; i < lines; i++)
+  {
+     int size = old->getLineLen(i);
+     if (size > LINE_SIZE)
+     {
+        Character *tmp_line = new Character[size];
+        old->getCells(i, 0, size, tmp_line);
+        newScroll->addCells(tmp_line, size);
+        newScroll->addLine(old->isWrappedLine(i));
+        delete [] tmp_line;
+     }
+     else
+     {
+        old->getCells(i, 0, size, line);
+        newScroll->addCells(line, size);
+        newScroll->addLine(old->isWrappedLine(i));
+     }
+  }
+
+  delete old;
+  return newScroll; 
+}
+
+int HistoryTypeFile::maximumLineCount() const
+{
+  return 0;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/History.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,330 @@
+/*
+    This file is part of Konsole, an X terminal.
+    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+#ifndef HISTORY_H
+#define HISTORY_H
+
+// Qt
+#include <QtCore/QBitRef>
+#include <QtCore/QHash>
+#include <QtCore>
+
+// Konsole
+#include "unix/BlockArray.h"
+#include "unix/Character.h"
+
+
+class HistoryFile
+{
+public:
+  HistoryFile();
+  virtual ~HistoryFile();
+
+  virtual void add(const unsigned char* bytes, int len);
+  virtual void get(unsigned char* bytes, int len, int loc);
+  virtual int  len();
+
+  //mmaps the file in read-only mode
+  void map();
+  //un-mmaps the file
+  void unmap();
+  //returns true if the file is mmap'ed
+  bool isMapped();
+
+
+private:
+  int  ion;
+  int  length;
+  QTemporaryFile tmpFile;
+
+  //pointer to start of mmap'ed file data, or 0 if the file is not mmap'ed
+  char* fileMap;
+ 
+  //incremented whenver 'add' is called and decremented whenever
+  //'get' is called.
+  //this is used to detect when a large number of lines are being read and processed from the history
+  //and automatically mmap the file for better performance (saves the overhead of many lseek-read calls).
+  int readWriteBalance;
+
+  //when readWriteBalance goes below this threshold, the file will be mmap'ed automatically
+  static const int MAP_THRESHOLD = -1000;
+};
+
+//////////////////////////////////////////////////////////////////////
+
+//////////////////////////////////////////////////////////////////////
+// Abstract base class for file and buffer versions
+//////////////////////////////////////////////////////////////////////
+class HistoryType;
+
+class HistoryScroll
+{
+public:
+  HistoryScroll(HistoryType*);
+ virtual ~HistoryScroll();
+
+  virtual bool hasScroll();
+
+  // access to history
+  virtual int  getLines() = 0;
+  virtual int  getLineLen(int lineno) = 0;
+  virtual void getCells(int lineno, int colno, int count, Character res[]) = 0;
+  virtual bool isWrappedLine(int lineno) = 0;
+
+  // backward compatibility (obsolete)
+  Character   getCell(int lineno, int colno) { Character res; getCells(lineno,colno,1,&res); return res; }
+
+  // adding lines.
+  virtual void addCells(const Character a[], int count) = 0;
+  // convenience method - this is virtual so that subclasses can take advantage
+  // of QVector's implicit copying
+  virtual void addCellsVector(const QVector<Character>& cells)
+  {
+    addCells(cells.data(),cells.size());
+  }
+
+  virtual void addLine(bool previousWrapped=false) = 0;
+
+  //
+  // FIXME:  Passing around constant references to HistoryType instances
+  // is very unsafe, because those references will no longer
+  // be valid if the history scroll is deleted.
+  //
+  const HistoryType& getType() { return *m_histType; }
+
+protected:
+  HistoryType* m_histType;
+
+};
+
+
+//////////////////////////////////////////////////////////////////////
+// File-based history (e.g. file log, no limitation in length)
+//////////////////////////////////////////////////////////////////////
+
+class HistoryScrollFile : public HistoryScroll
+{
+public:
+  HistoryScrollFile(const QString &logFileName);
+  virtual ~HistoryScrollFile();
+
+  virtual int  getLines();
+  virtual int  getLineLen(int lineno);
+  virtual void getCells(int lineno, int colno, int count, Character res[]);
+  virtual bool isWrappedLine(int lineno);
+
+  virtual void addCells(const Character a[], int count);
+  virtual void addLine(bool previousWrapped=false);
+
+private:
+  int startOfLine(int lineno);
+
+  QString m_logFileName;
+  HistoryFile index; // lines Row(int)
+  HistoryFile cells; // text  Row(Character)
+  HistoryFile lineflags; // flags Row(unsigned char)
+};
+
+
+//////////////////////////////////////////////////////////////////////
+// Buffer-based history (limited to a fixed nb of lines)
+//////////////////////////////////////////////////////////////////////
+class HistoryScrollBuffer : public HistoryScroll
+{
+public:
+  typedef QVector<Character> HistoryLine;
+
+  HistoryScrollBuffer(unsigned int maxNbLines = 1000);
+  virtual ~HistoryScrollBuffer();
+
+  virtual int  getLines();
+  virtual int  getLineLen(int lineno);
+  virtual void getCells(int lineno, int colno, int count, Character res[]);
+  virtual bool isWrappedLine(int lineno);
+
+  virtual void addCells(const Character a[], int count);
+  virtual void addCellsVector(const QVector<Character>& cells);
+  virtual void addLine(bool previousWrapped=false);
+
+  void setMaxNbLines(unsigned int nbLines);
+  unsigned int maxNbLines() { return _maxLineCount; }
+  
+
+private:
+  int bufferIndex(int lineNumber);
+
+  HistoryLine* _historyBuffer;
+  QBitArray _wrappedLine;
+  int _maxLineCount;
+  int _usedLines;  
+  int _head;
+  
+  //QVector<histline*> m_histBuffer;
+  //QBitArray m_wrappedLine;
+  //unsigned int m_maxNbLines;
+  //unsigned int m_nbLines;
+  //unsigned int m_arrayIndex;
+  //bool         m_buffFilled;
+};
+
+/*class HistoryScrollBufferV2 : public HistoryScroll
+{
+public:
+  virtual int  getLines();
+  virtual int  getLineLen(int lineno);
+  virtual void getCells(int lineno, int colno, int count, Character res[]);
+  virtual bool isWrappedLine(int lineno);
+
+  virtual void addCells(const Character a[], int count);
+  virtual void addCells(const QVector<Character>& cells);
+  virtual void addLine(bool previousWrapped=false);
+
+};*/
+
+
+//////////////////////////////////////////////////////////////////////
+// Nothing-based history (no history :-)
+//////////////////////////////////////////////////////////////////////
+class HistoryScrollNone : public HistoryScroll
+{
+public:
+  HistoryScrollNone();
+  virtual ~HistoryScrollNone();
+
+  virtual bool hasScroll();
+
+  virtual int  getLines();
+  virtual int  getLineLen(int lineno);
+  virtual void getCells(int lineno, int colno, int count, Character res[]);
+  virtual bool isWrappedLine(int lineno);
+
+  virtual void addCells(const Character a[], int count);
+  virtual void addLine(bool previousWrapped=false);
+};
+
+//////////////////////////////////////////////////////////////////////
+// BlockArray-based history
+//////////////////////////////////////////////////////////////////////
+class HistoryScrollBlockArray : public HistoryScroll
+{
+public:
+  HistoryScrollBlockArray(size_t size);
+  virtual ~HistoryScrollBlockArray();
+
+  virtual int  getLines();
+  virtual int  getLineLen(int lineno);
+  virtual void getCells(int lineno, int colno, int count, Character res[]);
+  virtual bool isWrappedLine(int lineno);
+
+  virtual void addCells(const Character a[], int count);
+  virtual void addLine(bool previousWrapped=false);
+
+protected:
+  BlockArray m_blockArray;
+  QHash<int,size_t> m_lineLengths;
+};
+
+//////////////////////////////////////////////////////////////////////
+// History type
+//////////////////////////////////////////////////////////////////////
+
+class HistoryType
+{
+public:
+  HistoryType();
+  virtual ~HistoryType();
+
+  /**
+   * Returns true if the history is enabled ( can store lines of output )
+   * or false otherwise. 
+   */
+  virtual bool isEnabled()           const = 0;
+  /**
+   * Returns true if the history size is unlimited.
+   */
+  bool isUnlimited() const { return maximumLineCount() == 0; }
+  /**
+   * Returns the maximum number of lines which this history type
+   * can store or 0 if the history can store an unlimited number of lines.
+   */
+  virtual int maximumLineCount()    const = 0;
+
+  virtual HistoryScroll* scroll(HistoryScroll *) const = 0;
+};
+
+class HistoryTypeNone : public HistoryType
+{
+public:
+  HistoryTypeNone();
+
+  virtual bool isEnabled() const;
+  virtual int maximumLineCount() const;
+
+  virtual HistoryScroll* scroll(HistoryScroll *) const;
+};
+
+class HistoryTypeBlockArray : public HistoryType
+{
+public:
+  HistoryTypeBlockArray(size_t size);
+  
+  virtual bool isEnabled() const;
+  virtual int maximumLineCount() const;
+
+  virtual HistoryScroll* scroll(HistoryScroll *) const;
+
+protected:
+  size_t m_size;
+};
+
+
+class HistoryTypeFile : public HistoryType
+{
+public:
+  HistoryTypeFile(const QString& fileName=QString());
+
+  virtual bool isEnabled() const;
+  virtual const QString& getFileName() const;
+  virtual int maximumLineCount() const;
+
+  virtual HistoryScroll* scroll(HistoryScroll *) const;
+
+protected:
+  QString m_fileName;
+};
+
+
+class HistoryTypeBuffer : public HistoryType
+{
+public:
+  HistoryTypeBuffer(unsigned int nbLines);
+  
+  virtual bool isEnabled() const;
+  virtual int maximumLineCount() const;
+
+  virtual HistoryScroll* scroll(HistoryScroll *) const;
+
+protected:
+  unsigned int m_nbLines;
+};
+
+#endif // HISTORY_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/KeyboardTranslator.cpp	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,888 @@
+/*
+    This source file was part of Konsole, a terminal emulator.
+
+    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+// Own
+#include "unix/KeyboardTranslator.h"
+
+// System
+#include <ctype.h>
+#include <stdio.h>
+
+// Qt
+#include <QtCore/QBuffer>
+#include <QtCore/QFile>
+#include <QtCore/QFileInfo>
+#include <QtCore>
+#include <QtGui>
+
+//and this is default now translator - default.keytab from original Konsole
+const char* KeyboardTranslatorManager::defaultTranslatorText = 
+#include "ExtendedDefaultTranslator.h"
+;
+
+KeyboardTranslatorManager::KeyboardTranslatorManager()
+    : _haveLoadedAll(false)
+{
+}
+KeyboardTranslatorManager::~KeyboardTranslatorManager()
+{
+    qDeleteAll(_translators.values());
+}
+QString KeyboardTranslatorManager::findTranslatorPath(const QString& name)
+{
+    return QString("kb-layouts/" + name + ".keytab");
+}
+void KeyboardTranslatorManager::findTranslators()
+{
+    QDir dir("kb-layouts/");
+    QStringList filters;
+    filters << "*.keytab";
+    dir.setNameFilters(filters);
+    QStringList list = dir.entryList(filters); //(".keytab"); // = KGlobal::dirs()->findAllResources("data",
+    //                                 "konsole/*.keytab",
+    //                                 KStandardDirs::NoDuplicates);
+    list = dir.entryList(filters);
+    // add the name of each translator to the list and associated
+    // the name with a null pointer to indicate that the translator
+    // has not yet been loaded from disk
+    QStringListIterator listIter(list);
+    while (listIter.hasNext())
+    {
+        QString translatorPath = listIter.next();
+
+        QString name = QFileInfo(translatorPath).baseName();
+
+        if ( !_translators.contains(name) ) {
+            _translators.insert(name,0);
+	}
+    }
+    _haveLoadedAll = true;
+}
+
+const KeyboardTranslator* KeyboardTranslatorManager::findTranslator(const QString& name)
+{
+    if ( name.isEmpty() )
+        return defaultTranslator();
+
+    //here was smth wrong in original Konsole source
+    findTranslators();
+
+    if ( _translators.contains(name) && _translators[name] != 0 ) {
+        return _translators[name];
+    }
+
+    KeyboardTranslator* translator = loadTranslator(name);
+
+    if ( translator != 0 )
+        _translators[name] = translator;
+    else if ( !name.isEmpty() )
+        qWarning() << "Unable to load translator" << name;
+
+    return translator;
+}
+
+bool KeyboardTranslatorManager::saveTranslator(const KeyboardTranslator* translator)
+{
+    const QString path = ".keytab";// = KGlobal::dirs()->saveLocation("data","konsole/")+translator->name()
+    //           +".keytab";
+
+    qDebug() << "Saving translator to" << path;
+
+    QFile destination(path);
+    
+    if (!destination.open(QIODevice::WriteOnly | QIODevice::Text))
+    {
+        qWarning() << "Unable to save keyboard translation:" 
+                   << destination.errorString();
+
+        return false;
+    }
+
+    {
+        KeyboardTranslatorWriter writer(&destination);
+        writer.writeHeader(translator->description());
+
+        QListIterator<KeyboardTranslator::Entry> iter(translator->entries());
+        while ( iter.hasNext() )
+            writer.writeEntry(iter.next());
+    }
+
+    destination.close();
+
+    return true;
+}
+
+KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(const QString& name)
+{
+    const QString& path = findTranslatorPath(name);
+
+    QFile source(path); 
+    
+    if (name.isEmpty() || !source.open(QIODevice::ReadOnly | QIODevice::Text))
+        return 0;
+
+    return loadTranslator(&source,name);
+}
+
+const KeyboardTranslator* KeyboardTranslatorManager::defaultTranslator()
+{
+    QBuffer textBuffer;
+    textBuffer.setData(defaultTranslatorText,strlen(defaultTranslatorText));
+
+    if (!textBuffer.open(QIODevice::ReadOnly))
+        return 0;
+
+    return loadTranslator(&textBuffer,"fallback");
+}
+
+KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(QIODevice* source,const QString& name)
+{
+    KeyboardTranslator* translator = new KeyboardTranslator(name);
+    KeyboardTranslatorReader reader(source);
+    translator->setDescription( reader.description() );
+    
+    while ( reader.hasNextEntry() ) {
+        translator->addEntry(reader.nextEntry());
+    }	
+
+    source->close();
+
+    if ( !reader.parseError() )
+    {
+        return translator;
+    }
+    else
+    {
+        delete translator;
+        return 0;
+    }
+}
+
+KeyboardTranslatorWriter::KeyboardTranslatorWriter(QIODevice* destination)
+    : _destination(destination)
+{
+    Q_ASSERT( destination && destination->isWritable() );
+
+    _writer = new QTextStream(_destination);
+}
+KeyboardTranslatorWriter::~KeyboardTranslatorWriter()
+{
+    delete _writer;
+}
+void KeyboardTranslatorWriter::writeHeader( const QString& description )
+{
+    *_writer << "keyboard \"" << description << '\"' << '\n';
+}
+void KeyboardTranslatorWriter::writeEntry( const KeyboardTranslator::Entry& entry )
+{
+    QString result;
+
+    if ( entry.command() != KeyboardTranslator::NoCommand )
+        result = entry.resultToString();
+    else
+        result = '\"' + entry.resultToString() + '\"';
+
+    *_writer << "key " << entry.conditionToString() << " : " << result << '\n';
+}
+
+
+// each line of the keyboard translation file is one of:
+//
+// - keyboard "name"
+// - key KeySequence : "characters"
+// - key KeySequence : CommandName
+//
+// KeySequence begins with the name of the key ( taken from the Qt::Key enum )
+// and is followed by the keyboard modifiers and state flags ( with + or - in front
+// of each modifier or flag to indicate whether it is required ).  All keyboard modifiers
+// and flags are optional, if a particular modifier or state is not specified it is 
+// assumed not to be a part of the sequence.  The key sequence may contain whitespace
+//
+// eg:  "key Up+Shift : scrollLineUp"
+//      "key Next-Shift : "\E[6~"
+//
+// (lines containing only whitespace are ignored, parseLine assumes that comments have
+// already been removed)
+//
+
+KeyboardTranslatorReader::KeyboardTranslatorReader( QIODevice* source )
+    : _source(source)
+    , _hasNext(false)
+{
+    // read input until we find the description
+    while ( _description.isEmpty() && !source->atEnd() )
+    {
+        const QList<Token>& tokens = tokenize( QString(source->readLine()) );
+
+        if ( !tokens.isEmpty() && tokens.first().type == Token::TitleKeyword )
+        {
+            _description = (tokens[1].text.toUtf8());
+        }
+    }
+
+    readNext();
+}
+void KeyboardTranslatorReader::readNext() 
+{
+    // find next entry
+    while ( !_source->atEnd() )
+    {
+        const QList<Token>& tokens = tokenize( QString(_source->readLine()) );
+        if ( !tokens.isEmpty() && tokens.first().type == Token::KeyKeyword )
+        {
+            KeyboardTranslator::States flags = KeyboardTranslator::NoState;
+            KeyboardTranslator::States flagMask = KeyboardTranslator::NoState;
+            Qt::KeyboardModifiers modifiers = Qt::NoModifier;
+            Qt::KeyboardModifiers modifierMask = Qt::NoModifier;
+
+            int keyCode = Qt::Key_unknown;
+
+            decodeSequence(tokens[1].text.toLower(),
+                           keyCode,
+                           modifiers,
+                           modifierMask,
+                           flags,
+                           flagMask); 
+
+            KeyboardTranslator::Command command = KeyboardTranslator::NoCommand;
+            QByteArray text;
+
+            // get text or command
+            if ( tokens[2].type == Token::OutputText )
+            {
+                text = tokens[2].text.toLocal8Bit();
+            }
+            else if ( tokens[2].type == Token::Command )
+            {
+                // identify command
+                if (!parseAsCommand(tokens[2].text,command))
+                    qWarning() << "Command" << tokens[2].text << "not understood.";
+            }
+
+            KeyboardTranslator::Entry newEntry;
+            newEntry.setKeyCode( keyCode );
+            newEntry.setState( flags );
+            newEntry.setStateMask( flagMask );
+            newEntry.setModifiers( modifiers );
+            newEntry.setModifierMask( modifierMask );
+            newEntry.setText( text );
+            newEntry.setCommand( command );
+
+            _nextEntry = newEntry;
+
+            _hasNext = true;
+
+            return;
+        }
+    } 
+
+    _hasNext = false;
+}
+
+bool KeyboardTranslatorReader::parseAsCommand(const QString& text,KeyboardTranslator::Command& command) 
+{
+    if ( text.compare("erase",Qt::CaseInsensitive) == 0 )
+        command = KeyboardTranslator::EraseCommand;
+    else if ( text.compare("scrollpageup",Qt::CaseInsensitive) == 0 )
+        command = KeyboardTranslator::ScrollPageUpCommand;
+    else if ( text.compare("scrollpagedown",Qt::CaseInsensitive) == 0 )
+        command = KeyboardTranslator::ScrollPageDownCommand;
+    else if ( text.compare("scrolllineup",Qt::CaseInsensitive) == 0 )
+        command = KeyboardTranslator::ScrollLineUpCommand;
+    else if ( text.compare("scrolllinedown",Qt::CaseInsensitive) == 0 )
+        command = KeyboardTranslator::ScrollLineDownCommand;
+    else if ( text.compare("scrolllock",Qt::CaseInsensitive) == 0 )
+        command = KeyboardTranslator::ScrollLockCommand;
+    else
+    	return false;
+
+    return true;
+}
+
+bool KeyboardTranslatorReader::decodeSequence(const QString& text,
+                                              int& keyCode,
+                                              Qt::KeyboardModifiers& modifiers,
+                                              Qt::KeyboardModifiers& modifierMask,
+                                              KeyboardTranslator::States& flags,
+                                              KeyboardTranslator::States& flagMask)
+{
+    bool isWanted = true; 
+    bool endOfItem = false;
+    QString buffer;
+
+    Qt::KeyboardModifiers tempModifiers = modifiers;
+    Qt::KeyboardModifiers tempModifierMask = modifierMask;
+    KeyboardTranslator::States tempFlags = flags;
+    KeyboardTranslator::States tempFlagMask = flagMask;
+
+    for ( int i = 0 ; i < text.count() ; i++ )
+    {
+        const QChar& ch = text[i];
+        bool isLastLetter = ( i == text.count()-1 );
+
+        endOfItem = true;
+        if ( ch.isLetterOrNumber() )
+        {
+            endOfItem = false;
+            buffer.append(ch);
+        }
+
+        if ( (endOfItem || isLastLetter) && !buffer.isEmpty() )
+        {
+            Qt::KeyboardModifier itemModifier = Qt::NoModifier;
+            int itemKeyCode = 0;
+            KeyboardTranslator::State itemFlag = KeyboardTranslator::NoState;
+
+            if ( parseAsModifier(buffer,itemModifier) )
+            {
+                tempModifierMask |= itemModifier;
+
+                if ( isWanted )
+                    tempModifiers |= itemModifier;
+            }
+            else if ( parseAsStateFlag(buffer,itemFlag) )
+            {
+                tempFlagMask |= itemFlag;
+
+                if ( isWanted )
+                    tempFlags |= itemFlag;
+            }
+            else if ( parseAsKeyCode(buffer,itemKeyCode) )
+                keyCode = itemKeyCode;
+            else
+                qDebug() << "Unable to parse key binding item:" << buffer;
+
+            buffer.clear();
+        }
+
+        // check if this is a wanted / not-wanted flag and update the 
+        // state ready for the next item
+        if ( ch == '+' )
+            isWanted = true;
+        else if ( ch == '-' )
+            isWanted = false;
+    } 
+
+    modifiers = tempModifiers;
+    modifierMask = tempModifierMask;
+    flags = tempFlags;
+    flagMask = tempFlagMask;
+
+    return true;
+}
+
+bool KeyboardTranslatorReader::parseAsModifier(const QString& item , Qt::KeyboardModifier& modifier)
+{
+    if ( item == "shift" )
+        modifier = Qt::ShiftModifier;
+    else if ( item == "ctrl" || item == "control" )
+        modifier = Qt::ControlModifier;
+    else if ( item == "alt" )
+        modifier = Qt::AltModifier;
+    else if ( item == "meta" )
+        modifier = Qt::MetaModifier;
+    else if ( item == "keypad" )
+        modifier = Qt::KeypadModifier;
+    else
+        return false;
+
+    return true;
+}
+bool KeyboardTranslatorReader::parseAsStateFlag(const QString& item , KeyboardTranslator::State& flag)
+{
+    if ( item == "appcukeys" )
+        flag = KeyboardTranslator::CursorKeysState;
+    else if ( item == "ansi" )
+        flag = KeyboardTranslator::AnsiState;
+    else if ( item == "newline" )
+        flag = KeyboardTranslator::NewLineState;
+    else if ( item == "appscreen" )
+        flag = KeyboardTranslator::AlternateScreenState;
+    else if ( item == "anymod" )
+        flag = KeyboardTranslator::AnyModifierState;
+    else
+        return false;
+
+    return true;
+}
+bool KeyboardTranslatorReader::parseAsKeyCode(const QString& item , int& keyCode)
+{
+    QKeySequence sequence = QKeySequence::fromString(item);
+    if ( !sequence.isEmpty() )
+    {
+        keyCode = sequence[0];
+
+        if ( sequence.count() > 1 )
+        {
+            qDebug() << "Unhandled key codes in sequence: " << item;
+        }
+    }
+    // additional cases implemented for backwards compatibility with KDE 3
+    else if ( item == "prior" )
+        keyCode = Qt::Key_PageUp;
+    else if ( item == "next" )
+        keyCode = Qt::Key_PageDown;
+    else
+        return false;
+
+    return true;
+}
+
+QString KeyboardTranslatorReader::description() const
+{
+    return _description;
+}
+bool KeyboardTranslatorReader::hasNextEntry()
+{
+    return _hasNext;
+}
+KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString& condition , 
+                                                                 const QString& result )
+{
+    QString entryString("keyboard \"temporary\"\nkey ");
+    entryString.append(condition);
+    entryString.append(" : ");
+
+    // if 'result' is the name of a command then the entry result will be that command,
+    // otherwise the result will be treated as a string to echo when the key sequence
+    // specified by 'condition' is pressed
+    KeyboardTranslator::Command command;
+    if (parseAsCommand(result,command))
+    	entryString.append(result);
+    else
+        entryString.append('\"' + result + '\"');
+
+    QByteArray array = entryString.toUtf8();
+
+    KeyboardTranslator::Entry entry;
+
+    QBuffer buffer(&array);
+    buffer.open(QIODevice::ReadOnly);
+    KeyboardTranslatorReader reader(&buffer);
+
+    if ( reader.hasNextEntry() )
+        entry = reader.nextEntry();
+
+    return entry;
+}
+
+KeyboardTranslator::Entry KeyboardTranslatorReader::nextEntry() 
+{
+    Q_ASSERT( _hasNext );
+
+
+    KeyboardTranslator::Entry entry = _nextEntry;
+
+    readNext();
+
+    return entry;
+}
+bool KeyboardTranslatorReader::parseError()
+{
+    return false;
+}
+QList<KeyboardTranslatorReader::Token> KeyboardTranslatorReader::tokenize(const QString& line)
+{
+    QString text = line.simplified();
+
+    // comment line: # comment
+    static QRegExp comment("\\#.*");
+    // title line: keyboard "title"
+    static QRegExp title("keyboard\\s+\"(.*)\"");
+    // key line: key KeySequence : "output"
+    // key line: key KeySequence : command
+    static QRegExp key("key\\s+([\\w\\+\\s\\-]+)\\s*:\\s*(\"(.*)\"|\\w+)");
+
+    QList<Token> list;
+
+    if ( text.isEmpty() || comment.exactMatch(text) )
+    {
+        return list;
+    }
+
+    if ( title.exactMatch(text) )
+    {
+        Token titleToken = { Token::TitleKeyword , QString() };
+        Token textToken = { Token::TitleText , title.capturedTexts()[1] };
+
+        list << titleToken << textToken;
+    }
+    else if  ( key.exactMatch(text) )
+    {
+        Token keyToken = { Token::KeyKeyword , QString() };
+        Token sequenceToken = { Token::KeySequence , key.capturedTexts()[1].remove(' ') };
+
+        list << keyToken << sequenceToken;
+
+        if ( key.capturedTexts()[3].isEmpty() )
+        {
+            // capturedTexts()[2] is a command
+            Token commandToken = { Token::Command , key.capturedTexts()[2] };
+            list << commandToken;    
+        }   
+        else
+        {
+            // capturedTexts()[3] is the output string
+            Token outputToken = { Token::OutputText , key.capturedTexts()[3] };
+            list << outputToken;
+        }     
+    }
+    else
+    {
+        qWarning() << "Line in keyboard translator file could not be understood:" << text;
+    }
+
+    return list;
+}
+
+QList<QString> KeyboardTranslatorManager::allTranslators() 
+{
+    if ( !_haveLoadedAll )
+    {
+        findTranslators();
+    }
+
+    return _translators.keys();
+}
+
+KeyboardTranslator::Entry::Entry()
+    : _keyCode(0)
+    , _modifiers(Qt::NoModifier)
+    , _modifierMask(Qt::NoModifier)
+    , _state(NoState)
+    , _stateMask(NoState)
+    , _command(NoCommand)
+{
+}
+
+bool KeyboardTranslator::Entry::operator==(const Entry& rhs) const
+{
+    return _keyCode == rhs._keyCode &&
+            _modifiers == rhs._modifiers &&
+            _modifierMask == rhs._modifierMask &&
+            _state == rhs._state &&
+            _stateMask == rhs._stateMask &&
+            _command == rhs._command &&
+            _text == rhs._text;
+}
+
+bool KeyboardTranslator::Entry::matches(int keyCode , 
+                                        Qt::KeyboardModifiers modifiers,
+                                        States state) const
+{
+    if ( _keyCode != keyCode )
+        return false;
+
+    if ( (modifiers & _modifierMask) != (_modifiers & _modifierMask) ) 
+        return false;
+
+    // if modifiers is non-zero, the 'any modifier' state is implicit
+    if ( modifiers != 0 )
+        state |= AnyModifierState;
+
+    if ( (state & _stateMask) != (_state & _stateMask) )
+        return false;
+
+    // special handling for the 'Any Modifier' state, which checks for the presence of 
+    // any or no modifiers.  In this context, the 'keypad' modifier does not count.
+    bool anyModifiersSet = modifiers != 0 && modifiers != Qt::KeypadModifier;
+    if ( _stateMask & KeyboardTranslator::AnyModifierState )
+    {
+        // test fails if any modifier is required but none are set
+        if ( (_state & KeyboardTranslator::AnyModifierState) && !anyModifiersSet )
+            return false;
+
+        // test fails if no modifier is allowed but one or more are set
+        if ( !(_state & KeyboardTranslator::AnyModifierState) && anyModifiersSet )
+            return false;
+    }
+
+    return true;
+}
+QByteArray KeyboardTranslator::Entry::escapedText(bool expandWildCards,Qt::KeyboardModifiers modifiers) const
+{
+    QByteArray result(text(expandWildCards,modifiers));
+
+    for ( int i = 0 ; i < result.count() ; i++ )
+    {
+        char ch = result[i];
+        char replacement = 0;
+
+        switch ( ch )
+        {
+        case 27 : replacement = 'E'; break;
+        case 8  : replacement = 'b'; break;
+        case 12 : replacement = 'f'; break;
+        case 9  : replacement = 't'; break;
+        case 13 : replacement = 'r'; break;
+        case 10 : replacement = 'n'; break;
+        default:
+            // any character which is not printable is replaced by an equivalent
+            // \xhh escape sequence (where 'hh' are the corresponding hex digits)
+            if ( !QChar(ch).isPrint() )
+                replacement = 'x';
+        }
+
+        if ( replacement == 'x' )
+        {
+            result.replace(i,1,"\\x"+QByteArray(1,ch).toInt(0, 16)); 
+        } else if ( replacement != 0 )
+        {
+            result.remove(i,1);
+            result.insert(i,'\\');
+            result.insert(i+1,replacement);
+        }
+    }
+
+    return result;
+}
+QByteArray KeyboardTranslator::Entry::unescape(const QByteArray& input) const
+{
+    QByteArray result(input);
+
+    for ( int i = 0 ; i < result.count()-1 ; i++ )
+    {
+
+        QByteRef ch = result[i];
+        if ( ch == '\\' )
+        {
+            char replacement[2] = {0,0};
+            int charsToRemove = 2;
+            bool escapedChar = true;
+
+            switch ( result[i+1] )
+            {
+            case 'E' : replacement[0] = 27; break;
+            case 'b' : replacement[0] = 8 ; break;
+            case 'f' : replacement[0] = 12; break;
+            case 't' : replacement[0] = 9 ; break;
+            case 'r' : replacement[0] = 13; break;
+            case 'n' : replacement[0] = 10; break;
+            case 'x' :
+            {
+                // format is \xh or \xhh where 'h' is a hexadecimal
+                // digit from 0-9 or A-F which should be replaced
+                // with the corresponding character value
+                char hexDigits[3] = {0};
+
+                if ( (i < result.count()-2) && isxdigit(result[i+2]) )
+                    hexDigits[0] = result[i+2];
+                if ( (i < result.count()-3) && isxdigit(result[i+3]) )
+                    hexDigits[1] = result[i+3];
+
+                int charValue = 0;
+                sscanf(hexDigits,"%x",&charValue);
+
+                replacement[0] = (char)charValue;
+
+                charsToRemove = 2 + strlen(hexDigits);
+            }
+            break;
+            default:
+                escapedChar = false;
+            }
+
+            if ( escapedChar )
+                result.replace(i,charsToRemove,replacement);
+        }
+    }
+    
+    return result;
+}
+
+void KeyboardTranslator::Entry::insertModifier( QString& item , int modifier ) const
+{
+    if ( !(modifier & _modifierMask) )
+        return;
+
+    if ( modifier & _modifiers )
+        item += '+';
+    else
+        item += '-';
+
+    if ( modifier == Qt::ShiftModifier )
+        item += "Shift";
+    else if ( modifier == Qt::ControlModifier )
+        item += "Ctrl";
+    else if ( modifier == Qt::AltModifier )
+        item += "Alt";
+    else if ( modifier == Qt::MetaModifier )
+        item += "Meta";
+    else if ( modifier == Qt::KeypadModifier )
+        item += "KeyPad";
+}
+void KeyboardTranslator::Entry::insertState( QString& item , int state ) const
+{
+    if ( !(state & _stateMask) )
+        return;
+
+    if ( state & _state )
+        item += '+' ;
+    else
+        item += '-' ;
+
+    if ( state == KeyboardTranslator::AlternateScreenState )
+        item += "AppScreen";
+    else if ( state == KeyboardTranslator::NewLineState )
+        item += "NewLine";
+    else if ( state == KeyboardTranslator::AnsiState )
+        item += "Ansi";
+    else if ( state == KeyboardTranslator::CursorKeysState )
+        item += "AppCuKeys";
+    else if ( state == KeyboardTranslator::AnyModifierState )
+        item += "AnyMod";
+}
+QString KeyboardTranslator::Entry::resultToString(bool expandWildCards,Qt::KeyboardModifiers modifiers) const
+{
+    if ( !_text.isEmpty() )
+        return escapedText(expandWildCards,modifiers);
+    else if ( _command == EraseCommand )
+        return "Erase";
+    else if ( _command == ScrollPageUpCommand )
+        return "ScrollPageUp";
+    else if ( _command == ScrollPageDownCommand )
+        return "ScrollPageDown";
+    else if ( _command == ScrollLineUpCommand )
+        return "ScrollLineUp";
+    else if ( _command == ScrollLineDownCommand )
+        return "ScrollLineDown";
+    else if ( _command == ScrollLockCommand )
+        return "ScrollLock";
+
+    return QString();
+}
+QString KeyboardTranslator::Entry::conditionToString() const
+{
+    QString result = QKeySequence(_keyCode).toString();
+
+    // add modifiers
+    insertModifier( result , Qt::ShiftModifier );
+    insertModifier( result , Qt::ControlModifier );
+    insertModifier( result , Qt::AltModifier );
+    insertModifier( result , Qt::MetaModifier ); 
+
+    // add states
+    insertState( result , KeyboardTranslator::AlternateScreenState );
+    insertState( result , KeyboardTranslator::NewLineState );
+    insertState( result , KeyboardTranslator::AnsiState );
+    insertState( result , KeyboardTranslator::CursorKeysState );
+    insertState( result , KeyboardTranslator::AnyModifierState );
+
+    return result;
+}
+
+KeyboardTranslator::KeyboardTranslator(const QString& name)
+    : _name(name)
+{
+}
+
+void KeyboardTranslator::setDescription(const QString& description) 
+{
+    _description = description;
+}
+QString KeyboardTranslator::description() const
+{
+    return _description;
+}
+void KeyboardTranslator::setName(const QString& name)
+{
+    _name = name;
+}
+QString KeyboardTranslator::name() const
+{
+    return _name;
+}
+
+QList<KeyboardTranslator::Entry> KeyboardTranslator::entries() const
+{
+    return _entries.values();
+}
+
+void KeyboardTranslator::addEntry(const Entry& entry)
+{
+    const int keyCode = entry.keyCode();
+    _entries.insertMulti(keyCode,entry);
+}
+void KeyboardTranslator::replaceEntry(const Entry& existing , const Entry& replacement)
+{
+    if ( !existing.isNull() )
+        _entries.remove(existing.keyCode());
+    _entries.insertMulti(replacement.keyCode(),replacement);
+}
+void KeyboardTranslator::removeEntry(const Entry& entry)
+{
+    _entries.remove(entry.keyCode());
+}
+KeyboardTranslator::Entry KeyboardTranslator::findEntry(int keyCode, Qt::KeyboardModifiers modifiers, States state) const
+{
+    if ( _entries.contains(keyCode) )
+    {
+        QList<Entry> entriesForKey = _entries.values(keyCode);
+        
+        QListIterator<Entry> iter(entriesForKey);
+
+        while (iter.hasNext())
+        {
+            const Entry& next = iter.next();
+            if ( next.matches(keyCode,modifiers,state) )
+                return next;
+        }
+
+        return Entry(); // entry not found
+    }
+    else
+    {
+        return Entry();
+    }
+    
+}
+void KeyboardTranslatorManager::addTranslator(KeyboardTranslator* translator)
+{
+    _translators.insert(translator->name(),translator);
+
+    if ( !saveTranslator(translator) )
+        qWarning() << "Unable to save translator" << translator->name()
+                   << "to disk.";
+}
+bool KeyboardTranslatorManager::deleteTranslator(const QString& name)
+{
+    Q_ASSERT( _translators.contains(name) );
+
+    // locate and delete
+    QString path = findTranslatorPath(name);
+    if ( QFile::remove(path) )
+    {
+        _translators.remove(name);
+        return true; 
+    }
+    else
+    {
+        qWarning() << "Failed to remove translator - " << path;
+        return false;
+    }
+}
+K_GLOBAL_STATIC( KeyboardTranslatorManager , theKeyboardTranslatorManager )
+KeyboardTranslatorManager* KeyboardTranslatorManager::instance()
+{
+    return theKeyboardTranslatorManager;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/KeyboardTranslator.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,650 @@
+/*
+    This source file is part of Konsole, a terminal emulator.
+
+    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+#ifndef KEYBOARDTRANSLATOR_H
+#define KEYBOARDTRANSLATOR_H
+
+// Qt
+#include <QtCore/QHash>
+#include <QtCore/QList>
+#include <QtGui/QKeySequence>
+#include <QtCore/QMetaType>
+#include <QtCore/QVarLengthArray>
+#include <QtCore>
+
+typedef void (*CleanUpFunction)();
+
+/**
+ * @internal
+ *
+ * Helper class for K_GLOBAL_STATIC to clean up the object on library unload or application
+ * shutdown.
+ */
+class CleanUpGlobalStatic
+{
+    public:
+        CleanUpFunction func;
+
+        inline ~CleanUpGlobalStatic() { func(); }
+};
+
+
+//these directives are taken from the heart of kdecore
+
+# define K_GLOBAL_STATIC_STRUCT_NAME(NAME)
+
+#if QT_VERSION < 0x040400
+# define Q_BASIC_ATOMIC_INITIALIZER     Q_ATOMIC_INIT
+# define testAndSetOrdered              testAndSet
+#endif
+
+#define K_GLOBAL_STATIC(TYPE, NAME) K_GLOBAL_STATIC_WITH_ARGS(TYPE, NAME, ())
+
+#define K_GLOBAL_STATIC_WITH_ARGS(TYPE, NAME, ARGS)                            \
+static QBasicAtomicPointer<TYPE > _k_static_##NAME = Q_BASIC_ATOMIC_INITIALIZER(0); \
+static bool _k_static_##NAME##_destroyed;                                      \
+static struct K_GLOBAL_STATIC_STRUCT_NAME(NAME)                                \
+{                                                                              \
+    bool isDestroyed()                                                         \
+    {                                                                          \
+        return _k_static_##NAME##_destroyed;                                   \
+    }                                                                          \
+    inline operator TYPE*()                                                    \
+    {                                                                          \
+        return operator->();                                                   \
+    }                                                                          \
+    inline TYPE *operator->()                                                  \
+    {                                                                          \
+        if (!_k_static_##NAME) {                                               \
+            if (isDestroyed()) {                                               \
+            qFatal("Fatal Error: Accessed global static '%s *%s()' after destruction. " \
+             "Defined at %s:%d", #TYPE, #NAME, __FILE__, __LINE__);		\
+	     }                                                                  \
+	     TYPE *x = new TYPE ARGS;                                           \
+	     if (!_k_static_##NAME.testAndSetOrdered(0, x)                      \
+	         && _k_static_##NAME != x ) {                                   \
+	         delete x;                                                      \
+	     } else { 								\
+		static CleanUpGlobalStatic cleanUpObject = { destroy };	\
+	     }   								\
+	 }                                                                      \
+         return _k_static_##NAME;                                               \
+    }            								\
+    inline TYPE &operator*()                                                   \
+    {                                                                          \
+        return *operator->();                                                  \
+    }                                                                          \
+    static void destroy()                                                      \
+    {                                                                          \
+        _k_static_##NAME##_destroyed = true;                                   \
+        TYPE *x = _k_static_##NAME;                                            \
+        _k_static_##NAME = 0;                                                  \
+        delete x;                                                              \
+    }                                                                          \
+} NAME;
+								
+								
+
+
+
+class QIODevice;
+class QTextStream;
+
+/** 
+ * A convertor which maps between key sequences pressed by the user and the
+ * character strings which should be sent to the terminal and commands
+ * which should be invoked when those character sequences are pressed.
+ *
+ * Konsole supports multiple keyboard translators, allowing the user to
+ * specify the character sequences which are sent to the terminal
+ * when particular key sequences are pressed.
+ *
+ * A key sequence is defined as a key code, associated keyboard modifiers
+ * (Shift,Ctrl,Alt,Meta etc.) and state flags which indicate the state
+ * which the terminal must be in for the key sequence to apply.
+ */
+class KeyboardTranslator
+{
+public:
+    /** 
+     * The meaning of a particular key sequence may depend upon the state which
+     * the terminal emulation is in.  Therefore findEntry() may return a different
+     * Entry depending upon the state flags supplied.
+     *
+     * This enum describes the states which may be associated with with a particular
+     * entry in the keyboard translation entry.
+     */
+    enum State
+    {
+        /** Indicates that no special state is active */
+        NoState = 0,
+        /**
+         * TODO More documentation
+         */
+        NewLineState = 1,
+        /** 
+         * Indicates that the terminal is in 'Ansi' mode.
+         * TODO: More documentation
+         */
+        AnsiState = 2,
+        /**
+         * TODO More documentation
+         */
+        CursorKeysState = 4,
+        /**
+         * Indicates that the alternate screen ( typically used by interactive programs
+         * such as screen or vim ) is active 
+         */
+        AlternateScreenState = 8,
+        /** Indicates that any of the modifier keys is active. */ 
+        AnyModifierState = 16
+    };
+    Q_DECLARE_FLAGS(States,State)
+
+    /**
+     * This enum describes commands which are associated with particular key sequences.
+     */
+    enum Command
+    {
+        /** Indicates that no command is associated with this command sequence */
+        NoCommand = 0,
+        /** TODO Document me */
+        SendCommand = 1,
+        /** Scroll the terminal display up one page */
+        ScrollPageUpCommand = 2,
+        /** Scroll the terminal display down one page */
+        ScrollPageDownCommand = 4,
+        /** Scroll the terminal display up one line */
+        ScrollLineUpCommand = 8,
+        /** Scroll the terminal display down one line */
+        ScrollLineDownCommand = 16,
+        /** Toggles scroll lock mode */
+        ScrollLockCommand = 32,
+		/** Echos the operating system specific erase character. */
+		EraseCommand = 64
+    };
+    Q_DECLARE_FLAGS(Commands,Command)
+
+    /**
+     * Represents an association between a key sequence pressed by the user
+     * and the character sequence and commands associated with it for a particular
+     * KeyboardTranslator.
+     */
+    class Entry
+    {
+    public:
+        /** 
+         * Constructs a new entry for a keyboard translator.
+         */
+        Entry();
+
+        /** 
+         * Returns true if this entry is null.
+         * This is true for newly constructed entries which have no properties set. 
+         */
+        bool isNull() const;
+
+        /** Returns the commands associated with this entry */
+        Command command() const;
+        /** Sets the command associated with this entry. */
+        void setCommand(Command command);
+
+        /** 
+         * Returns the character sequence associated with this entry, optionally replacing 
+         * wildcard '*' characters with numbers to indicate the keyboard modifiers being pressed.
+         *
+         * TODO: The numbers used to replace '*' characters are taken from the Konsole/KDE 3 code.
+         * Document them. 
+         *
+         * @param expandWildCards Specifies whether wild cards (occurrences of the '*' character) in
+         * the entry should be replaced with a number to indicate the modifier keys being pressed. 
+         *
+         * @param modifiers The keyboard modifiers being pressed.
+         */
+        QByteArray text(bool expandWildCards = false,
+                        Qt::KeyboardModifiers modifiers = Qt::NoModifier) const;
+
+        /** Sets the character sequence associated with this entry */
+        void setText(const QByteArray& text);
+
+        /** 
+         * Returns the character sequence associated with this entry,
+         * with any non-printable characters replaced with escape sequences.
+         *
+         * eg. \\E for Escape, \\t for tab, \\n for new line.
+         *
+         * @param expandWildCards See text()
+         * @param modifiers See text()
+         */
+        QByteArray escapedText(bool expandWildCards = false,
+                               Qt::KeyboardModifiers modifiers = Qt::NoModifier) const;
+
+        /** Returns the character code ( from the Qt::Key enum ) associated with this entry */
+        int keyCode() const;
+        /** Sets the character code associated with this entry */
+        void setKeyCode(int keyCode);
+
+        /** 
+         * Returns a bitwise-OR of the enabled keyboard modifiers associated with this entry. 
+         * If a modifier is set in modifierMask() but not in modifiers(), this means that the entry
+         * only matches when that modifier is NOT pressed.
+         *
+         * If a modifier is not set in modifierMask() then the entry matches whether the modifier
+         * is pressed or not. 
+         */
+        Qt::KeyboardModifiers modifiers() const;
+
+        /** Returns the keyboard modifiers which are valid in this entry.  See modifiers() */
+        Qt::KeyboardModifiers modifierMask() const;
+
+        /** See modifiers() */
+        void setModifiers( Qt::KeyboardModifiers modifiers );
+        /** See modifierMask() and modifiers() */
+        void setModifierMask( Qt::KeyboardModifiers modifiers );
+
+        /** 
+         * Returns a bitwise-OR of the enabled state flags associated with this entry. 
+         * If flag is set in stateMask() but not in state(), this means that the entry only 
+         * matches when the terminal is NOT in that state.
+         *
+         * If a state is not set in stateMask() then the entry matches whether the terminal
+         * is in that state or not. 
+         */
+        States state() const;
+
+        /** Returns the state flags which are valid in this entry.  See state() */
+        States stateMask() const;
+
+        /** See state() */
+        void setState( States state );
+        /** See stateMask() */
+        void setStateMask( States mask );
+
+        /** 
+         * Returns the key code and modifiers associated with this entry 
+         * as a QKeySequence
+         */
+        //QKeySequence keySequence() const;
+
+        /** 
+         * Returns this entry's conditions ( ie. its key code, modifier and state criteria )
+         * as a string.
+         */
+        QString conditionToString() const;
+
+        /**
+         * Returns this entry's result ( ie. its command or character sequence )
+         * as a string.
+         *
+         * @param expandWildCards See text()
+         * @param modifiers See text()
+         */
+        QString resultToString(bool expandWildCards = false,
+                               Qt::KeyboardModifiers modifiers = Qt::NoModifier) const;
+
+        /** 
+         * Returns true if this entry matches the given key sequence, specified
+         * as a combination of @p keyCode , @p modifiers and @p state.
+         */
+        bool matches( int keyCode , 
+                      Qt::KeyboardModifiers modifiers , 
+                      States flags ) const;
+
+        bool operator==(const Entry& rhs) const;
+       
+    private:
+        void insertModifier( QString& item , int modifier ) const;
+        void insertState( QString& item , int state ) const;
+        QByteArray unescape(const QByteArray& text) const;
+
+        int _keyCode;
+        Qt::KeyboardModifiers _modifiers;
+        Qt::KeyboardModifiers _modifierMask;
+        States _state;
+        States _stateMask;
+
+        Command _command;
+        QByteArray _text;
+    };
+
+    /** Constructs a new keyboard translator with the given @p name */
+    KeyboardTranslator(const QString& name);
+   
+    //KeyboardTranslator(const KeyboardTranslator& other);
+
+    /** Returns the name of this keyboard translator */
+    QString name() const;
+
+    /** Sets the name of this keyboard translator */
+    void setName(const QString& name);
+
+    /** Returns the descriptive name of this keyboard translator */
+    QString description() const;
+
+    /** Sets the descriptive name of this keyboard translator */
+    void setDescription(const QString& description);
+
+    /**
+     * Looks for an entry in this keyboard translator which matches the given
+     * key code, keyboard modifiers and state flags.
+     * 
+     * Returns the matching entry if found or a null Entry otherwise ( ie.
+     * entry.isNull() will return true )
+     *
+     * @param keyCode A key code from the Qt::Key enum
+     * @param modifiers A combination of modifiers
+     * @param state Optional flags which specify the current state of the terminal
+     */
+    Entry findEntry(int keyCode , 
+                    Qt::KeyboardModifiers modifiers , 
+                    States state = NoState) const;
+
+    /** 
+     * Adds an entry to this keyboard translator's table.  Entries can be looked up according
+     * to their key sequence using findEntry()
+     */
+    void addEntry(const Entry& entry);
+
+    /**
+     * Replaces an entry in the translator.  If the @p existing entry is null,
+     * then this is equivalent to calling addEntry(@p replacement)
+     */
+    void replaceEntry(const Entry& existing , const Entry& replacement);
+
+    /**
+     * Removes an entry from the table.
+     */
+    void removeEntry(const Entry& entry);
+
+    /** Returns a list of all entries in the translator. */
+    QList<Entry> entries() const;
+
+private:
+
+    QHash<int,Entry> _entries; // entries in this keyboard translation,
+                                                 // entries are indexed according to
+                                                 // their keycode
+    QString _name;
+    QString _description;
+};
+Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardTranslator::States)
+Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardTranslator::Commands)
+
+/** 
+ * Parses the contents of a Keyboard Translator (.keytab) file and 
+ * returns the entries found in it.
+ *
+ * Usage example:
+ *
+ * @code
+ *  QFile source( "/path/to/keytab" );
+ *  source.open( QIODevice::ReadOnly );
+ *
+ *  KeyboardTranslator* translator = new KeyboardTranslator( "name-of-translator" );
+ *
+ *  KeyboardTranslatorReader reader(source);
+ *  while ( reader.hasNextEntry() )
+ *      translator->addEntry(reader.nextEntry());
+ *
+ *  source.close();
+ *
+ *  if ( !reader.parseError() )
+ *  {
+ *      // parsing succeeded, do something with the translator
+ *  } 
+ *  else
+ *  {
+ *      // parsing failed
+ *  }
+ * @endcode
+ */
+class KeyboardTranslatorReader
+{
+public:
+    /** Constructs a new reader which parses the given @p source */
+    KeyboardTranslatorReader( QIODevice* source );
+
+    /** 
+     * Returns the description text. 
+     * TODO: More documentation 
+     */
+    QString description() const;
+
+    /** Returns true if there is another entry in the source stream */
+    bool hasNextEntry();
+    /** Returns the next entry found in the source stream */
+    KeyboardTranslator::Entry nextEntry(); 
+
+    /** 
+     * Returns true if an error occurred whilst parsing the input or
+     * false if no error occurred.
+     */
+    bool parseError();
+
+    /**
+     * Parses a condition and result string for a translator entry
+     * and produces a keyboard translator entry.
+     *
+     * The condition and result strings are in the same format as in  
+     */
+    static KeyboardTranslator::Entry createEntry( const QString& condition ,
+                                                  const QString& result );
+private:
+    struct Token
+    {
+        enum Type
+        {
+            TitleKeyword,
+            TitleText,
+            KeyKeyword,
+            KeySequence,
+            Command,
+            OutputText
+        };
+        Type type;
+        QString text;
+    };
+    QList<Token> tokenize(const QString&);
+    void readNext();
+    bool decodeSequence(const QString& , 
+                                int& keyCode,
+                                Qt::KeyboardModifiers& modifiers,
+                                Qt::KeyboardModifiers& modifierMask,
+                                KeyboardTranslator::States& state,
+                                KeyboardTranslator::States& stateFlags);
+
+    static bool parseAsModifier(const QString& item , Qt::KeyboardModifier& modifier);
+    static bool parseAsStateFlag(const QString& item , KeyboardTranslator::State& state);
+    static bool parseAsKeyCode(const QString& item , int& keyCode);
+   	static bool parseAsCommand(const QString& text , KeyboardTranslator::Command& command);
+
+    QIODevice* _source;
+    QString _description;
+    KeyboardTranslator::Entry _nextEntry;
+    bool _hasNext;
+};
+
+/** Writes a keyboard translation to disk. */
+class KeyboardTranslatorWriter
+{
+public:
+    /** 
+     * Constructs a new writer which saves data into @p destination.
+     * The caller is responsible for closing the device when writing is complete.
+     */
+    KeyboardTranslatorWriter(QIODevice* destination);
+    ~KeyboardTranslatorWriter();
+
+    /** 
+     * Writes the header for the keyboard translator. 
+     * @param description Description of the keyboard translator. 
+     */
+    void writeHeader( const QString& description );
+    /** Writes a translator entry. */
+    void writeEntry( const KeyboardTranslator::Entry& entry ); 
+
+private:
+    QIODevice* _destination;  
+    QTextStream* _writer;
+};
+
+/**
+ * Manages the keyboard translations available for use by terminal sessions,
+ * see KeyboardTranslator.
+ */
+class KeyboardTranslatorManager
+{
+public:
+    /** 
+     * Constructs a new KeyboardTranslatorManager and loads the list of
+     * available keyboard translations.
+     *
+     * The keyboard translations themselves are not loaded until they are
+     * first requested via a call to findTranslator()
+     */
+    KeyboardTranslatorManager();
+    ~KeyboardTranslatorManager();
+
+    /**
+     * Adds a new translator.  If a translator with the same name 
+     * already exists, it will be replaced by the new translator.
+     *
+     * TODO: More documentation.
+     */
+    void addTranslator(KeyboardTranslator* translator);
+
+    /**
+     * Deletes a translator.  Returns true on successful deletion or false otherwise.
+     *
+     * TODO: More documentation
+     */
+    bool deleteTranslator(const QString& name);
+
+    /** Returns the default translator for Konsole. */
+    const KeyboardTranslator* defaultTranslator();
+
+    /** 
+     * Returns the keyboard translator with the given name or 0 if no translator
+     * with that name exists.
+     *
+     * The first time that a translator with a particular name is requested,
+     * the on-disk .keyboard file is loaded and parsed.  
+     */
+    const KeyboardTranslator* findTranslator(const QString& name);
+    /**
+     * Returns a list of the names of available keyboard translators.
+     *
+     * The first time this is called, a search for available 
+     * translators is started.
+     */
+    QList<QString> allTranslators();
+
+    /** Returns the global KeyboardTranslatorManager instance. */
+   static KeyboardTranslatorManager* instance();
+
+private:
+    static const char* defaultTranslatorText;
+    
+    void findTranslators(); // locate the available translators
+    KeyboardTranslator* loadTranslator(const QString& name); // loads the translator 
+                                                             // with the given name
+    KeyboardTranslator* loadTranslator(QIODevice* device,const QString& name);
+
+    bool saveTranslator(const KeyboardTranslator* translator);
+    QString findTranslatorPath(const QString& name);
+    
+    QHash<QString,KeyboardTranslator*> _translators; // maps translator-name -> KeyboardTranslator
+                                                     // instance
+    bool _haveLoadedAll;
+};
+
+inline int KeyboardTranslator::Entry::keyCode() const { return _keyCode; }
+inline void KeyboardTranslator::Entry::setKeyCode(int keyCode) { _keyCode = keyCode; }
+
+inline void KeyboardTranslator::Entry::setModifiers( Qt::KeyboardModifiers modifier ) 
+{ 
+    _modifiers = modifier;
+}
+inline Qt::KeyboardModifiers KeyboardTranslator::Entry::modifiers() const { return _modifiers; }
+
+inline void  KeyboardTranslator::Entry::setModifierMask( Qt::KeyboardModifiers mask ) 
+{ 
+   _modifierMask = mask; 
+}
+inline Qt::KeyboardModifiers KeyboardTranslator::Entry::modifierMask() const { return _modifierMask; }
+
+inline bool KeyboardTranslator::Entry::isNull() const
+{
+    return ( *this == Entry() );
+}
+
+inline void KeyboardTranslator::Entry::setCommand( Command command )
+{ 
+    _command = command; 
+}
+inline KeyboardTranslator::Command KeyboardTranslator::Entry::command() const { return _command; }
+
+inline void KeyboardTranslator::Entry::setText( const QByteArray& text )
+{ 
+    _text = unescape(text);
+}
+inline int oneOrZero(int value)
+{
+    return value ? 1 : 0;
+}
+inline QByteArray KeyboardTranslator::Entry::text(bool expandWildCards,Qt::KeyboardModifiers modifiers) const 
+{
+    QByteArray expandedText = _text;
+    
+    if (expandWildCards)
+    {
+        int modifierValue = 1;
+        modifierValue += oneOrZero(modifiers & Qt::ShiftModifier);
+        modifierValue += oneOrZero(modifiers & Qt::AltModifier)     << 1;
+        modifierValue += oneOrZero(modifiers & Qt::ControlModifier) << 2;
+
+        for (int i=0;i<_text.length();i++) 
+        {
+            if (expandedText[i] == '*')
+                expandedText[i] = '0' + modifierValue;
+        }
+    }
+
+    return expandedText; 
+}
+
+inline void KeyboardTranslator::Entry::setState( States state )
+{ 
+    _state = state; 
+}
+inline KeyboardTranslator::States KeyboardTranslator::Entry::state() const { return _state; }
+
+inline void KeyboardTranslator::Entry::setStateMask( States stateMask )
+{ 
+    _stateMask = stateMask; 
+}
+inline KeyboardTranslator::States KeyboardTranslator::Entry::stateMask() const { return _stateMask; }
+
+
+#endif // KEYBOARDTRANSLATOR_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/LineFont.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,21 @@
+// WARNING: Autogenerated by "fontembedder ./linefont.src".
+// You probably do not want to hand-edit this!
+
+static const quint32 LineChars[] = {
+	0x00007c00, 0x000fffe0, 0x00421084, 0x00e739ce, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 
+	0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00427000, 0x004e7380, 0x00e77800, 0x00ef7bc0, 
+	0x00421c00, 0x00439ce0, 0x00e73c00, 0x00e7bde0, 0x00007084, 0x000e7384, 0x000079ce, 0x000f7bce, 
+	0x00001c84, 0x00039ce4, 0x00003dce, 0x0007bdee, 0x00427084, 0x004e7384, 0x004279ce, 0x00e77884, 
+	0x00e779ce, 0x004f7bce, 0x00ef7bc4, 0x00ef7bce, 0x00421c84, 0x00439ce4, 0x00423dce, 0x00e73c84, 
+	0x00e73dce, 0x0047bdee, 0x00e7bde4, 0x00e7bdee, 0x00427c00, 0x0043fce0, 0x004e7f80, 0x004fffe0, 
+	0x004fffe0, 0x00e7fde0, 0x006f7fc0, 0x00efffe0, 0x00007c84, 0x0003fce4, 0x000e7f84, 0x000fffe4, 
+	0x00007dce, 0x0007fdee, 0x000f7fce, 0x000fffee, 0x00427c84, 0x0043fce4, 0x004e7f84, 0x004fffe4, 
+	0x00427dce, 0x00e77c84, 0x00e77dce, 0x0047fdee, 0x004e7fce, 0x00e7fde4, 0x00ef7f84, 0x004fffee, 
+	0x00efffe4, 0x00e7fdee, 0x00ef7fce, 0x00efffee, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 
+	0x000f83e0, 0x00a5294a, 0x004e1380, 0x00a57800, 0x00ad0bc0, 0x004390e0, 0x00a53c00, 0x00a5a1e0, 
+	0x000e1384, 0x0000794a, 0x000f0b4a, 0x000390e4, 0x00003d4a, 0x0007a16a, 0x004e1384, 0x00a5694a, 
+	0x00ad2b4a, 0x004390e4, 0x00a52d4a, 0x00a5a16a, 0x004f83e0, 0x00a57c00, 0x00ad83e0, 0x000f83e4, 
+	0x00007d4a, 0x000f836a, 0x004f93e4, 0x00a57d4a, 0x00ad836a, 0x00000000, 0x00000000, 0x00000000, 
+	0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00001c00, 0x00001084, 0x00007000, 0x00421000, 
+	0x00039ce0, 0x000039ce, 0x000e7380, 0x00e73800, 0x000e7f80, 0x00e73884, 0x0003fce0, 0x004239ce
+};
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/QUnixTerminalImpl.cpp	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,163 @@
+/*  Copyright (C) 2008 e_k (e_k@users.sourceforge.net)
+    Copyright (C) 2012 Jacob Dawid <jacob.dawid@googlemail.com>
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Library General Public
+    License as published by the Free Software Foundation; either
+    version 2 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Library General Public License for more details.
+
+    You should have received a copy of the GNU Library General Public License
+    along with this library; see the file COPYING.LIB.  If not, write to
+    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+    Boston, MA 02110-1301, USA.
+*/
+
+#include <QDebug>
+
+#include "unix/QUnixTerminalImpl.h"
+#include "unix/kpty.h"
+
+#include <termios.h>
+
+QUnixTerminalImpl::QUnixTerminalImpl(QWidget *parent)
+    : QTerminalInterface(parent) {
+    setMinimumSize(600, 400);
+    initialize();
+}
+
+void QUnixTerminalImpl::initialize()
+{
+    m_terminalView = new TerminalView(this);
+    m_terminalView->setKeyboardCursorShape(TerminalView::UnderlineCursor);
+    m_terminalView->setBlinkingCursor(true);
+    m_terminalView->setBellMode(TerminalView::NotifyBell);
+    m_terminalView->setTerminalSizeHint(true);
+    m_terminalView->setContextMenuPolicy(Qt::CustomContextMenu);
+    m_terminalView->setTripleClickMode(TerminalView::SelectWholeLine);
+    m_terminalView->setTerminalSizeStartup(true);
+    m_terminalView->setSize(80, 40);
+    m_terminalView->setScrollBarPosition(TerminalView::ScrollBarRight);
+
+    connect(m_terminalView, SIGNAL(customContextMenuRequested(QPoint)),
+            this, SLOT(handleCustomContextMenuRequested(QPoint)));
+
+#ifdef Q_OS_MAC
+    QFont font = QFont("Monaco");
+    font.setStyleHint(QFont::TypeWriter);
+    font.setPointSize(11);
+#else
+    QFont font = QFont("Monospace");
+    font.setStyleHint(QFont::TypeWriter);
+    font.setPointSize(10);
+#endif
+    setTerminalFont(font);
+    setFocusProxy(m_terminalView);
+    setFocus(Qt::OtherFocusReason);
+
+    m_kpty = new KPty();
+    m_kpty->open();
+
+    m_terminalModel = new TerminalModel(m_kpty);
+    m_terminalModel->setAutoClose(true);
+    m_terminalModel->setCodec(QTextCodec::codecForName("UTF-8"));
+    m_terminalModel->setHistoryType(HistoryTypeBuffer(1000));
+    m_terminalModel->setDarkBackground(true);
+    m_terminalModel->setKeyBindings("");
+    m_terminalModel->run();
+    m_terminalModel->addView(m_terminalView);
+    connectToPty();
+}
+
+void QUnixTerminalImpl::connectToPty()
+{
+    int fds = m_kpty->slaveFd();
+
+    dup2 (fds, STDIN_FILENO);
+    dup2 (fds, STDOUT_FILENO);
+    dup2 (fds, STDERR_FILENO);
+
+    if(!isatty(STDIN_FILENO)) {
+        qDebug("Error: stdin is not a tty.");
+    }
+
+    if(!isatty(STDOUT_FILENO)) {
+        qDebug("Error: stdout is not a tty.");
+    }
+
+    if(!isatty(STDERR_FILENO)) {
+        qDebug("Error: stderr is not a tty.");
+    }
+}
+
+QUnixTerminalImpl::~QUnixTerminalImpl()
+{
+    emit destroyed();
+}
+
+void QUnixTerminalImpl::setTerminalFont(const QFont &font)
+{
+    if(!m_terminalView)
+        return;
+    m_terminalView->setVTFont(font);
+}
+
+void QUnixTerminalImpl::setSize(int h, int v)
+{
+    if(!m_terminalView)
+        return;
+    m_terminalView->setSize(h, v);
+}
+
+void QUnixTerminalImpl::sendText(const QString& text)
+{
+    m_terminalModel->sendText(text);
+}
+
+void QUnixTerminalImpl::setCursorType(CursorType type, bool blinking)
+{
+    switch(type) {
+        case UnderlineCursor: m_terminalView->setKeyboardCursorShape(TerminalView::UnderlineCursor); break;
+        case BlockCursor: m_terminalView->setKeyboardCursorShape(TerminalView::BlockCursor); break;
+        case IBeamCursor: m_terminalView->setKeyboardCursorShape(TerminalView::IBeamCursor); break;
+    }
+    m_terminalView->setBlinkingCursor(blinking);
+}
+
+void QUnixTerminalImpl::focusInEvent(QFocusEvent *focusEvent)
+{
+    Q_UNUSED(focusEvent);
+    m_terminalView->updateImage();
+    m_terminalView->repaint();
+    m_terminalView->update();
+}
+
+void QUnixTerminalImpl::showEvent(QShowEvent *)
+{
+    m_terminalView->updateImage();
+    m_terminalView->repaint();
+    m_terminalView->update();
+}
+
+void QUnixTerminalImpl::resizeEvent(QResizeEvent*)
+{
+    m_terminalView->resize(this->size());
+    m_terminalView->updateImage();
+    m_terminalView->repaint();
+    m_terminalView->update();
+}
+
+void QUnixTerminalImpl::copyClipboard()
+{
+    m_terminalView->copyClipboard();
+}
+
+void QUnixTerminalImpl::pasteClipboard()
+{
+    m_terminalView->pasteClipboard();
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/QUnixTerminalImpl.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,61 @@
+/*  Copyright (C) 2008 e_k (e_k@users.sourceforge.net)
+    Copyright (C) 2012 Jacob Dawid <jacob.dawid@googlemail.com>
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Library General Public
+    License as published by the Free Software Foundation; either
+    version 2 of the License, or (at your option) any later version.
+		    
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Library General Public License for more details.
+			    
+    You should have received a copy of the GNU Library General Public License
+    along with this library; see the file COPYING.LIB.  If not, write to
+    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+    Boston, MA 02110-1301, USA.
+*/
+						    
+
+#ifndef Q_UNIXTERMINALIMPL
+#define Q_UNIXTERMINALIMPL
+
+#include <QtGui>
+#include "unix/kpty.h"
+#include "unix/TerminalModel.h"
+#include "unix/TerminalView.h"
+#include "QTerminalInterface.h"
+
+class QUnixTerminalImpl : public QTerminalInterface
+{
+    Q_OBJECT
+public:
+    QUnixTerminalImpl(QWidget *parent = 0);
+    virtual ~QUnixTerminalImpl();
+    
+    void setTerminalFont(const QFont &font); 
+    void setSize(int h, int v);
+    void sendText(const QString& text);
+
+    void setCursorType(CursorType type, bool blinking);
+
+public slots:
+    void copyClipboard();
+    void pasteClipboard();
+        
+protected:
+    void focusInEvent(QFocusEvent *focusEvent);
+    void showEvent(QShowEvent *);
+    virtual void resizeEvent(QResizeEvent *);   
+    
+private:
+    void initialize();
+    void connectToPty();
+
+    TerminalView *m_terminalView;
+    TerminalModel *m_terminalModel;
+    KPty *m_kpty;
+};
+
+#endif // Q_UNIXTERMINALIMPL
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/Screen.cpp	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,1566 @@
+/*
+    This file is part of Konsole, an X terminal.
+    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+// Own
+#include "unix/Screen.h"
+
+// Standard
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <assert.h>
+#include <string.h>
+#include <ctype.h>
+
+// Qt
+#include <QtCore/QTextStream>
+#include <QtCore/QDate>
+
+// Konsole
+#include "unix/konsole_wcwidth.h"
+#include "unix/TerminalCharacterDecoder.h"
+
+//FIXME: this is emulation specific. Use false for xterm, true for ANSI.
+//FIXME: see if we can get this from terminfo.
+#define BS_CLEARS false
+
+//Macro to convert x,y position on screen to position within an image.
+//
+//Originally the image was stored as one large contiguous block of 
+//memory, so a position within the image could be represented as an
+//offset from the beginning of the block.  For efficiency reasons this
+//is no longer the case.  
+//Many internal parts of this class still use this representation for parameters and so on,
+//notably moveImage() and clearImage().
+//This macro converts from an X,Y position into an image offset.
+#ifndef loc
+#define loc(X,Y) ((Y)*columns+(X))
+#endif
+
+
+Character Screen::defaultChar = Character(' ',
+					  CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR),
+					  CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR),
+					  DEFAULT_RENDITION);
+
+//#define REVERSE_WRAPPED_LINES  // for wrapped line debug
+
+Screen::Screen(int l, int c)
+  : lines(l),
+    columns(c),
+    screenLines(new ImageLine[lines+1] ),
+    _scrolledLines(0),
+    _droppedLines(0),
+    hist(new HistoryScrollNone()),
+    cuX(0), cuY(0),
+    cu_re(0),
+    tmargin(0), bmargin(0),
+    tabstops(0),
+    sel_begin(0), sel_TL(0), sel_BR(0),
+    sel_busy(false),
+    columnmode(false),
+    ef_fg(CharacterColor()), ef_bg(CharacterColor()), ef_re(0),
+    sa_cuX(0), sa_cuY(0),
+    sa_cu_re(0),
+    lastPos(-1)
+{
+  lineProperties.resize(lines+1);
+  for (int i=0;i<lines+1;i++)
+          lineProperties[i]=LINE_DEFAULT;
+
+  initTabStops();
+  clearSelection();
+  reset();
+}
+
+/*! Destructor
+*/
+
+Screen::~Screen()
+{
+  delete[] screenLines;
+  delete[] tabstops;
+  delete hist;
+}
+
+/* ------------------------------------------------------------------------- */
+/*                                                                           */
+/* Normalized                    Screen Operations                           */
+/*                                                                           */
+/* ------------------------------------------------------------------------- */
+
+// Cursor Setting --------------------------------------------------------------
+
+/*! \section Cursor
+
+    The `cursor' is a location within the screen that is implicitely used in
+    many operations. The operations within this section allow to manipulate
+    the cursor explicitly and to obtain it's value.
+
+    The position of the cursor is guarantied to be between (including) 0 and
+    `columns-1' and `lines-1'.
+*/
+
+/*!
+    Move the cursor up.
+
+    The cursor will not be moved beyond the top margin.
+*/
+
+void Screen::cursorUp(int n)
+//=CUU
+{
+  if (n == 0) n = 1; // Default
+  int stop = cuY < tmargin ? 0 : tmargin;
+  cuX = qMin(columns-1,cuX); // nowrap!
+  cuY = qMax(stop,cuY-n);
+}
+
+/*!
+    Move the cursor down.
+
+    The cursor will not be moved beyond the bottom margin.
+*/
+
+void Screen::cursorDown(int n)
+//=CUD
+{
+  if (n == 0) n = 1; // Default
+  int stop = cuY > bmargin ? lines-1 : bmargin;
+  cuX = qMin(columns-1,cuX); // nowrap!
+  cuY = qMin(stop,cuY+n);
+}
+
+/*!
+    Move the cursor left.
+
+    The cursor will not move beyond the first column.
+*/
+
+void Screen::cursorLeft(int n)
+//=CUB
+{
+  if (n == 0) n = 1; // Default
+  cuX = qMin(columns-1,cuX); // nowrap!
+  cuX = qMax(0,cuX-n);
+}
+
+/*!
+    Move the cursor left.
+
+    The cursor will not move beyond the rightmost column.
+*/
+
+void Screen::cursorRight(int n)
+//=CUF
+{
+  if (n == 0) n = 1; // Default
+  cuX = qMin(columns-1,cuX+n);
+}
+
+void Screen::setMargins(int top, int bot)
+//=STBM
+{
+  if (top == 0) top = 1;      // Default
+  if (bot == 0) bot = lines;  // Default
+  top = top - 1;              // Adjust to internal lineno
+  bot = bot - 1;              // Adjust to internal lineno
+  if ( !( 0 <= top && top < bot && bot < lines ) )
+  { qDebug()<<" setRegion("<<top<<","<<bot<<") : bad range.";
+    return;                   // Default error action: ignore
+  }
+  tmargin = top;
+  bmargin = bot;
+  cuX = 0;
+  cuY = getMode(MODE_Origin) ? top : 0;
+
+}
+
+int Screen::topMargin() const
+{
+    return tmargin;
+}
+int Screen::bottomMargin() const
+{
+    return bmargin;
+}
+
+void Screen::index()
+//=IND
+{
+  if (cuY == bmargin)
+  {
+    scrollUp(1);
+  }
+  else if (cuY < lines-1)
+    cuY += 1;
+}
+
+void Screen::reverseIndex()
+//=RI
+{
+  if (cuY == tmargin)
+     scrollDown(tmargin,1);
+  else if (cuY > 0)
+    cuY -= 1;
+}
+
+/*!
+    Move the cursor to the begin of the next line.
+
+    If cursor is on bottom margin, the region between the
+    actual top and bottom margin is scrolled up.
+*/
+
+void Screen::NextLine()
+//=NEL
+{
+  Return(); index();
+}
+
+void Screen::eraseChars(int n)
+{
+  if (n == 0) n = 1; // Default
+  int p = qMax(0,qMin(cuX+n-1,columns-1));
+  clearImage(loc(cuX,cuY),loc(p,cuY),' ');
+}
+
+void Screen::deleteChars(int n)
+{
+  Q_ASSERT( n >= 0 );
+
+  // always delete at least one char
+  if (n == 0) 
+      n = 1; 
+
+  // if cursor is beyond the end of the line there is nothing to do
+  if ( cuX >= screenLines[cuY].count() )
+      return;
+
+  if ( cuX+n >= screenLines[cuY].count() ) 
+       n = screenLines[cuY].count() - 1 - cuX;
+
+  Q_ASSERT( n >= 0 );
+  Q_ASSERT( cuX+n < screenLines[cuY].count() );
+
+  screenLines[cuY].remove(cuX,n);
+}
+
+void Screen::insertChars(int n)
+{
+  if (n == 0) n = 1; // Default
+
+  if ( screenLines[cuY].size() < cuX )
+    screenLines[cuY].resize(cuX);
+
+  screenLines[cuY].insert(cuX,n,' ');
+
+  if ( screenLines[cuY].count() > columns )
+      screenLines[cuY].resize(columns);
+}
+
+void Screen::deleteLines(int n)
+{
+  if (n == 0) n = 1; // Default
+  scrollUp(cuY,n);
+}
+
+/*! insert `n' lines at the cursor position.
+
+    The cursor is not moved by the operation.
+*/
+
+void Screen::insertLines(int n)
+{
+  if (n == 0) n = 1; // Default
+  scrollDown(cuY,n);
+}
+
+// Mode Operations -----------------------------------------------------------
+
+/*! Set a specific mode. */
+
+void Screen::setMode(int m)
+{
+  currParm.mode[m] = true;
+  switch(m)
+  {
+    case MODE_Origin : cuX = 0; cuY = tmargin; break; //FIXME: home
+  }
+}
+
+/*! Reset a specific mode. */
+
+void Screen::resetMode(int m)
+{
+  currParm.mode[m] = false;
+  switch(m)
+  {
+    case MODE_Origin : cuX = 0; cuY = 0; break; //FIXME: home
+  }
+}
+
+/*! Save a specific mode. */
+
+void Screen::saveMode(int m)
+{
+  saveParm.mode[m] = currParm.mode[m];
+}
+
+/*! Restore a specific mode. */
+
+void Screen::restoreMode(int m)
+{
+  currParm.mode[m] = saveParm.mode[m];
+}
+
+bool Screen::getMode(int m) const
+{
+  return currParm.mode[m];
+}
+
+void Screen::saveCursor()
+{
+  sa_cuX     = cuX;
+  sa_cuY     = cuY;
+  sa_cu_re   = cu_re;
+  sa_cu_fg   = cu_fg;
+  sa_cu_bg   = cu_bg;
+}
+
+void Screen::restoreCursor()
+{
+  cuX     = qMin(sa_cuX,columns-1);
+  cuY     = qMin(sa_cuY,lines-1);
+  cu_re   = sa_cu_re;
+  cu_fg   = sa_cu_fg;
+  cu_bg   = sa_cu_bg;
+  effectiveRendition();
+}
+
+/* ------------------------------------------------------------------------- */
+/*                                                                           */
+/*                             Screen Operations                             */
+/*                                                                           */
+/* ------------------------------------------------------------------------- */
+
+/*! Resize the screen image
+
+    The topmost left position is maintained, while lower lines
+    or right hand side columns might be removed or filled with
+    spaces to fit the new size.
+
+    The region setting is reset to the whole screen and the
+    tab positions reinitialized.
+
+    If the new image is narrower than the old image then text on lines
+    which extends past the end of the new image is preserved so that it becomes
+    visible again if the screen is later resized to make it larger.
+*/
+
+void Screen::resizeImage(int new_lines, int new_columns)
+{
+  if ((new_lines==lines) && (new_columns==columns)) return;
+
+  if (cuY > new_lines-1)
+  { // attempt to preserve focus and lines
+    bmargin = lines-1; //FIXME: margin lost
+    for (int i = 0; i < cuY-(new_lines-1); i++)
+    {
+      addHistLine(); scrollUp(0,1);
+    }
+  }
+
+  // create new screen lines and copy from old to new
+  
+   ImageLine* newScreenLines = new ImageLine[new_lines+1];
+   for (int i=0; i < qMin(lines-1,new_lines+1) ;i++)
+           newScreenLines[i]=screenLines[i];
+   for (int i=lines;(i > 0) && (i<new_lines+1);i++)
+           newScreenLines[i].resize( new_columns );
+   
+  lineProperties.resize(new_lines+1);
+  for (int i=lines;(i > 0) && (i<new_lines+1);i++)
+          lineProperties[i] = LINE_DEFAULT;
+
+  clearSelection();
+ 
+  delete[] screenLines; 
+  screenLines = newScreenLines;
+
+  lines = new_lines;
+  columns = new_columns;
+  cuX = qMin(cuX,columns-1);
+  cuY = qMin(cuY,lines-1);
+
+  // FIXME: try to keep values, evtl.
+  tmargin=0;
+  bmargin=lines-1;
+  initTabStops();
+  clearSelection();
+}
+
+void Screen::setDefaultMargins()
+{
+	tmargin = 0;
+	bmargin = lines-1;
+}
+
+
+/*
+   Clarifying rendition here and in the display.
+
+   currently, the display's color table is
+     0       1       2 .. 9    10 .. 17
+     dft_fg, dft_bg, dim 0..7, intensive 0..7
+
+   cu_fg, cu_bg contain values 0..8;
+   - 0    = default color
+   - 1..8 = ansi specified color
+
+   re_fg, re_bg contain values 0..17
+   due to the TerminalDisplay's color table
+
+   rendition attributes are
+
+      attr           widget screen
+      -------------- ------ ------
+      RE_UNDERLINE     XX     XX    affects foreground only
+      RE_BLINK         XX     XX    affects foreground only
+      RE_BOLD          XX     XX    affects foreground only
+      RE_REVERSE       --     XX
+      RE_TRANSPARENT   XX     --    affects background only
+      RE_INTENSIVE     XX     --    affects foreground only
+
+   Note that RE_BOLD is used in both widget
+   and screen rendition. Since xterm/vt102
+   is to poor to distinguish between bold
+   (which is a font attribute) and intensive
+   (which is a color attribute), we translate
+   this and RE_BOLD in falls eventually appart
+   into RE_BOLD and RE_INTENSIVE.
+*/
+
+void Screen::reverseRendition(Character& p) const
+{ 
+	CharacterColor f = p.foregroundColor; 
+	CharacterColor b = p.backgroundColor;
+  	
+	p.foregroundColor = b; 
+	p.backgroundColor = f; //p->r &= ~RE_TRANSPARENT;
+}
+
+void Screen::effectiveRendition()
+// calculate rendition
+{
+  //copy "current rendition" straight into "effective rendition", which is then later copied directly
+  //into the image[] array which holds the characters and their appearance properties.
+  //- The old version below filtered out all attributes other than underline and blink at this stage,
+  //so that they would not be copied into the image[] array and hence would not be visible by TerminalDisplay
+  //which actually paints the screen using the information from the image[] array.  
+  //I don't know why it did this, but I'm fairly sure it was the wrong thing to do.  The net result
+  //was that bold text wasn't printed in bold by Konsole.
+  ef_re = cu_re;
+  
+  //OLD VERSION:
+  //ef_re = cu_re & (RE_UNDERLINE | RE_BLINK);
+  
+  if (cu_re & RE_REVERSE)
+  {
+    ef_fg = cu_bg;
+    ef_bg = cu_fg;
+  }
+  else
+  {
+    ef_fg = cu_fg;
+    ef_bg = cu_bg;
+  }
+ 
+  if (cu_re & RE_BOLD)
+    ef_fg.toggleIntensive();
+}
+
+/*!
+    returns the image.
+
+    Get the size of the image by \sa getLines and \sa getColumns.
+
+    NOTE that the image returned by this function must later be
+    freed.
+
+*/
+
+void Screen::copyFromHistory(Character* dest, int startLine, int count) const
+{
+  Q_ASSERT( startLine >= 0 && count > 0 && startLine + count <= hist->getLines() );
+
+  for (int line = startLine; line < startLine + count; line++) 
+  {
+    const int length = qMin(columns,hist->getLineLen(line));
+    const int destLineOffset  = (line-startLine)*columns;
+
+    hist->getCells(line,0,length,dest + destLineOffset);
+
+    for (int column = length; column < columns; column++) 
+		dest[destLineOffset+column] = defaultChar;
+    
+	// invert selected text
+	if (sel_begin !=-1)
+	{
+    	for (int column = 0; column < columns; column++)
+    	{
+        	if (isSelected(column,line)) 
+			{
+          		reverseRendition(dest[destLineOffset + column]); 
+    		}
+  		}
+	}
+  }
+}
+
+void Screen::copyFromScreen(Character* dest , int startLine , int count) const
+{
+	Q_ASSERT( startLine >= 0 && count > 0 && startLine + count <= lines );
+
+    for (int line = startLine; line < (startLine+count) ; line++)
+    {
+       int srcLineStartIndex  = line*columns;
+	   int destLineStartIndex = (line-startLine)*columns;
+
+       for (int column = 0; column < columns; column++)
+       { 
+		 int srcIndex = srcLineStartIndex + column; 
+		 int destIndex = destLineStartIndex + column;
+
+         dest[destIndex] = screenLines[srcIndex/columns].value(srcIndex%columns,defaultChar);
+
+	     // invert selected text
+         if (sel_begin != -1 && isSelected(column,line + hist->getLines()))
+           reverseRendition(dest[destIndex]); 
+       }
+
+    }
+}
+
+void Screen::getImage( Character* dest, int size, int startLine, int endLine ) const
+{
+  Q_ASSERT( startLine >= 0 ); 
+  Q_ASSERT( endLine >= startLine && endLine < hist->getLines() + lines );
+
+  const int mergedLines = endLine - startLine + 1;
+
+  Q_ASSERT( size >= mergedLines * columns ); 
+  Q_UNUSED( size );
+
+  const int linesInHistoryBuffer = qBound(0,hist->getLines()-startLine,mergedLines);
+  const int linesInScreenBuffer = mergedLines - linesInHistoryBuffer;
+
+  // copy lines from history buffer
+  if (linesInHistoryBuffer > 0) {
+  	copyFromHistory(dest,startLine,linesInHistoryBuffer); 
+    }
+
+  // copy lines from screen buffer
+  if (linesInScreenBuffer > 0) {
+  	copyFromScreen(dest + linesInHistoryBuffer*columns,
+				   startLine + linesInHistoryBuffer - hist->getLines(),
+				   linesInScreenBuffer);
+    }				
+ 
+  // invert display when in screen mode
+  if (getMode(MODE_Screen))
+  {  
+    for (int i = 0; i < mergedLines*columns; i++)
+      reverseRendition(dest[i]); // for reverse display
+  }
+
+  // mark the character at the current cursor position
+  int cursorIndex = loc(cuX, cuY + linesInHistoryBuffer);
+  if(getMode(MODE_Cursor) && cursorIndex < columns*mergedLines)
+    dest[cursorIndex].rendition |= RE_CURSOR;
+}
+
+QVector<LineProperty> Screen::getLineProperties( int startLine , int endLine ) const
+{
+  Q_ASSERT( startLine >= 0 ); 
+  Q_ASSERT( endLine >= startLine && endLine < hist->getLines() + lines );
+
+	const int mergedLines = endLine-startLine+1;
+	const int linesInHistory = qBound(0,hist->getLines()-startLine,mergedLines);
+  const int linesInScreen = mergedLines - linesInHistory;
+
+  QVector<LineProperty> result(mergedLines);
+  int index = 0;
+
+  // copy properties for lines in history
+  for (int line = startLine; line < startLine + linesInHistory; line++) 
+  {
+		//TODO Support for line properties other than wrapped lines
+	  if (hist->isWrappedLine(line))
+	  {
+	  	result[index] = (LineProperty)(result[index] | LINE_WRAPPED);
+	  }
+    index++;
+  }
+  
+  // copy properties for lines in screen buffer
+  const int firstScreenLine = startLine + linesInHistory - hist->getLines();
+  for (int line = firstScreenLine; line < firstScreenLine+linesInScreen; line++)
+	{
+    result[index]=lineProperties[line];
+  	index++;
+	}
+
+  return result;
+}
+
+/*!
+*/
+
+void Screen::reset(bool clearScreen)
+{
+    setMode(MODE_Wrap  ); saveMode(MODE_Wrap  );  // wrap at end of margin
+  resetMode(MODE_Origin); saveMode(MODE_Origin);  // position refere to [1,1]
+  resetMode(MODE_Insert); saveMode(MODE_Insert);  // overstroke
+    setMode(MODE_Cursor);                         // cursor visible
+  resetMode(MODE_Screen);                         // screen not inverse
+  resetMode(MODE_NewLine);
+
+  tmargin=0;
+  bmargin=lines-1;
+
+  setDefaultRendition();
+  saveCursor();
+
+  if ( clearScreen )
+    clear();
+}
+
+/*! Clear the entire screen and home the cursor.
+*/
+
+void Screen::clear()
+{
+  clearEntireScreen();
+  home();
+}
+
+void Screen::BackSpace()
+{
+  cuX = qMin(columns-1,cuX); // nowrap!
+  cuX = qMax(0,cuX-1);
+ // if (BS_CLEARS) image[loc(cuX,cuY)].character = ' ';
+
+  if (screenLines[cuY].size() < cuX+1)
+          screenLines[cuY].resize(cuX+1);
+
+  if (BS_CLEARS) screenLines[cuY][cuX].character = ' ';
+}
+
+void Screen::Tabulate(int n)
+{
+  // note that TAB is a format effector (does not write ' ');
+  if (n == 0) n = 1;
+  while((n > 0) && (cuX < columns-1))
+  {
+    cursorRight(1); while((cuX < columns-1) && !tabstops[cuX]) cursorRight(1);
+    n--;
+  }
+}
+
+void Screen::backTabulate(int n)
+{
+  // note that TAB is a format effector (does not write ' ');
+  if (n == 0) n = 1;
+  while((n > 0) && (cuX > 0))
+  {
+     cursorLeft(1); while((cuX > 0) && !tabstops[cuX]) cursorLeft(1);
+     n--;
+  }
+}
+
+void Screen::clearTabStops()
+{
+  for (int i = 0; i < columns; i++) tabstops[i] = false;
+}
+
+void Screen::changeTabStop(bool set)
+{
+  if (cuX >= columns) return;
+  tabstops[cuX] = set;
+}
+
+void Screen::initTabStops()
+{
+  delete[] tabstops;
+  tabstops = new bool[columns];
+
+  // Arrg! The 1st tabstop has to be one longer than the other.
+  // i.e. the kids start counting from 0 instead of 1.
+  // Other programs might behave correctly. Be aware.
+  for (int i = 0; i < columns; i++) tabstops[i] = (i%8 == 0 && i != 0);
+}
+
+/*!
+   This behaves either as IND (Screen::Index) or as NEL (Screen::NextLine)
+   depending on the NewLine Mode (LNM). This mode also
+   affects the key sequence returned for newline ([CR]LF).
+*/
+
+void Screen::NewLine()
+{
+  if (getMode(MODE_NewLine)) Return();
+  index();
+}
+
+/*! put `c' literally onto the screen at the current cursor position.
+
+    VT100 uses the convention to produce an automatic newline (am)
+    with the *first* character that would fall onto the next line (xenl).
+*/
+
+void Screen::checkSelection(int from, int to)
+{
+  if (sel_begin == -1) return;
+  int scr_TL = loc(0, hist->getLines());
+  //Clear entire selection if it overlaps region [from, to]
+  if ( (sel_BR > (from+scr_TL) )&&(sel_TL < (to+scr_TL)) )
+  {
+    clearSelection();
+  }
+}
+
+void Screen::ShowCharacter(unsigned short c)
+{
+  // Note that VT100 does wrapping BEFORE putting the character.
+  // This has impact on the assumption of valid cursor positions.
+  // We indicate the fact that a newline has to be triggered by
+  // putting the cursor one right to the last column of the screen.
+
+  int w = konsole_wcwidth(c);
+
+  if (w <= 0)
+     return;
+
+  if (cuX+w > columns) {
+    if (getMode(MODE_Wrap)) {
+      lineProperties[cuY] = (LineProperty)(lineProperties[cuY] | LINE_WRAPPED);
+      NextLine();
+    }
+    else
+      cuX = columns-w;
+  }
+
+  // ensure current line vector has enough elements
+  int size = screenLines[cuY].size();
+  if (size == 0 && cuY > 0)
+  {
+          screenLines[cuY].resize( qMax(screenLines[cuY-1].size() , cuX+w) );
+  }
+  else
+  {
+    if (size < cuX+w)
+    {
+          screenLines[cuY].resize(cuX+w);
+    }
+  }
+
+  if (getMode(MODE_Insert)) insertChars(w);
+
+  lastPos = loc(cuX,cuY);
+
+  // check if selection is still valid.
+  checkSelection(cuX,cuY);
+
+  Character& currentChar = screenLines[cuY][cuX];
+
+  currentChar.character = c;
+  currentChar.foregroundColor = ef_fg;
+  currentChar.backgroundColor = ef_bg;
+  currentChar.rendition = ef_re;
+
+  int i = 0;
+  int newCursorX = cuX + w--;
+  while(w)
+  {
+     i++;
+   
+     if ( screenLines[cuY].size() < cuX + i + 1 )
+         screenLines[cuY].resize(cuX+i+1);
+     
+     Character& ch = screenLines[cuY][cuX + i];
+     ch.character = 0;
+     ch.foregroundColor = ef_fg;
+     ch.backgroundColor = ef_bg;
+     ch.rendition = ef_re;
+
+     w--;
+  }
+  cuX = newCursorX;
+}
+
+void Screen::compose(const QString& /*compose*/)
+{
+   Q_ASSERT( 0 /*Not implemented yet*/ );
+
+/*  if (lastPos == -1)
+     return;
+     
+  QChar c(image[lastPos].character);
+  compose.prepend(c);
+  //compose.compose(); ### FIXME!
+  image[lastPos].character = compose[0].unicode();*/
+}
+
+int Screen::scrolledLines() const
+{
+        return _scrolledLines;
+}
+int Screen::droppedLines() const
+{
+    return _droppedLines;
+}
+void Screen::resetDroppedLines()
+{
+    _droppedLines = 0;
+}
+void Screen::resetScrolledLines()
+{
+    //kDebug() << "scrolled lines reset";
+
+    _scrolledLines = 0;
+}
+
+// Region commands -------------------------------------------------------------
+
+void Screen::scrollUp(int n)
+{
+   if (n == 0) n = 1; // Default
+   if (tmargin == 0) addHistLine(); // hist.history
+   scrollUp(tmargin, n);
+}
+
+/*! scroll up `n' lines within current region.
+    The `n' new lines are cleared.
+    \sa setRegion \sa scrollDown
+*/
+
+QRect Screen::lastScrolledRegion() const
+{
+    return _lastScrolledRegion;
+}
+
+void Screen::scrollUp(int from, int n)
+{
+  if (n <= 0 || from + n > bmargin) return;
+
+  _scrolledLines -= n;
+  _lastScrolledRegion = QRect(0,tmargin,columns-1,(bmargin-tmargin));
+
+  //FIXME: make sure `tmargin', `bmargin', `from', `n' is in bounds.
+  moveImage(loc(0,from),loc(0,from+n),loc(columns-1,bmargin));
+  clearImage(loc(0,bmargin-n+1),loc(columns-1,bmargin),' ');
+}
+
+void Screen::scrollDown(int n)
+{
+   if (n == 0) n = 1; // Default
+   scrollDown(tmargin, n);
+}
+
+/*! scroll down `n' lines within current region.
+    The `n' new lines are cleared.
+    \sa setRegion \sa scrollUp
+*/
+
+void Screen::scrollDown(int from, int n)
+{
+
+  //kDebug() << "Screen::scrollDown( from: " << from << " , n: " << n << ")";
+  
+  _scrolledLines += n;
+
+//FIXME: make sure `tmargin', `bmargin', `from', `n' is in bounds.
+  if (n <= 0) return;
+  if (from > bmargin) return;
+  if (from + n > bmargin) n = bmargin - from;
+  moveImage(loc(0,from+n),loc(0,from),loc(columns-1,bmargin-n));
+  clearImage(loc(0,from),loc(columns-1,from+n-1),' ');
+}
+
+void Screen::setCursorYX(int y, int x)
+{
+  setCursorY(y); setCursorX(x);
+}
+
+void Screen::setCursorX(int x)
+{
+  if (x == 0) x = 1; // Default
+  x -= 1; // Adjust
+  cuX = qMax(0,qMin(columns-1, x));
+}
+
+void Screen::setCursorY(int y)
+{
+  if (y == 0) y = 1; // Default
+  y -= 1; // Adjust
+  cuY = qMax(0,qMin(lines  -1, y + (getMode(MODE_Origin) ? tmargin : 0) ));
+}
+
+void Screen::home()
+{
+  cuX = 0;
+  cuY = 0;
+}
+
+void Screen::Return()
+{
+  cuX = 0;
+}
+
+int Screen::getCursorX() const
+{
+  return cuX;
+}
+
+int Screen::getCursorY() const
+{
+  return cuY;
+}
+
+// Erasing ---------------------------------------------------------------------
+
+/*! \section Erasing
+
+    This group of operations erase parts of the screen contents by filling
+    it with spaces colored due to the current rendition settings.
+
+    Althought the cursor position is involved in most of these operations,
+    it is never modified by them.
+*/
+
+/*! fill screen between (including) `loca' (start) and `loce' (end) with spaces.
+
+    This is an internal helper functions. The parameter types are internal
+    addresses of within the screen image and make use of the way how the
+    screen matrix is mapped to the image vector.
+*/
+
+void Screen::clearImage(int loca, int loce, char c)
+{ 
+  int scr_TL=loc(0,hist->getLines());
+  //FIXME: check positions
+
+  //Clear entire selection if it overlaps region to be moved...
+  if ( (sel_BR > (loca+scr_TL) )&&(sel_TL < (loce+scr_TL)) )
+  {
+    clearSelection();
+  }
+
+  int topLine = loca/columns;
+  int bottomLine = loce/columns;
+
+  Character clearCh(c,cu_fg,cu_bg,DEFAULT_RENDITION);
+  
+  //if the character being used to clear the area is the same as the
+  //default character, the affected lines can simply be shrunk.
+  bool isDefaultCh = (clearCh == Character());
+
+  for (int y=topLine;y<=bottomLine;y++)
+  {
+        lineProperties[y] = 0;
+
+        int endCol = ( y == bottomLine) ? loce%columns : columns-1;
+        int startCol = ( y == topLine ) ? loca%columns : 0;
+
+        QVector<Character>& line = screenLines[y];
+
+        if ( isDefaultCh && endCol == columns-1 )
+        {
+            line.resize(startCol);
+        }
+        else
+        {
+            if (line.size() < endCol + 1)
+                line.resize(endCol+1);
+
+            Character* data = line.data();
+            for (int i=startCol;i<=endCol;i++)
+                data[i]=clearCh;
+        }
+  }
+}
+
+/*! move image between (including) `sourceBegin' and `sourceEnd' to 'dest'.
+    
+    The 'dest', 'sourceBegin' and 'sourceEnd' parameters can be generated using
+    the loc(column,line) macro.
+
+NOTE:  moveImage() can only move whole lines.
+
+    This is an internal helper functions. The parameter types are internal
+    addresses of within the screen image and make use of the way how the
+    screen matrix is mapped to the image vector.
+*/
+
+void Screen::moveImage(int dest, int sourceBegin, int sourceEnd)
+{
+  //kDebug() << "moving image from (" << (sourceBegin/columns) 
+  //    << "," << (sourceEnd/columns) << ") to " <<
+  //    (dest/columns);
+
+  Q_ASSERT( sourceBegin <= sourceEnd );
+ 
+  int lines=(sourceEnd-sourceBegin)/columns;
+
+  //move screen image and line properties:
+  //the source and destination areas of the image may overlap, 
+  //so it matters that we do the copy in the right order - 
+  //forwards if dest < sourceBegin or backwards otherwise.
+  //(search the web for 'memmove implementation' for details)
+  if (dest < sourceBegin)
+  {
+    for (int i=0;i<=lines;i++)
+    {
+        screenLines[ (dest/columns)+i ] = screenLines[ (sourceBegin/columns)+i ];
+        lineProperties[(dest/columns)+i]=lineProperties[(sourceBegin/columns)+i];
+    }
+  }
+  else
+  {
+    for (int i=lines;i>=0;i--)
+    {
+        screenLines[ (dest/columns)+i ] = screenLines[ (sourceBegin/columns)+i ];
+        lineProperties[(dest/columns)+i]=lineProperties[(sourceBegin/columns)+i];
+    }
+  }
+
+  if (lastPos != -1)
+  {
+     int diff = dest - sourceBegin; // Scroll by this amount
+     lastPos += diff;
+     if ((lastPos < 0) || (lastPos >= (lines*columns)))
+        lastPos = -1;
+  }
+     
+  // Adjust selection to follow scroll.
+  if (sel_begin != -1)
+  {
+     bool beginIsTL = (sel_begin == sel_TL);
+     int diff = dest - sourceBegin; // Scroll by this amount
+     int scr_TL=loc(0,hist->getLines());
+     int srca = sourceBegin+scr_TL; // Translate index from screen to global
+     int srce = sourceEnd+scr_TL; // Translate index from screen to global
+     int desta = srca+diff;
+     int deste = srce+diff;
+
+     if ((sel_TL >= srca) && (sel_TL <= srce))
+        sel_TL += diff;
+     else if ((sel_TL >= desta) && (sel_TL <= deste))
+        sel_BR = -1; // Clear selection (see below)
+
+     if ((sel_BR >= srca) && (sel_BR <= srce))
+        sel_BR += diff;
+     else if ((sel_BR >= desta) && (sel_BR <= deste))
+        sel_BR = -1; // Clear selection (see below)
+
+     if (sel_BR < 0)
+     {
+        clearSelection();
+     }
+     else
+     {
+        if (sel_TL < 0)
+           sel_TL = 0;
+     }
+
+     if (beginIsTL)
+        sel_begin = sel_TL;
+     else
+        sel_begin = sel_BR;
+  }
+}
+
+void Screen::clearToEndOfScreen()
+{
+  clearImage(loc(cuX,cuY),loc(columns-1,lines-1),' ');
+}
+
+void Screen::clearToBeginOfScreen()
+{
+  clearImage(loc(0,0),loc(cuX,cuY),' ');
+}
+
+void Screen::clearEntireScreen()
+{
+  // Add entire screen to history
+  for (int i = 0; i < (lines-1); i++)
+  {
+    addHistLine(); scrollUp(0,1);
+  }
+
+  clearImage(loc(0,0),loc(columns-1,lines-1),' ');
+}
+
+/*! fill screen with 'E'
+    This is to aid screen alignment
+*/
+
+void Screen::helpAlign()
+{
+  clearImage(loc(0,0),loc(columns-1,lines-1),'E');
+}
+
+void Screen::clearToEndOfLine()
+{
+  clearImage(loc(cuX,cuY),loc(columns-1,cuY),' ');
+}
+
+void Screen::clearToBeginOfLine()
+{
+  clearImage(loc(0,cuY),loc(cuX,cuY),' ');
+}
+
+void Screen::clearEntireLine()
+{
+  clearImage(loc(0,cuY),loc(columns-1,cuY),' ');
+}
+
+void Screen::setRendition(int re)
+{
+  cu_re |= re;
+  effectiveRendition();
+}
+
+void Screen::resetRendition(int re)
+{
+  cu_re &= ~re;
+  effectiveRendition();
+}
+
+void Screen::setDefaultRendition()
+{
+  setForeColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR);
+  setBackColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR);
+  cu_re   = DEFAULT_RENDITION;
+  effectiveRendition();
+}
+
+void Screen::setForeColor(int space, int color)
+{
+  cu_fg = CharacterColor(space, color);
+
+  if ( cu_fg.isValid() ) 
+    effectiveRendition();
+  else 
+    setForeColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR);
+}
+
+void Screen::setBackColor(int space, int color)
+{
+  cu_bg = CharacterColor(space, color);
+
+  if ( cu_bg.isValid() ) 
+    effectiveRendition();
+  else
+    setBackColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR);
+}
+
+/* ------------------------------------------------------------------------- */
+/*                                                                           */
+/*                            Marking & Selection                            */
+/*                                                                           */
+/* ------------------------------------------------------------------------- */
+
+void Screen::clearSelection()
+{
+  sel_BR = -1;
+  sel_TL = -1;
+  sel_begin = -1;
+}
+
+void Screen::getSelectionStart(int& column , int& line)
+{
+    if ( sel_TL != -1 )
+    {
+        column = sel_TL % columns;
+        line = sel_TL / columns; 
+    }
+    else
+    {
+        column = cuX + getHistLines();
+        line = cuY + getHistLines();
+    }
+}
+void Screen::getSelectionEnd(int& column , int& line)
+{
+    if ( sel_BR != -1 )
+    {
+        column = sel_BR % columns;
+        line = sel_BR / columns;
+    }
+    else
+    {
+        column = cuX + getHistLines();
+        line = cuY + getHistLines();
+    } 
+}
+void Screen::setSelectionStart(/*const ScreenCursor& viewCursor ,*/ const int x, const int y, const bool mode)
+{
+//  kDebug(1211) << "setSelBeginXY(" << x << "," << y << ")";
+  sel_begin = loc(x,y); //+histCursor) ;
+
+  /* FIXME, HACK to correct for x too far to the right... */
+  if (x == columns) sel_begin--;
+
+  sel_BR = sel_begin;
+  sel_TL = sel_begin;
+  columnmode = mode;
+}
+
+void Screen::setSelectionEnd( const int x, const int y)
+{
+//  kDebug(1211) << "setSelExtentXY(" << x << "," << y << ")";
+  if (sel_begin == -1) return;
+  int l =  loc(x,y); // + histCursor);
+
+  if (l < sel_begin)
+  {
+    sel_TL = l;
+    sel_BR = sel_begin;
+  }
+  else
+  {
+    /* FIXME, HACK to correct for x too far to the right... */
+    if (x == columns) l--;
+
+    sel_TL = sel_begin;
+    sel_BR = l;
+  }
+}
+
+bool Screen::isSelected( const int x,const int y) const
+{
+  if (columnmode) {
+    int sel_Left,sel_Right;
+    if ( sel_TL % columns < sel_BR % columns ) {
+      sel_Left = sel_TL; sel_Right = sel_BR;
+    } else {
+      sel_Left = sel_BR; sel_Right = sel_TL;
+    }
+    return ( x >= sel_Left % columns ) && ( x <= sel_Right % columns ) &&
+           ( y >= sel_TL / columns ) && ( y <= sel_BR / columns );
+            //( y+histCursor >= sel_TL / columns ) && ( y+histCursor <= sel_BR / columns );
+  }
+  else {
+  //int pos = loc(x,y+histCursor);
+  int pos = loc(x,y);
+  return ( pos >= sel_TL && pos <= sel_BR );
+  }
+}
+
+QString Screen::selectedText(bool preserveLineBreaks)
+{
+  QString result;
+  QTextStream stream(&result, QIODevice::ReadWrite);
+  
+  PlainTextDecoder decoder;
+  decoder.begin(&stream);
+  writeSelectionToStream(&decoder , preserveLineBreaks);
+  decoder.end();
+  
+  return result;
+}
+
+bool Screen::isSelectionValid() const
+{
+    return ( sel_TL >= 0 && sel_BR >= 0 );
+}
+
+void Screen::writeSelectionToStream(TerminalCharacterDecoder* decoder , 
+                                    bool preserveLineBreaks)
+{
+    // do nothing if selection is invalid
+    if ( !isSelectionValid() )
+        return;
+
+	int top = sel_TL / columns;	
+	int left = sel_TL % columns;
+
+	int bottom = sel_BR / columns;
+	int right = sel_BR % columns;
+
+    Q_ASSERT( top >= 0 && left >= 0 && bottom >= 0 && right >= 0 );
+
+    //kDebug() << "sel_TL = " << sel_TL;
+    //kDebug() << "columns = " << columns;
+
+	for (int y=top;y<=bottom;y++)
+	{
+			int start = 0;
+			if ( y == top || columnmode ) start = left;
+		
+			int count = -1;
+			if ( y == bottom || columnmode ) count = right - start + 1;
+
+            const bool appendNewLine = ( y != bottom );
+			copyLineToStream( y,
+                              start,
+                              count,
+                              decoder, 
+                              appendNewLine,
+                              preserveLineBreaks );
+	}	
+}
+
+
+void Screen::copyLineToStream(int line , 
+                              int start, 
+                              int count,
+                              TerminalCharacterDecoder* decoder,
+                              bool appendNewLine,
+                              bool preserveLineBreaks)
+{
+		//buffer to hold characters for decoding
+		//the buffer is static to avoid initialising every 
+        //element on each call to copyLineToStream
+		//(which is unnecessary since all elements will be overwritten anyway)
+		static const int MAX_CHARS = 1024;
+		static Character characterBuffer[MAX_CHARS];
+		
+		assert( count < MAX_CHARS );
+
+        LineProperty currentLineProperties = 0;
+
+		//determine if the line is in the history buffer or the screen image
+		if (line < hist->getLines())
+		{
+            const int lineLength = hist->getLineLen(line);
+
+            // ensure that start position is before end of line
+            start = qMin(start,qMax(0,lineLength-1));
+
+			//retrieve line from history buffer
+			if (count == -1)
+            {
+					count = lineLength-start;
+            }
+			else
+            {
+					count = qMin(start+count,lineLength)-start;
+            }
+
+            // safety checks
+            assert( start >= 0 );
+            assert( count >= 0 );    
+            assert( (start+count) <= hist->getLineLen(line) );
+
+			hist->getCells(line,start,count,characterBuffer);
+
+            if ( hist->isWrappedLine(line) )
+                currentLineProperties |= LINE_WRAPPED;
+		}
+		else
+		{
+			if ( count == -1 )
+					count = columns - start;
+
+            assert( count >= 0 );
+
+            const int screenLine = line-hist->getLines();
+
+            Character* data = screenLines[screenLine].data();
+            int length = screenLines[screenLine].count();
+
+			//retrieve line from screen image
+			for (int i=start;i < qMin(start+count,length);i++)
+			{
+			    characterBuffer[i-start] = data[i];
+            }
+
+            // count cannot be any greater than length
+			count = qBound(0,count,length-start);
+
+            Q_ASSERT( screenLine < lineProperties.count() );
+            currentLineProperties |= lineProperties[screenLine]; 
+		}
+
+		//do not decode trailing whitespace characters
+		for (int i=count-1 ; i >= 0; i--)
+				if (QChar(characterBuffer[i].character).isSpace())
+						count--;
+				else
+						break;
+
+        // add new line character at end
+        const bool omitLineBreak = (currentLineProperties & LINE_WRAPPED) ||
+                                   !preserveLineBreaks;
+
+        if ( !omitLineBreak && appendNewLine && (count+1 < MAX_CHARS) )
+        {
+            characterBuffer[count] = '\n';
+            count++;
+        }
+
+		//decode line and write to text stream	
+		decoder->decodeLine( (Character*) characterBuffer , 
+                             count, currentLineProperties );
+}
+
+// Method below has been removed because of its reliance on 'histCursor'
+// and I want to restrict the methods which have knowledge of the scroll position
+// to just those which deal with selection and supplying final screen images.
+//
+/*void Screen::writeToStream(QTextStream* stream , TerminalCharacterDecoder* decoder) {
+  sel_begin = 0;
+  sel_BR = sel_begin;
+  sel_TL = sel_begin;
+  setSelectionEnd(columns-1,lines-1+hist->getLines()-histCursor);
+  
+  writeSelectionToStream(stream,decoder);
+  
+  clearSelection();
+}*/
+
+void Screen::writeToStream(TerminalCharacterDecoder* decoder, int from, int to)
+{
+	sel_begin = loc(0,from);
+	sel_TL = sel_begin;
+	sel_BR = loc(columns-1,to);
+	writeSelectionToStream(decoder);
+	clearSelection();
+}
+
+QString Screen::getHistoryLine(int no)
+{
+  sel_begin = loc(0,no);
+  sel_TL = sel_begin;
+  sel_BR = loc(columns-1,no);
+  return selectedText(false);
+}
+
+void Screen::addHistLine()
+{
+  // add line to history buffer
+  // we have to take care about scrolling, too...
+
+  if (hasScroll())
+  {
+    int oldHistLines = hist->getLines();
+
+    hist->addCellsVector(screenLines[0]);
+    hist->addLine( lineProperties[0] & LINE_WRAPPED );
+
+    int newHistLines = hist->getLines();
+
+    bool beginIsTL = (sel_begin == sel_TL);
+
+    // If the history is full, increment the count
+    // of dropped lines
+    if ( newHistLines == oldHistLines )
+        _droppedLines++;
+
+    // Adjust selection for the new point of reference
+    if (newHistLines > oldHistLines)
+    {
+       if (sel_begin != -1)
+       {
+          sel_TL += columns;
+          sel_BR += columns;
+       }
+    }
+
+    if (sel_begin != -1)
+    {
+       // Scroll selection in history up
+       int top_BR = loc(0, 1+newHistLines);
+
+       if (sel_TL < top_BR)
+          sel_TL -= columns;
+
+       if (sel_BR < top_BR)
+          sel_BR -= columns;
+
+       if (sel_BR < 0)
+       {
+          clearSelection();
+       }
+       else
+       {
+          if (sel_TL < 0)
+             sel_TL = 0;
+       }
+
+       if (beginIsTL)
+          sel_begin = sel_TL;
+       else
+          sel_begin = sel_BR;
+    }
+  }
+
+}
+
+int Screen::getHistLines()
+{
+  return hist->getLines();
+}
+
+void Screen::setScroll(const HistoryType& t , bool copyPreviousScroll)
+{
+  clearSelection();
+
+  if ( copyPreviousScroll )
+    hist = t.scroll(hist);
+  else
+  {
+      HistoryScroll* oldScroll = hist;
+      hist = t.scroll(0);
+      delete oldScroll;
+  }
+}
+
+bool Screen::hasScroll()
+{
+  return hist->hasScroll();
+}
+
+const HistoryType& Screen::getScroll()
+{
+  return hist->getType();
+}
+
+void Screen::setLineProperty(LineProperty property , bool enable)
+{
+	if ( enable )
+	{
+		lineProperties[cuY] = (LineProperty)(lineProperties[cuY] | property);
+	}
+	else
+	{
+		lineProperties[cuY] = (LineProperty)(lineProperties[cuY] & ~property);
+	}
+}
+void Screen::fillWithDefaultChar(Character* dest, int count)
+{
+	for (int i=0;i<count;i++)
+		dest[i] = defaultChar;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/Screen.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,655 @@
+/*
+    This file is part of Konsole, KDE's terminal.
+
+    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
+    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+#ifndef SCREEN_H
+#define SCREEN_H
+
+// Qt
+#include <QtCore/QRect>
+#include <QtCore/QTextStream>
+#include <QtCore/QVarLengthArray>
+
+// Konsole
+#include "unix/Character.h"
+#include "unix/History.h"
+
+#define MODE_Origin    0
+#define MODE_Wrap      1
+#define MODE_Insert    2
+#define MODE_Screen    3
+#define MODE_Cursor    4
+#define MODE_NewLine   5
+#define MODES_SCREEN   6
+
+struct ScreenParm
+{
+  int mode[MODES_SCREEN];
+};
+
+class TerminalCharacterDecoder;
+
+/**
+    \brief An image of characters with associated attributes.
+
+    The terminal emulation ( Emulation ) receives a serial stream of
+    characters from the program currently running in the terminal.
+    From this stream it creates an image of characters which is ultimately
+    rendered by the display widget ( TerminalDisplay ).  Some types of emulation
+    may have more than one screen image. 
+
+    getImage() is used to retrieve the currently visible image
+    which is then used by the display widget to draw the output from the
+    terminal. 
+
+    The number of lines of output history which are kept in addition to the current
+    screen image depends on the history scroll being used to store the output.  
+    The scroll is specified using setScroll()
+    The output history can be retrieved using writeToStream()
+
+    The screen image has a selection associated with it, specified using 
+    setSelectionStart() and setSelectionEnd().  The selected text can be retrieved
+    using selectedText().  When getImage() is used to retrieve the the visible image,
+    characters which are part of the selection have their colours inverted.   
+*/
+class Screen
+{
+public:
+    /** Construct a new screen image of size @p lines by @p columns. */
+    Screen(int lines, int columns);
+    ~Screen();
+
+    // VT100/2 Operations 
+    // Cursor Movement
+    
+    /** Move the cursor up by @p n lines. */
+    void cursorUp    (int n);
+    /** Move the cursor down by @p n lines. */
+    void cursorDown  (int n);
+    /** Move the cursor to the left by @p n columns. */
+    void cursorLeft  (int n);
+    /** Move the cursor to the right by @p n columns. */
+    void cursorRight (int n);
+    /** Position the cursor on line @p y. */
+    void setCursorY  (int y);
+    /** Position the cursor at column @p x. */
+    void setCursorX  (int x);
+    /** Position the cursor at line @p y, column @p x. */
+    void setCursorYX (int y, int x);
+    /**
+     * Sets the margins for scrolling the screen.
+     *
+     * @param topLine The top line of the new scrolling margin. 
+     * @param bottomLine The bottom line of the new scrolling margin. 
+     */
+    void setMargins  (int topLine , int bottomLine);
+    /** Returns the top line of the scrolling region. */ 
+    int topMargin() const;
+    /** Returns the bottom line of the scrolling region. */
+    int bottomMargin() const;
+
+    /** 
+     * Resets the scrolling margins back to the top and bottom lines
+     * of the screen.
+     */
+    void setDefaultMargins();
+    
+    /** 
+     * Moves the cursor down one line, if the MODE_NewLine mode 
+     * flag is enabled then the cursor is returned to the leftmost
+     * column first.
+     *
+     * Equivalent to NextLine() if the MODE_NewLine flag is set
+     * or index() otherwise. 
+     */
+    void NewLine     ();
+    /**
+     * Moves the cursor down one line and positions it at the beginning
+     * of the line.
+     */
+    void NextLine    ();
+
+    /** 
+     * Move the cursor down one line.  If the cursor is on the bottom
+     * line of the scrolling region (as returned by bottomMargin()) the
+     * scrolling region is scrolled up by one line instead.
+     */
+    void index       ();
+    /**
+     * Move the cursor up one line.  If the cursor is on the top line
+     * of the scrolling region (as returned by topMargin()) the scrolling
+     * region is scrolled down by one line instead.
+     */
+    void reverseIndex();
+    
+    /** 
+     * Scroll the scrolling region of the screen up by @p n lines. 
+     * The scrolling region is initially the whole screen, but can be changed 
+     * using setMargins()
+     */ 
+    void scrollUp(int n);
+    /**
+     * Scroll the scrolling region of the screen down by @p n lines.
+     * The scrolling region is initially the whole screen, but can be changed
+     * using setMargins()
+     */
+    void scrollDown(int n);
+    
+    /** 
+     * Moves the cursor to the beginning of the current line. 
+     * Equivalent to setCursorX(0)
+     */
+    void Return      ();
+    /** 
+     * Moves the cursor one column to the left and erases the character
+     * at the new cursor position.
+     */
+    void BackSpace   ();
+    /** 
+     * Moves the cursor @p n tab-stops to the right.
+     */
+    void Tabulate    (int n = 1);
+    /** 
+     * Moves the cursor @p n tab-stops to the left. 
+     */
+    void backTabulate(int n);
+    
+    // Editing
+    
+    /** 
+     * Erase @p n characters beginning from the current cursor position. 
+     * This is equivalent to over-writing @p n characters starting with the current
+     * cursor position with spaces.
+     * If @p n is 0 then one character is erased. 
+     */
+    void eraseChars  (int n);
+    /** 
+     * Delete @p n characters beginning from the current cursor position. 
+     * If @p n is 0 then one character is deleted. 
+     */
+    void deleteChars (int n);
+    /**
+     * Insert @p n blank characters beginning from the current cursor position.
+     * The position of the cursor is not altered.  
+     * If @p n is 0 then one character is inserted.
+     */
+    void insertChars (int n);
+    /** 
+     * Removes @p n lines beginning from the current cursor position.
+     * The position of the cursor is not altered.
+     * If @p n is 0 then one line is removed.
+     */
+    void deleteLines (int n);
+    /**
+     * Inserts @p lines beginning from the current cursor position.
+     * The position of the cursor is not altered.
+     * If @p n is 0 then one line is inserted.
+     */
+    void insertLines (int n);
+    /** Clears all the tab stops. */
+    void clearTabStops();
+    /**  Sets or removes a tab stop at the cursor's current column. */ 
+    void changeTabStop(bool set);
+   
+    /** Resets (clears) the specified screen @p mode. */
+    void resetMode   (int mode);
+    /** Sets (enables) the specified screen @p mode. */
+    void setMode     (int mode);
+    /** 
+     * Saves the state of the specified screen @p mode.  It can be restored
+     * using restoreMode()
+     */
+    void saveMode    (int mode);
+    /** Restores the state of a screen @p mode saved by calling saveMode() */
+    void restoreMode (int mode);
+    /** Returns whether the specified screen @p mode is enabled or not .*/
+    bool getMode     (int mode) const;
+   
+    /** 
+     * Saves the current position and appearence (text color and style) of the cursor. 
+     * It can be restored by calling restoreCursor() 
+     */ 
+    void saveCursor  ();
+    /** Restores the position and appearence of the cursor.  See saveCursor() */
+    void restoreCursor();
+   
+    /** Clear the whole screen, moving the current screen contents into the history first. */ 
+    void clearEntireScreen();
+    /** 
+     * Clear the area of the screen from the current cursor position to the end of 
+     * the screen.
+     */
+    void clearToEndOfScreen();
+    /**
+     * Clear the area of the screen from the current cursor position to the start
+     * of the screen.
+     */
+    void clearToBeginOfScreen();
+    /** Clears the whole of the line on which the cursor is currently positioned. */
+    void clearEntireLine();
+    /** Clears from the current cursor position to the end of the line. */
+    void clearToEndOfLine();
+    /** Clears from the current cursor position to the beginning of the line. */
+    void clearToBeginOfLine();
+    
+    /** Fills the entire screen with the letter 'E' */
+    void helpAlign   ();
+       
+    /** 
+     * Enables the given @p rendition flag.  Rendition flags control the appearence 
+     * of characters on the screen.
+     *
+     * @see Character::rendition
+     */  
+    void setRendition  (int rendition);
+    /**
+     * Disables the given @p rendition flag.  Rendition flags control the appearence
+     * of characters on the screen.
+     *
+     * @see Character::rendition
+     */
+    void resetRendition(int rendition);
+    
+    /** 
+     * Sets the cursor's foreground color.
+     * @param space The color space used by the @p color argument
+     * @param color The new foreground color.  The meaning of this depends on
+     * the color @p space used.
+     *
+     * @see CharacterColor
+     */
+    void setForeColor  (int space, int color);
+    /**
+     * Sets the cursor's background color.
+     * @param space The color space used by the @p color argumnet.
+     * @param color The new background color.  The meaning of this depends on
+     * the color @p space used.
+     *
+     * @see CharacterColor
+     */
+    void setBackColor  (int space, int color);
+    /** 
+     * Resets the cursor's color back to the default and sets the 
+     * character's rendition flags back to the default settings.
+     */
+    void setDefaultRendition();
+    
+    /** Returns the column which the cursor is positioned at. */
+    int  getCursorX() const;
+    /** Returns the line which the cursor is positioned on. */
+    int  getCursorY() const;
+   
+	/** TODO Document me */ 
+	void clear();
+    /** 
+     * Sets the position of the cursor to the 'home' position at the top-left
+     * corner of the screen (0,0) 
+     */
+    void home();
+    /**
+     * Resets the state of the screen.  This resets the various screen modes
+     * back to their default states.  The cursor style and colors are reset
+     * (as if setDefaultRendition() had been called)
+     *
+     * <ul>
+     * <li>Line wrapping is enabled.</li>
+     * <li>Origin mode is disabled.</li>
+     * <li>Insert mode is disabled.</li>
+     * <li>Cursor mode is enabled.  TODO Document me</li>
+     * <li>Screen mode is disabled. TODO Document me</li>
+     * <li>New line mode is disabled.  TODO Document me</li>
+     * </ul>
+     *
+     * If @p clearScreen is true then the screen contents are erased entirely, 
+     * otherwise they are unaltered.
+     */
+    void reset(bool clearScreen = true);
+   
+    /** 
+     * Displays a new character at the current cursor position. 
+     * 
+     * If the cursor is currently positioned at the right-edge of the screen and
+     * line wrapping is enabled then the character is added at the start of a new 
+     * line below the current one.
+     *
+     * If the MODE_Insert screen mode is currently enabled then the character 
+     * is inserted at the current cursor position, otherwise it will replace the 
+     * character already at the current cursor position.  
+     */ 
+    void ShowCharacter(unsigned short c);
+    
+    // Do composition with last shown character FIXME: Not implemented yet for KDE 4
+    void compose(const QString& compose);
+    
+    /** 
+     * Resizes the image to a new fixed size of @p new_lines by @p new_columns.  
+     * In the case that @p new_columns is smaller than the current number of columns,
+     * existing lines are not truncated.  This prevents characters from being lost
+     * if the terminal display is resized smaller and then larger again.
+     *
+     * (note that in versions of Konsole prior to KDE 4, existing lines were
+     *  truncated when making the screen image smaller)
+     */
+    void resizeImage(int new_lines, int new_columns);
+    
+    /**
+     * Returns the current screen image.  
+     * The result is an array of Characters of size [getLines()][getColumns()] which
+     * must be freed by the caller after use.
+     *
+     * @param dest Buffer to copy the characters into
+     * @param size Size of @p dest in Characters
+     * @param startLine Index of first line to copy
+     * @param endLine Index of last line to copy
+     */
+    void getImage( Character* dest , int size , int startLine , int endLine ) const;
+
+    /** 
+     * Returns the additional attributes associated with lines in the image.
+     * The most important attribute is LINE_WRAPPED which specifies that the 
+     * line is wrapped,
+     * other attributes control the size of characters in the line.
+     */
+    QVector<LineProperty> getLineProperties( int startLine , int endLine ) const;
+	
+
+    /** Return the number of lines. */
+    int  getLines()   { return lines; }
+    /** Return the number of columns. */
+    int  getColumns() { return columns; }
+    /** Return the number of lines in the history buffer. */
+    int  getHistLines ();
+    /** 
+     * Sets the type of storage used to keep lines in the history. 
+     * If @p copyPreviousScroll is true then the contents of the previous 
+     * history buffer are copied into the new scroll.
+     */
+    void setScroll(const HistoryType& , bool copyPreviousScroll = true);
+    /** Returns the type of storage used to keep lines in the history. */
+    const HistoryType& getScroll();
+    /** 
+     * Returns true if this screen keeps lines that are scrolled off the screen
+     * in a history buffer.
+     */
+    bool hasScroll();
+
+    /** 
+     * Sets the start of the selection.
+     *
+     * @param column The column index of the first character in the selection.
+     * @param line The line index of the first character in the selection.
+     * @param columnmode True if the selection is in column mode.
+     */
+    void setSelectionStart(const int column, const int line, const bool columnmode);
+    
+    /**
+     * Sets the end of the current selection.
+     *
+     * @param column The column index of the last character in the selection.
+     * @param line The line index of the last character in the selection. 
+     */ 
+    void setSelectionEnd(const int column, const int line);
+   
+    /**
+     * Retrieves the start of the selection or the cursor position if there
+     * is no selection.
+     */
+    void getSelectionStart(int& column , int& line);
+    
+    /**
+     * Retrieves the end of the selection or the cursor position if there
+     * is no selection.
+     */
+    void getSelectionEnd(int& column , int& line);
+
+    /** Clears the current selection */
+    void clearSelection();
+
+    void setBusySelecting(bool busy) { sel_busy = busy; }
+
+    /** 
+ 	 * 	Returns true if the character at (@p column, @p line) is part of the
+ 	 *  current selection. 
+ 	 */ 
+    bool isSelected(const int column,const int line) const;
+
+    /** 
+     * Convenience method.  Returns the currently selected text. 
+     * @param preserveLineBreaks Specifies whether new line characters should 
+     * be inserted into the returned text at the end of each terminal line.
+     */
+    QString selectedText(bool preserveLineBreaks);
+	    
+	/**
+	 * Copies part of the output to a stream.
+	 *
+	 * @param decoder A decoder which coverts terminal characters into text
+	 * @param from The first line in the history to retrieve
+	 * @param to The last line in the history to retrieve
+	 */
+	void writeToStream(TerminalCharacterDecoder* decoder, int from, int to);
+
+    /** 
+     * Sets the selection to line @p no in the history and returns
+     * the text of that line from the history buffer.
+     */
+    QString getHistoryLine(int no);
+
+	/**
+	 * Copies the selected characters, set using @see setSelBeginXY and @see setSelExtentXY
+	 * into a stream.
+	 *
+	 * @param decoder A decoder which converts terminal characters into text.  
+	 * PlainTextDecoder is the most commonly used decoder which coverts characters 
+	 * into plain text with no formatting.
+     * @param preserveLineBreaks Specifies whether new line characters should 
+     * be inserted into the returned text at the end of each terminal line. 
+	 */
+	void writeSelectionToStream(TerminalCharacterDecoder* decoder , bool
+                                preserveLineBreaks = true);
+
+    /** TODO Document me */
+    void checkSelection(int from, int to);
+
+	/** 
+	 * Sets or clears an attribute of the current line.
+	 * 
+	 * @param property The attribute to set or clear
+	 * Possible properties are:
+	 * LINE_WRAPPED:	 Specifies that the line is wrapped.
+	 * LINE_DOUBLEWIDTH: Specifies that the characters in the current line should be double the normal width.
+	 * LINE_DOUBLEHEIGHT:Specifies that the characters in the current line should be double the normal height.
+     *                   Double-height lines are formed of two lines containing the same characters,
+     *                   with both having the LINE_DOUBLEHEIGHT attribute.  This allows other parts of the 
+     *                   code to work on the assumption that all lines are the same height.
+	 *
+	 * @param enable true to apply the attribute to the current line or false to remove it
+	 */
+	void setLineProperty(LineProperty property , bool enable);
+
+
+    /** 
+     * Returns the number of lines that the image has been scrolled up or down by,
+     * since the last call to resetScrolledLines().
+     *
+     * a positive return value indicates that the image has been scrolled up,
+     * a negative return value indicates that the image has been scrolled down. 
+     */
+    int scrolledLines() const;
+
+    /**
+     * Returns the region of the image which was last scrolled.
+     *
+     * This is the area of the image from the top margin to the 
+     * bottom margin when the last scroll occurred.
+     */
+    QRect lastScrolledRegion() const;
+
+    /** 
+     * Resets the count of the number of lines that the image has been scrolled up or down by,
+     * see scrolledLines()
+     */
+    void resetScrolledLines();
+
+    /**
+     * Returns the number of lines of output which have been
+     * dropped from the history since the last call
+     * to resetDroppedLines()
+     *
+     * If the history is not unlimited then it will drop
+     * the oldest lines of output if new lines are added when
+     * it is full.  
+     */
+    int droppedLines() const;
+
+    /**
+     * Resets the count of the number of lines dropped from
+     * the history.
+     */
+    void resetDroppedLines();
+
+	/** 
+ 	 * Fills the buffer @p dest with @p count instances of the default (ie. blank)
+ 	 * Character style.
+ 	 */
+	static void fillWithDefaultChar(Character* dest, int count);
+
+private: 
+
+	//copies a line of text from the screen or history into a stream using a 
+	//specified character decoder
+	//line - the line number to copy, from 0 (the earliest line in the history) up to 
+	//		 hist->getLines() + lines - 1
+	//start - the first column on the line to copy
+	//count - the number of characters on the line to copy
+	//decoder - a decoder which coverts terminal characters (an Character array) into text
+    //appendNewLine - if true a new line character (\n) is appended to the end of the line
+	void copyLineToStream(int line, 
+                          int start, 
+                          int count, 
+                          TerminalCharacterDecoder* decoder,
+                          bool appendNewLine,
+                          bool preserveLineBreaks);
+	
+    //fills a section of the screen image with the character 'c'
+    //the parameters are specified as offsets from the start of the screen image.
+    //the loc(x,y) macro can be used to generate these values from a column,line pair.
+    void clearImage(int loca, int loce, char c);
+
+    //move screen image between 'sourceBegin' and 'sourceEnd' to 'dest'.
+    //the parameters are specified as offsets from the start of the screen image.
+    //the loc(x,y) macro can be used to generate these values from a column,line pair.
+    void moveImage(int dest, int sourceBegin, int sourceEnd);
+    
+    void scrollUp(int from, int i);
+    void scrollDown(int from, int i);
+
+    void addHistLine();
+
+    void initTabStops();
+
+    void effectiveRendition();
+    void reverseRendition(Character& p) const;
+
+    bool isSelectionValid() const;
+
+	// copies 'count' lines from the screen buffer into 'dest',
+	// starting from 'startLine', where 0 is the first line in the screen buffer
+	void copyFromScreen(Character* dest, int startLine, int count) const;
+	// copies 'count' lines from the history buffer into 'dest',
+	// starting from 'startLine', where 0 is the first line in the history
+	void copyFromHistory(Character* dest, int startLine, int count) const;
+
+
+    // screen image ----------------
+    int lines;
+    int columns;
+
+    typedef QVector<Character> ImageLine;      // [0..columns]
+    ImageLine*          screenLines;    // [lines]
+
+    int _scrolledLines;
+    QRect _lastScrolledRegion;
+
+    int _droppedLines;
+
+    QVarLengthArray<LineProperty,64> lineProperties;    
+	
+    // history buffer ---------------
+    HistoryScroll *hist;
+    
+    // cursor location
+    int cuX;
+    int cuY;
+
+    // cursor color and rendition info
+    CharacterColor cu_fg;      // foreground
+    CharacterColor cu_bg;      // background
+    quint8 cu_re;      // rendition
+
+    // margins ----------------
+    int tmargin;      // top margin
+    int bmargin;      // bottom margin
+
+    // states ----------------
+    ScreenParm currParm;
+
+    // ----------------------------
+
+    bool* tabstops;
+
+    // selection -------------------
+    int sel_begin; // The first location selected.
+    int sel_TL;    // TopLeft Location.
+    int sel_BR;    // Bottom Right Location.
+    bool sel_busy; // Busy making a selection.
+    bool columnmode;  // Column selection mode
+
+    // effective colors and rendition ------------
+    CharacterColor ef_fg;      // These are derived from
+    CharacterColor ef_bg;      // the cu_* variables above
+    quint8 ef_re;      // to speed up operation
+
+    //
+    // save cursor, rendition & states ------------
+    // 
+
+    // cursor location
+    int sa_cuX;
+    int sa_cuY;
+
+    // rendition info
+    quint8 sa_cu_re;
+    CharacterColor sa_cu_fg;
+    CharacterColor sa_cu_bg;
+    
+    // last position where we added a character
+    int lastPos;
+
+    // modes
+    ScreenParm saveParm;
+
+    static Character defaultChar;
+};
+
+#endif // SCREEN_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/ScreenWindow.cpp	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,294 @@
+/*
+    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+// Own
+#include "unix/ScreenWindow.h"
+
+// Qt
+#include <QtCore>
+
+// Konsole
+#include "unix/Screen.h"
+
+ScreenWindow::ScreenWindow(QObject* parent)
+    : QObject(parent)
+	, _windowBuffer(0)
+	, _windowBufferSize(0)
+	, _bufferNeedsUpdate(true)
+	, _windowLines(1)
+    , _currentLine(0)
+    , _trackOutput(true)
+    , _scrollCount(0)
+{
+}
+
+ScreenWindow::~ScreenWindow()
+{
+	delete[] _windowBuffer;
+}
+void ScreenWindow::setScreen(Screen* screen)
+{
+    Q_ASSERT( screen );
+
+    _screen = screen;
+}
+
+Screen* ScreenWindow::screen() const
+{
+    return _screen;
+}
+
+Character* ScreenWindow::getImage()
+{
+	// reallocate internal buffer if the window size has changed
+	int size = windowLines() * windowColumns();
+	if (_windowBuffer == 0 || _windowBufferSize != size) 
+	{
+		delete[] _windowBuffer;
+		_windowBufferSize = size;
+		_windowBuffer = new Character[size];
+		_bufferNeedsUpdate = true;
+	}
+
+	 if (!_bufferNeedsUpdate)
+		return _windowBuffer;
+ 
+	_screen->getImage(_windowBuffer,size,
+					  currentLine(),endWindowLine());
+
+	// this window may look beyond the end of the screen, in which 
+	// case there will be an unused area which needs to be filled
+	// with blank characters
+	fillUnusedArea();
+
+	_bufferNeedsUpdate = false;
+	return _windowBuffer;
+}
+
+void ScreenWindow::fillUnusedArea()
+{
+	int screenEndLine = _screen->getHistLines() + _screen->getLines() - 1;
+	int windowEndLine = currentLine() + windowLines() - 1;
+
+	int unusedLines = windowEndLine - screenEndLine;
+	int charsToFill = unusedLines * windowColumns();
+
+	Screen::fillWithDefaultChar(_windowBuffer + _windowBufferSize - charsToFill,charsToFill); 
+}
+
+// return the index of the line at the end of this window, or if this window 
+// goes beyond the end of the screen, the index of the line at the end
+// of the screen.
+//
+// when passing a line number to a Screen method, the line number should
+// never be more than endWindowLine()
+//
+int ScreenWindow::endWindowLine() const
+{
+	return qMin(currentLine() + windowLines() - 1,
+				lineCount() - 1);
+}
+QVector<LineProperty> ScreenWindow::getLineProperties()
+{
+    QVector<LineProperty> result = _screen->getLineProperties(currentLine(),endWindowLine());
+	
+	if (result.count() != windowLines())
+		result.resize(windowLines());
+
+	return result;
+}
+
+QString ScreenWindow::selectedText( bool preserveLineBreaks ) const
+{
+    return _screen->selectedText( preserveLineBreaks );
+}
+
+void ScreenWindow::getSelectionStart( int& column , int& line )
+{
+    _screen->getSelectionStart(column,line);
+    line -= currentLine();
+}
+void ScreenWindow::getSelectionEnd( int& column , int& line )
+{
+    _screen->getSelectionEnd(column,line);
+    line -= currentLine();
+}
+void ScreenWindow::setSelectionStart( int column , int line , bool columnMode )
+{
+    _screen->setSelectionStart( column , qMin(line + currentLine(),endWindowLine())  , columnMode);
+	
+	_bufferNeedsUpdate = true;
+    emit selectionChanged();
+}
+
+void ScreenWindow::setSelectionEnd( int column , int line )
+{
+    _screen->setSelectionEnd( column , qMin(line + currentLine(),endWindowLine()) );
+
+	_bufferNeedsUpdate = true;
+    emit selectionChanged();
+}
+
+bool ScreenWindow::isSelected( int column , int line )
+{
+    return _screen->isSelected( column , qMin(line + currentLine(),endWindowLine()) );
+}
+
+void ScreenWindow::clearSelection()
+{
+    _screen->clearSelection();
+
+    emit selectionChanged();
+}
+
+void ScreenWindow::setWindowLines(int lines)
+{
+	Q_ASSERT(lines > 0);
+	_windowLines = lines;
+}
+int ScreenWindow::windowLines() const
+{
+	return _windowLines;		
+}
+
+int ScreenWindow::windowColumns() const
+{
+    return _screen->getColumns();
+}
+
+int ScreenWindow::lineCount() const
+{
+    return _screen->getHistLines() + _screen->getLines();
+}
+
+int ScreenWindow::columnCount() const
+{
+    return _screen->getColumns();
+}
+
+QPoint ScreenWindow::cursorPosition() const
+{
+    QPoint position;
+    
+    position.setX( _screen->getCursorX() );
+    position.setY( _screen->getCursorY() );
+
+    return position; 
+}
+
+int ScreenWindow::currentLine() const
+{
+    return qBound(0,_currentLine,lineCount()-windowLines());
+}
+
+void ScreenWindow::scrollBy( RelativeScrollMode mode , int amount )
+{
+    if ( mode == ScrollLines )
+    {
+        scrollTo( currentLine() + amount );
+    }
+    else if ( mode == ScrollPages )
+    {
+        scrollTo( currentLine() + amount * ( windowLines() / 2 ) ); 
+    }
+}
+
+bool ScreenWindow::atEndOfOutput() const
+{
+    return currentLine() == (lineCount()-windowLines());
+}
+
+void ScreenWindow::scrollTo( int line )
+{
+	int maxCurrentLineNumber = lineCount() - windowLines();
+	line = qBound(0,line,maxCurrentLineNumber);
+
+    const int delta = line - _currentLine;
+    _currentLine = line;
+
+    // keep track of number of lines scrolled by,
+    // this can be reset by calling resetScrollCount()
+    _scrollCount += delta;
+
+    _bufferNeedsUpdate = true;
+
+    emit scrolled(_currentLine);
+}
+
+void ScreenWindow::setTrackOutput(bool trackOutput)
+{
+    _trackOutput = trackOutput;
+}
+
+bool ScreenWindow::trackOutput() const
+{
+    return _trackOutput;
+}
+
+int ScreenWindow::scrollCount() const
+{
+    return _scrollCount;
+}
+
+void ScreenWindow::resetScrollCount() 
+{
+    _scrollCount = 0;
+}
+
+QRect ScreenWindow::scrollRegion() const
+{
+	bool equalToScreenSize = windowLines() == _screen->getLines();
+
+	if ( atEndOfOutput() && equalToScreenSize )
+    	return _screen->lastScrolledRegion();
+	else
+		return QRect(0,0,windowColumns(),windowLines());
+}
+
+void ScreenWindow::notifyOutputChanged()
+{
+    // move window to the bottom of the screen and update scroll count
+    // if this window is currently tracking the bottom of the screen
+    if ( _trackOutput )
+    { 
+        _scrollCount -= _screen->scrolledLines();
+        _currentLine = qMax(0,_screen->getHistLines() - (windowLines()-_screen->getLines()));
+    }
+    else
+    {
+        // if the history is not unlimited then it may 
+        // have run out of space and dropped the oldest
+        // lines of output - in this case the screen
+        // window's current line number will need to 
+        // be adjusted - otherwise the output will scroll
+        _currentLine = qMax(0,_currentLine - 
+                              _screen->droppedLines());
+
+        // ensure that the screen window's current position does
+        // not go beyond the bottom of the screen
+        _currentLine = qMin( _currentLine , _screen->getHistLines() );
+    }
+
+	_bufferNeedsUpdate = true;
+
+    emit outputChanged(); 
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/ScreenWindow.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,252 @@
+/*
+    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+#ifndef SCREENWINDOW_H
+#define SCREENWINDOW_H
+
+// Qt
+#include <QtCore/QObject>
+#include <QtCore/QPoint>
+#include <QtCore/QRect>
+
+// Konsole
+#include "unix/Character.h"
+
+class Screen;
+
+/**
+ * Provides a window onto a section of a terminal screen.
+ * This window can then be rendered by a terminal display widget ( TerminalDisplay ).
+ *
+ * To use the screen window, create a new ScreenWindow() instance and associated it with 
+ * a terminal screen using setScreen().
+ * Use the scrollTo() method to scroll the window up and down on the screen.
+ * Call the getImage() method to retrieve the character image which is currently visible in the window.
+ *
+ * setTrackOutput() controls whether the window moves to the bottom of the associated screen when new
+ * lines are added to it.
+ *
+ * Whenever the output from the underlying screen is changed, the notifyOutputChanged() slot should
+ * be called.  This in turn will update the window's position and emit the outputChanged() signal
+ * if necessary.
+ */
+class ScreenWindow : public QObject
+{
+Q_OBJECT
+
+public:
+    /** 
+     * Constructs a new screen window with the given parent.
+     * A screen must be specified by calling setScreen() before calling getImage() or getLineProperties().
+     *
+     * You should not call this constructor directly, instead use the Emulation::createWindow() method
+     * to create a window on the emulation which you wish to view.  This allows the emulation
+     * to notify the window when the associated screen has changed and synchronize selection updates
+     * between all views on a session.
+     */
+    ScreenWindow(QObject* parent = 0);
+	virtual ~ScreenWindow();
+
+    /** Sets the screen which this window looks onto */
+    void setScreen(Screen* screen);
+    /** Returns the screen which this window looks onto */
+    Screen* screen() const;
+
+    /** 
+     * Returns the image of characters which are currently visible through this window
+     * onto the screen.
+     *
+     * The buffer is managed by the ScreenWindow instance and does not need to be
+     * deleted by the caller.
+     */
+    Character* getImage();
+
+    /**
+     * Returns the line attributes associated with the lines of characters which
+     * are currently visible through this window
+     */
+    QVector<LineProperty> getLineProperties();
+
+    /**
+     * Returns the number of lines which the region of the window
+     * specified by scrollRegion() has been scrolled by since the last call 
+     * to resetScrollCount().  scrollRegion() is in most cases the 
+     * whole window, but will be a smaller area in, for example, applications
+     * which provide split-screen facilities.
+     *
+     * This is not guaranteed to be accurate, but allows views to optimise
+     * rendering by reducing the amount of costly text rendering that
+     * needs to be done when the output is scrolled. 
+     */
+    int scrollCount() const;
+
+    /**
+     * Resets the count of scrolled lines returned by scrollCount()
+     */
+    void resetScrollCount();
+
+    /**
+     * Returns the area of the window which was last scrolled, this is 
+     * usually the whole window area.
+     *
+     * Like scrollCount(), this is not guaranteed to be accurate,
+     * but allows views to optimise rendering.
+     */
+    QRect scrollRegion() const;
+
+    /** 
+     * Sets the start of the selection to the given @p line and @p column within 
+     * the window.
+     */
+    void setSelectionStart( int column , int line , bool columnMode );
+    /**
+     * Sets the end of the selection to the given @p line and @p column within
+     * the window.
+     */
+    void setSelectionEnd( int column , int line ); 
+    /**
+     * Retrieves the start of the selection within the window.
+     */
+    void getSelectionStart( int& column , int& line );
+    /**
+     * Retrieves the end of the selection within the window.
+     */
+    void getSelectionEnd( int& column , int& line );
+    /**
+     * Returns true if the character at @p line , @p column is part of the selection.
+     */
+    bool isSelected( int column , int line );
+    /** 
+     * Clears the current selection
+     */
+    void clearSelection();
+
+	/** Sets the number of lines in the window */
+	void setWindowLines(int lines);
+    /** Returns the number of lines in the window */
+    int windowLines() const;
+    /** Returns the number of columns in the window */
+    int windowColumns() const;
+    
+    /** Returns the total number of lines in the screen */
+    int lineCount() const;
+    /** Returns the total number of columns in the screen */
+    int columnCount() const;
+
+    /** Returns the index of the line which is currently at the top of this window */
+    int currentLine() const;
+
+    /** 
+     * Returns the position of the cursor 
+     * within the window.
+     */
+    QPoint cursorPosition() const;
+
+    /** 
+     * Convenience method. Returns true if the window is currently at the bottom
+     * of the screen.
+     */
+    bool atEndOfOutput() const;
+
+    /** Scrolls the window so that @p line is at the top of the window */
+    void scrollTo( int line );
+
+    enum RelativeScrollMode
+    {
+        ScrollLines,
+        ScrollPages
+    };
+
+    /** 
+     * Scrolls the window relative to its current position on the screen.
+     *
+     * @param mode Specifies whether @p amount refers to the number of lines or the number
+     * of pages to scroll.    
+     * @param amount The number of lines or pages ( depending on @p mode ) to scroll by.  If
+     * this number is positive, the view is scrolled down.  If this number is negative, the view
+     * is scrolled up.
+     */
+    void scrollBy( RelativeScrollMode mode , int amount );
+
+    /** 
+     * Specifies whether the window should automatically move to the bottom
+     * of the screen when new output is added.
+     *
+     * If this is set to true, the window will be moved to the bottom of the associated screen ( see 
+     * screen() ) when the notifyOutputChanged() method is called.
+     */
+    void setTrackOutput(bool trackOutput);
+    /** 
+     * Returns whether the window automatically moves to the bottom of the screen as
+     * new output is added.  See setTrackOutput()
+     */
+    bool trackOutput() const;
+
+    /**
+     * Returns the text which is currently selected.
+     *
+     * @param preserveLineBreaks See Screen::selectedText()
+     */
+    QString selectedText( bool preserveLineBreaks ) const;
+
+public slots:
+    /** 
+     * Notifies the window that the contents of the associated terminal screen have changed.
+     * This moves the window to the bottom of the screen if trackOutput() is true and causes
+     * the outputChanged() signal to be emitted.
+     */
+    void notifyOutputChanged();
+
+signals:
+    /**
+     * Emitted when the contents of the associated terminal screen ( see screen() ) changes. 
+     */
+    void outputChanged();
+
+    /**
+     * Emitted when the screen window is scrolled to a different position.
+     * 
+     * @param line The line which is now at the top of the window.
+     */
+    void scrolled(int line);
+
+    /**
+     * Emitted when the selection is changed.
+     */
+    void selectionChanged();
+
+private:
+	int endWindowLine() const;
+	void fillUnusedArea();
+
+    Screen* _screen; // see setScreen() , screen()
+	Character* _windowBuffer;
+	int _windowBufferSize;
+	bool _bufferNeedsUpdate;
+
+	int  _windowLines;
+    int  _currentLine; // see scrollTo() , currentLine()
+    bool _trackOutput; // see setTrackOutput() , trackOutput() 
+    int  _scrollCount; // count of lines which the window has been scrolled by since
+                       // the last call to resetScrollCount()
+};
+
+#endif // SCREENWINDOW_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/SelfListener.cpp	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,38 @@
+/* qterminal - a terminal widget for Qt
+ * Copyright (C) 2011 Jacob Dawid (jacob.dawid@googlemail.com)
+ *
+ * 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "unix/SelfListener.h"
+
+SelfListener::SelfListener(int a, QObject *parent) :
+    QThread(parent) {
+    _a = a;
+}
+
+void SelfListener::run() {
+    char buf[4096];
+    int len;
+    bool running = true;
+    while(running) {
+         while((len = ::read(_a, buf, 4096)) > 0) {
+            buf[len] = 0; // Just in case.
+            emit recvData(buf, len);
+            msleep(30);
+         }
+         if(len < 0)
+           running = false;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/SelfListener.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,40 @@
+/* qterminal - a terminal widget for Qt
+ * Copyright (C) 2011 Jacob Dawid (jacob.dawid@googlemail.com)
+ *
+ * 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef SELFLISTENER_H
+#define SELFLISTENER_H
+
+#include <QThread>
+#include <unistd.h>
+
+class SelfListener : public QThread
+{
+    Q_OBJECT
+public:
+    explicit SelfListener(int a, QObject *parent = 0);
+
+signals:
+    void recvData(const char* stdOutBuffer, int stdOutlen);
+
+public slots:
+
+protected:
+    void run();
+    int _a;
+};
+
+#endif // SELFLISTENER_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/TerminalCharacterDecoder.cpp	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,224 @@
+/*
+    This file is part of Konsole, an X terminal.
+    
+    Copyright (C) 2006 by Robert Knight <robertknight@gmail.com>
+    
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU Lesser General Public License as published by
+    the Free Software Foundation; either version 2 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 Lesser General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+// Own
+#include "unix/TerminalCharacterDecoder.h"
+
+// Qt
+#include <QtCore/QTextStream>
+
+PlainTextDecoder::PlainTextDecoder()
+ : _output(0)
+ , _includeTrailingWhitespace(true)
+{
+
+}
+void PlainTextDecoder::setTrailingWhitespace(bool enable)
+{
+    _includeTrailingWhitespace = enable;
+}
+bool PlainTextDecoder::trailingWhitespace() const
+{
+    return _includeTrailingWhitespace;
+}
+void PlainTextDecoder::begin(QTextStream* output)
+{
+   _output = output; 
+}
+void PlainTextDecoder::end()
+{
+    _output = 0;
+}
+void PlainTextDecoder::decodeLine(const Character* const characters, int count, LineProperty /*properties*/
+							 )
+{
+    Q_ASSERT( _output );
+
+	//TODO should we ignore or respect the LINE_WRAPPED line property?
+
+	//note:  we build up a QString and send it to the text stream rather writing into the text
+	//stream a character at a time because it is more efficient.
+	//(since QTextStream always deals with QStrings internally anyway)
+	QString plainText;
+	plainText.reserve(count);
+   
+    int outputCount = count;
+
+    // if inclusion of trailing whitespace is disabled then find the end of the
+    // line
+    if ( !_includeTrailingWhitespace )
+    {
+        for (int i = count-1 ; i >= 0 ; i--)
+        {
+            if ( characters[i].character != ' '  )
+                break;
+            else
+                outputCount--;
+        }
+    }
+
+	for (int i=0;i<outputCount;i++)
+	{
+		plainText.append( QChar(characters[i].character) );
+	}
+
+	*_output << plainText;
+}
+
+HTMLDecoder::HTMLDecoder() :
+        _output(0)
+	   ,_colorTable(base_color_table)
+       ,_innerSpanOpen(false)
+       ,_lastRendition(DEFAULT_RENDITION)
+{
+	
+}
+
+void HTMLDecoder::begin(QTextStream* output)
+{
+    _output = output;
+
+    QString text;
+
+	//open monospace span
+    openSpan(text,"font-family:monospace");
+
+    *output << text;
+}
+
+void HTMLDecoder::end()
+{
+    Q_ASSERT( _output );
+
+    QString text;
+
+    closeSpan(text);
+
+    *_output << text;
+
+    _output = 0;
+
+}
+
+//TODO: Support for LineProperty (mainly double width , double height)
+void HTMLDecoder::decodeLine(const Character* const characters, int count, LineProperty /*properties*/
+							)
+{
+    Q_ASSERT( _output );
+
+	QString text;
+
+	int spaceCount = 0;
+		
+	for (int i=0;i<count;i++)
+	{
+		QChar ch(characters[i].character);
+
+		//check if appearance of character is different from previous char
+		if ( characters[i].rendition != _lastRendition  ||
+		     characters[i].foregroundColor != _lastForeColor  ||
+			 characters[i].backgroundColor != _lastBackColor )
+		{
+			if ( _innerSpanOpen )
+					closeSpan(text);
+
+			_lastRendition = characters[i].rendition;
+			_lastForeColor = characters[i].foregroundColor;
+			_lastBackColor = characters[i].backgroundColor;
+			
+			//build up style string
+			QString style;
+
+			if ( _lastRendition & RE_BOLD ||
+                             (_colorTable && characters[i].isBold(_colorTable)) )
+					style.append("font-weight:bold;");
+
+
+			if ( _lastRendition & RE_UNDERLINE )
+					style.append("font-decoration:underline;");
+		
+			//colours - a colour table must have been defined first
+			if ( _colorTable )	
+			{
+				style.append( QString("color:%1;").arg(_lastForeColor.color(_colorTable).name() ) );
+
+				if (!characters[i].isTransparent(_colorTable))
+				{
+					style.append( QString("background-color:%1;").arg(_lastBackColor.color(_colorTable).name() ) );
+				}
+			}
+		
+			//open the span with the current style	
+			openSpan(text,style);
+			_innerSpanOpen = true;
+		}
+
+		//handle whitespace
+		if (ch.isSpace())
+			spaceCount++;
+		else
+			spaceCount = 0;
+		
+
+		//output current character
+		if (spaceCount < 2)
+		{
+			//escape HTML tag characters and just display others as they are
+			if ( ch == '<' )
+				text.append("&lt;");
+			else if (ch == '>')
+					text.append("&gt;");
+			else	
+					text.append(ch);
+		}
+		else
+		{
+			text.append("&nbsp;"); //HTML truncates multiple spaces, so use a space marker instead
+		}
+		
+	}
+
+	//close any remaining open inner spans
+	if ( _innerSpanOpen )
+		closeSpan(text);
+
+	//start new line
+	text.append("<br>");
+	
+	*_output << text;
+}
+
+void HTMLDecoder::openSpan(QString& text , const QString& style)
+{
+	text.append( QString("<span style=\"%1\">").arg(style) );
+}
+
+void HTMLDecoder::closeSpan(QString& text)
+{
+	text.append("</span>");
+}
+
+void HTMLDecoder::setColorTable(const ColorEntry* table)
+{
+	_colorTable = table;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/TerminalCharacterDecoder.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,134 @@
+/*
+    This file is part of Konsole, an X terminal.
+    
+    Copyright (C) 2006-7 by Robert Knight <robertknight@gmail.com>
+    
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU Lesser General Public License as published by
+    the Free Software Foundation; either version 2 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 Lesser General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+#ifndef TERMINAL_CHARACTER_DECODER_H
+#define TERMINAL_CHARACTER_DECODER_H
+
+#include "unix/Character.h"
+
+class QTextStream;
+
+/**
+ * Base class for terminal character decoders
+ *
+ * The decoder converts lines of terminal characters which consist of a unicode character, foreground
+ * and background colours and other appearance-related properties into text strings.
+ *
+ * Derived classes may produce either plain text with no other colour or appearance information, or
+ * they may produce text which incorporates these additional properties. 
+ */
+class TerminalCharacterDecoder
+{
+public:
+	virtual ~TerminalCharacterDecoder() {}
+
+    /** Begin decoding characters.  The resulting text is appended to @p output. */
+    virtual void begin(QTextStream* output) = 0;
+    /** End decoding. */
+    virtual void end() = 0;
+
+	/**
+	 * Converts a line of terminal characters with associated properties into a text string
+	 * and writes the string into an output QTextStream.
+	 *
+	 * @param characters An array of characters of length @p count.
+	 * @param properties Additional properties which affect all characters in the line
+	 * @param output The output stream which receives the decoded text
+	 */
+	virtual void decodeLine(const Character* const characters, 
+							int count,
+							LineProperty properties) = 0; 
+};
+
+/**
+ * A terminal character decoder which produces plain text, ignoring colours and other appearance-related
+ * properties of the original characters.
+ */
+class PlainTextDecoder : public TerminalCharacterDecoder
+{
+public:
+	PlainTextDecoder(); 
+
+    /** 
+     * Set whether trailing whitespace at the end of lines should be included 
+     * in the output.
+     * Defaults to true.
+     */
+    void setTrailingWhitespace(bool enable);
+    /**
+     * Returns whether trailing whitespace at the end of lines is included
+     * in the output.
+     */
+    bool trailingWhitespace() const;
+
+    virtual void begin(QTextStream* output);
+    virtual void end();
+
+	virtual void decodeLine(const Character* const characters,
+							int count,
+							LineProperty properties);	
+
+    
+private:
+    QTextStream* _output;
+    bool _includeTrailingWhitespace;
+};
+
+/**
+ * A terminal character decoder which produces pretty HTML markup
+ */
+class HTMLDecoder : public TerminalCharacterDecoder
+{
+public:
+	/** 
+	 * Constructs an HTML decoder using a default black-on-white color scheme.
+	 */
+	HTMLDecoder();
+
+	/**
+	 * Sets the colour table which the decoder uses to produce the HTML colour codes in its
+	 * output
+	 */
+	void setColorTable( const ColorEntry* table );
+		
+	virtual void decodeLine(const Character* const characters,
+							int count,
+							LineProperty properties);
+
+    virtual void begin(QTextStream* output);
+    virtual void end();
+
+private:
+	void openSpan(QString& text , const QString& style);
+	void closeSpan(QString& text);
+
+    QTextStream* _output;
+	const ColorEntry* _colorTable;
+    bool _innerSpanOpen; 
+	quint8 _lastRendition;
+	CharacterColor _lastForeColor;
+	CharacterColor _lastBackColor;
+
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/TerminalModel.cpp	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,414 @@
+/*
+    This file is part of Konsole
+
+    Copyright (C) 2006-2007 by Robert Knight <robertknight@gmail.com>
+    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    Copyright (C) 2012 Jacob Dawid <jacob.dawid@googlemail.com>
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+// Own
+#include "unix/TerminalModel.h"
+
+// Standard
+#include <assert.h>
+#include <stdlib.h>
+
+// Qt
+#include <QtGui/QApplication>
+#include <QtCore/QByteRef>
+#include <QtCore/QDir>
+#include <QtCore/QFile>
+#include <QtCore/QRegExp>
+#include <QtCore/QStringList>
+#include <QtCore>
+
+#include "unix/TerminalView.h"
+#include "unix/Vt102Emulation.h"
+
+TerminalModel::TerminalModel(KPty *kpty) :
+    _shellProcess(0)
+  , _emulation(0)
+  , _monitorActivity(false)
+  , _monitorSilence(false)
+  , _notifiedActivity(false)
+  , _autoClose(true)
+  , _wantedClose(false)
+  , _silenceSeconds(10)
+  , _addToUtmp(false)
+  , _fullScripting(false)
+  , _hasDarkBackground(false)
+{
+    _kpty = kpty;
+
+    //create emulation backend
+    _emulation = new Vt102Emulation();
+    connect( _emulation, SIGNAL( stateSet(int) ),
+             this, SLOT( activityStateSet(int) ) );
+    connect( _emulation, SIGNAL( changeTabTextColorRequest( int ) ),
+             this, SIGNAL( changeTabTextColorRequest( int ) ) );
+    connect( _emulation, SIGNAL(profileChangeCommandReceived(const QString&)),
+             this, SIGNAL( profileChangeCommandReceived(const QString&)) );
+    // TODO
+    // connect( _emulation,SIGNAL(imageSizeChanged(int,int)) , this ,
+    //        SLOT(onEmulationSizeChange(int,int)) );
+
+    _selfListener = new SelfListener(kpty->masterFd());
+    _selfListener->start();
+    connect( _selfListener, SIGNAL(recvData(const char*,int)),
+             this, SLOT(onReceiveBlock(const char*,int)), Qt::BlockingQueuedConnection);
+
+    connect( _emulation, SIGNAL(sendData(const char*,int))
+             ,this,SLOT(sendData(const char*,int)));
+
+    //connect( _emulation,SIGNAL(lockPtyRequest(bool)),_shellProcess,SLOT(lockPty(bool)) );
+    //connect( _emulation,SIGNAL(useUtf8Request(bool)),_shellProcess,SLOT(setUtf8Mode(bool)) );
+
+
+    //connect( _shellProcess,SIGNAL(done(int)), this, SLOT(done(int)) );
+
+    //setup timer for monitoring session activity
+    _monitorTimer = new QTimer(this);
+    _monitorTimer->setSingleShot(true);
+    connect(_monitorTimer, SIGNAL(timeout()), this, SLOT(monitorTimerDone()));
+}
+
+void TerminalModel::setDarkBackground(bool darkBackground)
+{
+    _hasDarkBackground = darkBackground;
+}
+bool TerminalModel::hasDarkBackground() const
+{
+    return _hasDarkBackground;
+}
+
+void TerminalModel::setCodec(QTextCodec* codec)
+{
+    emulation()->setCodec(codec);
+}
+
+QList<TerminalView*> TerminalModel::views() const
+{
+    return _views;
+}
+
+void TerminalModel::addView(TerminalView* widget)
+{
+    Q_ASSERT( !_views.contains(widget) );
+
+    _views.append(widget);
+
+    if ( _emulation != 0 )
+    {
+        // connect emulation - view signals and slots
+        connect( widget , SIGNAL(keyPressedSignal(QKeyEvent*)) , _emulation ,
+                 SLOT(sendKeyEvent(QKeyEvent*)) );
+        connect( widget , SIGNAL(mouseSignal(int,int,int,int)) , _emulation ,
+                 SLOT(sendMouseEvent(int,int,int,int)) );
+        connect( widget , SIGNAL(sendStringToEmu(const char*)) , _emulation ,
+                 SLOT(sendString(const char*)) );
+
+        // allow emulation to notify view when the foreground process
+        // indicates whether or not it is interested in mouse signals
+        connect( _emulation , SIGNAL(programUsesMouseChanged(bool)) , widget ,
+                 SLOT(setUsesMouse(bool)) );
+
+        widget->setUsesMouse( _emulation->programUsesMouse() );
+
+        widget->setScreenWindow(_emulation->createWindow());
+    }
+
+    //connect view signals and slots
+    QObject::connect( widget ,SIGNAL(changedContentSizeSignal(int,int)),this,
+                      SLOT(onViewSizeChange(int,int)));
+
+    QObject::connect( widget ,SIGNAL(destroyed(QObject*)) , this ,
+                      SLOT(viewDestroyed(QObject*)) );
+    //slot for close
+    //QObject::connect(this, SIGNAL(finished()), widget, SLOT(close()));
+}
+
+void TerminalModel::viewDestroyed(QObject* view)
+{
+    TerminalView* display = (TerminalView*)view;
+
+    Q_ASSERT( _views.contains(display) );
+
+    removeView(display);
+}
+
+void TerminalModel::sendData(const char *buf, int len)
+{
+    ssize_t bytesWritten = ::write(_kpty->masterFd(), buf, len);
+    (void)bytesWritten;
+}
+
+void TerminalModel::removeView(TerminalView* widget)
+{
+    _views.removeAll(widget);
+
+    disconnect(widget,0,this,0);
+
+    if ( _emulation != 0 )
+    {
+        // disconnect
+        //  - key presses signals from widget
+        //  - mouse activity signals from widget
+        //  - string sending signals from widget
+        //
+        //  ... and any other signals connected in addView()
+        disconnect( widget, 0, _emulation, 0);
+
+        // disconnect state change signals emitted by emulation
+        disconnect( _emulation , 0 , widget , 0);
+    }
+
+    // close the session automatically when the last view is removed
+    if ( _views.count() == 0 )
+    {
+        close();
+    }
+}
+
+void TerminalModel::run()
+{
+    emit started();
+}
+
+void TerminalModel::monitorTimerDone()
+{
+    //FIXME: The idea here is that the notification popup will appear to tell the user than output from
+    //the terminal has stopped and the popup will disappear when the user activates the session.
+    //
+    //This breaks with the addition of multiple views of a session.  The popup should disappear
+    //when any of the views of the session becomes active
+
+
+    //FIXME: Make message text for this notification and the activity notification more descriptive.
+    if (_monitorSilence) {
+        //    KNotification::event("Silence", ("Silence in session '%1'", _nameTitle), QPixmap(),
+        //                    QApplication::activeWindow(),
+        //                    KNotification::CloseWhenWidgetActivated);
+        emit stateChanged(NOTIFYSILENCE);
+    }
+    else
+    {
+        emit stateChanged(NOTIFYNORMAL);
+    }
+
+    _notifiedActivity=false;
+}
+
+void TerminalModel::activityStateSet(int state)
+{
+    if (state==NOTIFYBELL)
+    {
+        emit bellRequest("");
+    }
+    else if (state==NOTIFYACTIVITY)
+    {
+        if (_monitorSilence) {
+            _monitorTimer->start(_silenceSeconds*1000);
+        }
+
+        if ( _monitorActivity ) {
+            //FIXME:  See comments in Session::monitorTimerDone()
+            if (!_notifiedActivity) {
+                //        KNotification::event("Activity", ("Activity in session '%1'", _nameTitle), QPixmap(),
+                //                        QApplication::activeWindow(),
+                //        KNotification::CloseWhenWidgetActivated);
+                _notifiedActivity=true;
+            }
+        }
+    }
+
+    if ( state==NOTIFYACTIVITY && !_monitorActivity )
+        state = NOTIFYNORMAL;
+    if ( state==NOTIFYSILENCE && !_monitorSilence )
+        state = NOTIFYNORMAL;
+
+    emit stateChanged(state);
+}
+
+void TerminalModel::onViewSizeChange(int /*height*/, int /*width*/)
+{
+    updateTerminalSize();
+}
+void TerminalModel::onEmulationSizeChange(int lines , int columns)
+{
+    setSize( QSize(lines,columns) );
+}
+
+void TerminalModel::updateTerminalSize()
+{
+    QListIterator<TerminalView*> viewIter(_views);
+
+    int minLines = -1;
+    int minColumns = -1;
+
+    // minimum number of lines and columns that views require for
+    // their size to be taken into consideration ( to avoid problems
+    // with new view widgets which haven't yet been set to their correct size )
+    const int VIEW_LINES_THRESHOLD = 2;
+    const int VIEW_COLUMNS_THRESHOLD = 2;
+
+    //select largest number of lines and columns that will fit in all visible views
+    while ( viewIter.hasNext() )
+    {
+        TerminalView* view = viewIter.next();
+        if ( view->isHidden() == false &&
+             view->lines() >= VIEW_LINES_THRESHOLD &&
+             view->columns() >= VIEW_COLUMNS_THRESHOLD )
+        {
+            minLines = (minLines == -1) ? view->lines() : qMin( minLines , view->lines() );
+            minColumns = (minColumns == -1) ? view->columns() : qMin( minColumns , view->columns() );
+        }
+    }
+
+    // backend emulation must have a _terminal of at least 1 column x 1 line in size
+    if ( minLines > 0 && minColumns > 0 )
+    {
+        _emulation->setImageSize( minLines , minColumns );
+        _kpty->setWinSize (minLines, minColumns);
+        //_shellProcess->setWindowSize( minLines , minColumns );
+    }
+}
+
+void TerminalModel::refresh()
+{
+}
+
+void TerminalModel::close()
+{
+    _autoClose = true;
+    _wantedClose = true;
+}
+
+void TerminalModel::sendText(const QString &text) const
+{
+    _emulation->sendText(text);
+}
+
+TerminalModel::~TerminalModel()
+{
+    delete _emulation;
+}
+
+void TerminalModel::setProfileKey(const QString& key)
+{
+    _profileKey = key;
+    emit profileChanged(key);
+}
+QString TerminalModel::profileKey() const { return _profileKey; }
+
+void TerminalModel::done(int)
+{
+    emit finished();
+}
+
+Emulation* TerminalModel::emulation() const
+{
+    return _emulation;
+}
+
+QString TerminalModel::keyBindings() const
+{
+    return _emulation->keyBindings();
+}
+
+void TerminalModel::setKeyBindings(const QString &id)
+{
+    _emulation->setKeyBindings(id);
+}
+
+void TerminalModel::setHistoryType(const HistoryType &hType)
+{
+    _emulation->setHistory(hType);
+}
+
+const HistoryType& TerminalModel::historyType() const
+{
+    return _emulation->history();
+}
+
+void TerminalModel::clearHistory()
+{
+    _emulation->clearHistory();
+}
+
+// unused currently
+bool TerminalModel::isMonitorActivity() const { return _monitorActivity; }
+// unused currently
+bool TerminalModel::isMonitorSilence()  const { return _monitorSilence; }
+
+void TerminalModel::setMonitorActivity(bool _monitor)
+{
+    _monitorActivity=_monitor;
+    _notifiedActivity=false;
+
+    activityStateSet(NOTIFYNORMAL);
+}
+
+void TerminalModel::setMonitorSilence(bool _monitor)
+{
+    if (_monitorSilence==_monitor)
+        return;
+
+    _monitorSilence=_monitor;
+    if (_monitorSilence)
+    {
+        _monitorTimer->start(_silenceSeconds*1000);
+    }
+    else
+        _monitorTimer->stop();
+
+    activityStateSet(NOTIFYNORMAL);
+}
+
+void TerminalModel::setMonitorSilenceSeconds(int seconds)
+{
+    _silenceSeconds=seconds;
+    if (_monitorSilence) {
+        _monitorTimer->start(_silenceSeconds*1000);
+    }
+}
+
+void TerminalModel::setAddToUtmp(bool set)
+{
+    _addToUtmp = set;
+}
+
+void TerminalModel::onReceiveBlock(const char* buf, int len )
+{
+    _emulation->receiveData( buf, len );
+    emit receivedData( QString::fromLatin1( buf, len ) );
+}
+
+QSize TerminalModel::size()
+{
+    return _emulation->imageSize();
+}
+
+void TerminalModel::setSize(const QSize& size)
+{
+    if ((size.width() <= 1) || (size.height() <= 1))
+        return;
+
+    emit resizeRequest(size);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/TerminalModel.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,371 @@
+/*
+    This file is part of Konsole, an X terminal.
+
+    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
+    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    Copyright (C) 2012 Jacob Dawid <jacob.dawid@googlemail.com>
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+#ifndef TERMINALMODEL_H
+#define TERMINALMODEL_H
+
+// Qt
+#include <QtCore/QStringList>
+#include <QtCore>
+#include <QWidget>
+
+#include "unix/SelfListener.h"
+
+// Konsole
+#include "unix/History.h"
+#include "unix/kpty.h"
+
+class KProcess;
+
+class Emulation;
+class PseudoTerminal;
+class TerminalView;
+
+/**
+ * Represents a terminal session consisting of a pseudo-teletype and a terminal emulation.
+ * The pseudo-teletype (or PTY) handles I/O between the terminal process and Konsole.
+ * The terminal emulation ( Emulation and subclasses ) processes the output stream from the
+ * PTY and produces a character image which is then shown on views connected to the session.
+ *
+ * Each Session can be connected to one or more views by using the addView() method.
+ * The attached views can then display output from the program running in the terminal
+ * or send input to the program in the terminal in the form of keypresses and mouse
+ * activity.
+ */
+class TerminalModel : public QObject {
+Q_OBJECT
+
+public:
+  Q_PROPERTY(QString keyBindings READ keyBindings WRITE setKeyBindings)
+  Q_PROPERTY(QSize size READ size WRITE setSize)
+
+  /**
+   * Constructs a new session.
+   *
+   * To start the terminal process, call the run() method,
+   * after specifying the program and arguments
+   * using setProgram() and setArguments()
+   *
+   * If no program or arguments are specified explicitly, the Session
+   * falls back to using the program specified in the SHELL environment
+   * variable.
+   */
+  TerminalModel(KPty *kpty);
+  ~TerminalModel();
+
+
+  /**
+   * Sets the profile associated with this session.
+   *
+   * @param profileKey A key which can be used to obtain the current
+   * profile settings from the SessionManager
+   */
+  void setProfileKey(const QString& profileKey);
+  /**
+   * Returns the profile key associated with this session.
+   * This can be passed to the SessionManager to obtain the current
+   * profile settings.
+   */
+  QString profileKey() const;
+
+  /**
+   * Adds a new view for this session.
+   *
+   * The viewing widget will display the output from the terminal and
+   * input from the viewing widget (key presses, mouse activity etc.)
+   * will be sent to the terminal.
+   *
+   * Views can be removed using removeView().  The session is automatically
+   * closed when the last view is removed.
+   */
+  void addView(TerminalView* widget);
+  /**
+   * Removes a view from this session.  When the last view is removed,
+   * the session will be closed automatically.
+   *
+   * @p widget will no longer display output from or send input
+   * to the terminal
+   */
+  void removeView(TerminalView* widget);
+
+  /**
+   * Returns the views connected to this session
+   */
+  QList<TerminalView*> views() const;
+
+  /**
+   * Returns the terminal emulation instance being used to encode / decode
+   * characters to / from the process.
+   */
+  Emulation*  emulation() const;
+
+
+
+  /**
+   * Sets the type of history store used by this session.
+   * Lines of output produced by the terminal are added
+   * to the history store.  The type of history store
+   * used affects the number of lines which can be
+   * remembered before they are lost and the storage
+   * (in memory, on-disk etc.) used.
+   */
+  void setHistoryType(const HistoryType& type);
+  /**
+   * Returns the type of history store used by this session.
+   */
+  const HistoryType& historyType() const;
+  /**
+   * Clears the history store used by this session.
+   */
+  void clearHistory();
+
+  /**
+   * Enables monitoring for activity in the session.
+   * This will cause notifySessionState() to be emitted
+   * with the NOTIFYACTIVITY state flag when output is
+   * received from the terminal.
+   */
+  void setMonitorActivity(bool);
+  /** Returns true if monitoring for activity is enabled. */
+  bool isMonitorActivity() const;
+
+  /**
+   * Enables monitoring for silence in the session.
+   * This will cause notifySessionState() to be emitted
+   * with the NOTIFYSILENCE state flag when output is not
+   * received from the terminal for a certain period of
+   * time, specified with setMonitorSilenceSeconds()
+   */
+  void setMonitorSilence(bool);
+  /**
+   * Returns true if monitoring for inactivity (silence)
+   * in the session is enabled.
+   */
+  bool isMonitorSilence()  const;
+  /** See setMonitorSilence() */
+  void setMonitorSilenceSeconds(int seconds);
+
+  /**
+   * Sets the key bindings used by this session.  The bindings
+   * specify how input key sequences are translated into
+   * the character stream which is sent to the terminal.
+   *
+   * @param id The name of the key bindings to use.  The
+   * names of available key bindings can be determined using the
+   * KeyboardTranslatorManager class.
+   */
+  void setKeyBindings(const QString& id);
+  /** Returns the name of the key bindings used by this session. */
+  QString keyBindings() const;
+
+
+  /** Specifies whether a utmp entry should be created for the pty used by this session. */
+  void setAddToUtmp(bool);
+
+  /**
+   * Specifies whether to close the session automatically when the terminal
+   * process terminates.
+   */
+  void setAutoClose(bool b) { _autoClose = b; }
+
+  /**
+   * Sends @p text to the current foreground terminal program.
+   */
+  void sendText(const QString& text) const;
+
+
+  /** Returns the terminal session's window size in lines and columns. */
+  QSize size();
+  /**
+   * Emits a request to resize the session to accommodate
+   * the specified window size.
+   *
+   * @param size The size in lines and columns to request.
+   */
+  void setSize(const QSize& size);
+
+  /** Sets the text codec used by this session's terminal emulation. */
+  void setCodec(QTextCodec* codec);
+
+  /**
+   * Sets whether the session has a dark background or not.  The session
+   * uses this information to set the COLORFGBG variable in the process's
+   * environment, which allows the programs running in the terminal to determine
+   * whether the background is light or dark and use appropriate colors by default.
+   *
+   * This has no effect once the session is running.
+   */
+  void setDarkBackground(bool darkBackground);
+  /**
+   * Returns true if the session has a dark background.
+   * See setDarkBackground()
+   */
+  bool hasDarkBackground() const;
+
+  /**
+   * Attempts to get the shell program to redraw the current display area.
+   * This can be used after clearing the screen, for example, to get the
+   * shell to redraw the prompt line.
+   */
+  void refresh();
+
+public slots:
+
+  /**
+   * Starts the terminal session.
+   *
+   * This creates the terminal process and connects the teletype to it.
+   */
+  void run();
+
+  /**
+   * Closes the terminal session.  This sends a hangup signal
+   * (SIGHUP) to the terminal process and causes the done(Session*)
+   * signal to be emitted.
+   */
+  void close();
+
+signals:
+
+  /** Emitted when the terminal process starts. */
+  void started();
+
+  /**
+   * Emitted when the terminal process exits.
+   */
+  void finished();
+
+  /**
+   * Emitted when output is received from the terminal process.
+   */
+  void receivedData( const QString& text );
+
+  /** Emitted when the session's title has changed. */
+  void titleChanged();
+
+  /** Emitted when the session's profile has changed. */
+  void profileChanged(const QString& profile);
+
+  /**
+   * Emitted when the activity state of this session changes.
+   *
+   * @param state The new state of the session.  This may be one
+   * of NOTIFYNORMAL, NOTIFYSILENCE or NOTIFYACTIVITY
+   */
+  void stateChanged(int state);
+
+  /** Emitted when a bell event occurs in the session. */
+  void bellRequest( const QString& message );
+
+  /**
+   * Requests that the color the text for any tabs associated with
+   * this session should be changed;
+   *
+   * TODO: Document what the parameter does
+   */
+  void changeTabTextColorRequest(int);
+
+  /**
+   * Requests that the background color of views on this session
+   * should be changed.
+   */
+  void changeBackgroundColorRequest(const QColor&);
+
+  /** TODO: Document me. */
+  void openUrlRequest(const QString& url);
+
+  /**
+   * Emitted when the terminal process requests a change
+   * in the size of the terminal window.
+   *
+   * @param size The requested window size in terms of lines and columns.
+   */
+  void resizeRequest(const QSize& size);
+
+  /**
+   * Emitted when a profile change command is received from the terminal.
+   *
+   * @param text The text of the command.  This is a string of the form
+   * "PropertyName=Value;PropertyName=Value ..."
+   */
+  void profileChangeCommandReceived(const QString& text);
+
+private slots:
+  void done(int);
+
+  void onReceiveBlock(const char* buffer, int len );
+  void monitorTimerDone();
+
+  void onViewSizeChange(int height, int width);
+  void onEmulationSizeChange(int lines , int columns);
+
+  void activityStateSet(int);
+
+  //automatically detach views from sessions when view is destroyed
+  void viewDestroyed(QObject* view);
+
+  void sendData(const char* buf, int len);
+
+private:
+
+  void updateTerminalSize();
+  WId windowId() const;
+
+  int            _uniqueIdentifier;
+
+  PseudoTerminal* _shellProcess;
+  Emulation*    _emulation;
+
+  QList<TerminalView*> _views;
+
+  bool           _monitorActivity;
+  bool           _monitorSilence;
+  bool           _notifiedActivity;
+  bool           _masterMode;
+  bool           _autoClose;
+  bool           _wantedClose;
+  QTimer*        _monitorTimer;
+
+  int            _silenceSeconds;
+
+  bool           _addToUtmp;
+  bool           _fullScripting;
+
+  int            _masterFd;
+  int            _slaveFd;
+
+  SelfListener  *_selfListener;
+  KPty         * _kpty;
+
+
+  QColor         _modifiedBackground; // as set by: echo -en '\033]11;Color\007
+
+  QString        _profileKey;
+
+  bool _hasDarkBackground;
+};
+
+
+#endif // TERMINALMODEL_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/TerminalView.cpp	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,2661 @@
+/*
+    This file is part of Konsole, a terminal emulator for KDE.
+
+    Copyright (C) 2006-7 by Robert Knight <robertknight@gmail.com>
+    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    Copyright (C) 2012 Jacob Dawid <jacob.dawid@googlemail.com>
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+// Own
+#include "unix/TerminalView.h"
+
+// Qt
+#include <QtGui/QApplication>
+#include <QtGui/QBoxLayout>
+#include <QtGui/QClipboard>
+#include <QtGui/QKeyEvent>
+#include <QtCore/QEvent>
+#include <QtCore/QTime>
+#include <QtCore/QFile>
+#include <QtGui/QGridLayout>
+#include <QtGui/QLabel>
+#include <QtGui/QLayout>
+#include <QtGui/QPainter>
+#include <QtGui/QPixmap>
+#include <QtGui/QScrollBar>
+#include <QtGui/QStyle>
+#include <QtCore>
+#include <QtGui>
+
+#include "unix/Filter.h"
+#include "unix/konsole_wcwidth.h"
+#include "unix/ScreenWindow.h"
+#include "unix/TerminalCharacterDecoder.h"
+
+#ifndef loc
+#define loc(X,Y) ((Y)*_columns+(X))
+#endif
+
+#define yMouseScroll 1
+
+#define REPCHAR   "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
+  "abcdefgjijklmnopqrstuvwxyz" \
+  "0123456789./+@"
+
+// scroll increment used when dragging selection at top/bottom of window.
+
+// static
+bool TerminalView::_antialiasText = true;
+
+/* ------------------------------------------------------------------------- */
+/*                                                                           */
+/*                                Colors                                     */
+/*                                                                           */
+/* ------------------------------------------------------------------------- */
+
+/* Note that we use ANSI color order (bgr), while IBMPC color order is (rgb)
+
+   Code        0       1       2       3       4       5       6       7
+   ----------- ------- ------- ------- ------- ------- ------- ------- -------
+   ANSI  (bgr) Black   Red     Green   Yellow  Blue    Magenta Cyan    White
+   IBMPC (rgb) Black   Blue    Green   Cyan    Red     Magenta Yellow  White
+*/
+
+ScreenWindow* TerminalView::screenWindow() const
+{
+  return _screenWindow;
+}
+void TerminalView::setScreenWindow(ScreenWindow* window)
+{
+  // disconnect existing screen window if any
+  if ( _screenWindow )
+    {
+      disconnect( _screenWindow , 0 , this , 0 );
+    }
+
+  _screenWindow = window;
+
+  if ( window )
+    {
+      //#warning "The order here is not specified - does it matter whether updateImage or updateLineProperties comes first?"
+      connect( _screenWindow , SIGNAL(outputChanged()) , this , SLOT(updateLineProperties()) );
+      connect( _screenWindow , SIGNAL(outputChanged()) , this , SLOT(updateImage()) );
+      window->setWindowLines(_lines);
+    }
+}
+
+const ColorEntry* TerminalView::colorTable() const
+{
+  return _colorTable;
+}
+
+void TerminalView::setColorTable(const ColorEntry table[])
+{
+  for (int i = 0; i < TABLE_COLORS; i++)
+    _colorTable[i] = table[i];
+
+  QPalette p = palette();
+  p.setColor( backgroundRole(), _colorTable[DEFAULT_BACK_COLOR].color );
+  setPalette( p );
+
+  // Avoid propagating the palette change to the scroll bar
+  _scrollBar->setPalette( QApplication::palette() );
+
+  update();
+}
+
+/* ------------------------------------------------------------------------- */
+/*                                                                           */
+/*                                   Font                                    */
+/*                                                                           */
+/* ------------------------------------------------------------------------- */
+
+/*
+   The VT100 has 32 special graphical characters. The usual vt100 extended
+   xterm fonts have these at 0x00..0x1f.
+
+   QT's iso mapping leaves 0x00..0x7f without any changes. But the graphicals
+   come in here as proper unicode characters.
+
+   We treat non-iso10646 fonts as VT100 extended and do the required mapping
+   from unicode to 0x00..0x1f. The remaining translation is then left to the
+   QCodec.
+*/
+
+static inline bool isLineChar(quint16 c) { return ((c & 0xFF80) == 0x2500);}
+static inline bool isLineCharString(const QString& string)
+{
+  return (string.length() > 0) && (isLineChar(string.at(0).unicode()));
+}
+
+
+// assert for i in [0..31] : vt100extended(vt100_graphics[i]) == i.
+
+unsigned short vt100_graphics[32] =
+{ // 0/8     1/9    2/10    3/11    4/12    5/13    6/14    7/15
+  0x0020, 0x25C6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0,
+  0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c,
+  0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251c, 0x2524, 0x2534,
+  0x252c, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00b7
+};
+
+void TerminalView::fontChange(const QFont&)
+{
+  QFontMetrics fm(font());
+  _fontHeight = fm.height() + _lineSpacing;
+
+
+  // waba TerminalDisplay 1.123:
+  // "Base character width on widest ASCII character. This prevents too wide
+  //  characters in the presence of double wide (e.g. Japanese) characters."
+  // Get the width from representative normal width characters
+  _fontWidth = (double)fm.width(REPCHAR)/(double)strlen(REPCHAR);
+
+  _fixedFont = true;
+
+  int fw = fm.width(REPCHAR[0]);
+  for(unsigned int i=1; i< strlen(REPCHAR); i++)
+    {
+      if (fw != fm.width(REPCHAR[i]))
+        {
+          _fixedFont = false;
+          break;
+        }
+    }
+
+
+  if (_fontWidth < 1)
+    _fontWidth = 1;
+
+  _fontAscent = fm.ascent();
+
+  emit changedFontMetricSignal( _fontHeight, _fontWidth );
+  //parentWidget()->setFixedWidth(_fontWidth * 80 + _leftMargin);
+  propagateSize();
+  update();
+}
+
+void TerminalView::setVTFont(const QFont& f)
+{
+  QFont font = f;
+
+  QFontMetrics metrics(font);
+
+  if ( metrics.height() < height() && metrics.maxWidth() < width() )
+    {
+      // hint that text should be drawn without anti-aliasing.
+      // depending on the user's font configuration, this may not be respected
+      if (!_antialiasText)
+        font.setStyleStrategy( QFont::NoAntialias );
+
+      // experimental optimization.  Konsole assumes that the terminal is using a
+      // mono-spaced font, in which case kerning information should have an effect.
+      // Disabling kerning saves some computation when rendering text.
+      // font.setKerning(false);
+
+      QWidget::setFont(font);
+      fontChange(font);
+    }
+}
+
+void TerminalView::setFont(const QFont &)
+{
+  // ignore font change request if not coming from konsole itself
+}
+
+/* ------------------------------------------------------------------------- */
+/*                                                                           */
+/*                         Constructor / Destructor                          */
+/*                                                                           */
+/* ------------------------------------------------------------------------- */
+
+TerminalView::TerminalView(QWidget *parent)
+  :QWidget(parent)
+  ,_screenWindow(0)
+  ,_allowBell(true)
+  ,_gridLayout(0)
+  ,_fontHeight(1)
+  ,_fontWidth(1)
+  ,_fontAscent(1)
+  ,_lines(1)
+  ,_columns(1)
+  ,_usedLines(1)
+  ,_usedColumns(1)
+  ,_contentHeight(1)
+  ,_contentWidth(1)
+  ,_image(0)
+  ,_randomSeed(0)
+  ,_resizing(false)
+  ,_terminalSizeHint(false)
+  ,_terminalSizeStartup(true)
+  ,_actSel(0)
+  ,_wordSelectionMode(false)
+  ,_lineSelectionMode(false)
+  ,_preserveLineBreaks(false)
+  ,_columnSelectionMode(false)
+  ,_scrollbarLocation(NoScrollBar)
+  ,_wordCharacters(":@-./_~")
+  ,_bellMode(SystemBeepBell)
+  ,_blinking(false)
+  ,_cursorBlinking(false)
+  ,_hasBlinkingCursor(false)
+  ,_ctrlDrag(false)
+  ,_tripleClickMode(SelectWholeLine)
+  ,_isFixedSize(false)
+  ,_possibleTripleClick(false)
+  ,_resizeWidget(0)
+  ,_resizeTimer(0)
+  ,_outputSuspendedLabel(0)
+  ,_lineSpacing(0)
+  ,_colorsInverted(false)
+  ,_blendColor(qRgba(0,0,0,0xff))
+  ,_filterChain(new TerminalImageFilterChain())
+  ,_cursorShape(BlockCursor)
+  ,_readonly(false)
+{
+  // terminal applications are not designed with Right-To-Left in mind,
+  // so the layout is forced to Left-To-Right
+  setLayoutDirection(Qt::LeftToRight);
+
+  // The offsets are not yet calculated.
+  // Do not calculate these too often to be more smoothly when resizing
+  // konsole in opaque mode.
+  _topMargin = DEFAULT_TOP_MARGIN;
+  _leftMargin = DEFAULT_LEFT_MARGIN;
+
+  // create scroll bar for scrolling output up and down
+  // set the scroll bar's slider to occupy the whole area of the scroll bar initially
+  _scrollBar = new QScrollBar(this);
+  setScroll(0,0);
+  _scrollBar->setCursor( Qt::ArrowCursor );
+  connect(_scrollBar, SIGNAL(valueChanged(int)), this,
+          SLOT(scrollBarPositionChanged(int)));
+
+  // setup timers for blinking cursor and text
+  _blinkTimer   = new QTimer(this);
+  connect(_blinkTimer, SIGNAL(timeout()), this, SLOT(blinkEvent()));
+  _blinkCursorTimer   = new QTimer(this);
+  connect(_blinkCursorTimer, SIGNAL(timeout()), this, SLOT(blinkCursorEvent()));
+
+  //  QCursor::setAutoHideCursor( this, true );
+
+  setUsesMouse(true);
+  setColorTable(base_color_table);
+  setMouseTracking(true);
+
+  // Enable drag and drop
+  setAcceptDrops(true); // attempt
+  dragInfo.state = diNone;
+
+  setFocusPolicy( Qt::WheelFocus );
+
+  // enable input method support
+  setAttribute(Qt::WA_InputMethodEnabled, true);
+
+  // this is an important optimization, it tells Qt
+  // that TerminalDisplay will handle repainting its entire area.
+  setAttribute(Qt::WA_OpaquePaintEvent);
+
+  _gridLayout = new QGridLayout(this);
+  _gridLayout->setMargin(0);
+
+  setLayout( _gridLayout );
+}
+
+TerminalView::~TerminalView()
+{
+  qApp->removeEventFilter( this );
+
+  delete[] _image;
+
+  delete _gridLayout;
+  delete _outputSuspendedLabel;
+  delete _filterChain;
+}
+
+/* ------------------------------------------------------------------------- */
+/*                                                                           */
+/*                             Display Operations                            */
+/*                                                                           */
+/* ------------------------------------------------------------------------- */
+
+/**
+ A table for emulating the simple (single width) unicode drawing chars.
+ It represents the 250x - 257x glyphs. If it's zero, we can't use it.
+ if it's not, it's encoded as follows: imagine a 5x5 grid where the points are numbered
+ 0 to 24 left to top, top to bottom. Each point is represented by the corresponding bit.
+
+ Then, the pixels basically have the following interpretation:
+ _|||_
+ -...-
+ -...-
+ -...-
+ _|||_
+
+where _ = none
+      | = vertical line.
+      - = horizontal line.
+ */
+
+
+enum LineEncode
+{
+  TopL  = (1<<1),
+  TopC  = (1<<2),
+  TopR  = (1<<3),
+
+  LeftT = (1<<5),
+  Int11 = (1<<6),
+  Int12 = (1<<7),
+  Int13 = (1<<8),
+  RightT = (1<<9),
+
+  LeftC = (1<<10),
+  Int21 = (1<<11),
+  Int22 = (1<<12),
+  Int23 = (1<<13),
+  RightC = (1<<14),
+
+  LeftB = (1<<15),
+  Int31 = (1<<16),
+  Int32 = (1<<17),
+  Int33 = (1<<18),
+  RightB = (1<<19),
+
+  BotL  = (1<<21),
+  BotC  = (1<<22),
+  BotR  = (1<<23)
+};
+
+#include "LineFont.h"
+
+static void drawLineChar(QPainter& paint, int x, int y, int w, int h, uchar code)
+{
+  //Calculate cell midpoints, end points.
+  int cx = x + w/2;
+  int cy = y + h/2;
+  int ex = x + w - 1;
+  int ey = y + h - 1;
+
+  quint32 toDraw = LineChars[code];
+
+  //Top _lines:
+  if (toDraw & TopL)
+    paint.drawLine(cx-1, y, cx-1, cy-2);
+  if (toDraw & TopC)
+    paint.drawLine(cx, y, cx, cy-2);
+  if (toDraw & TopR)
+    paint.drawLine(cx+1, y, cx+1, cy-2);
+
+  //Bot _lines:
+  if (toDraw & BotL)
+    paint.drawLine(cx-1, cy+2, cx-1, ey);
+  if (toDraw & BotC)
+    paint.drawLine(cx, cy+2, cx, ey);
+  if (toDraw & BotR)
+    paint.drawLine(cx+1, cy+2, cx+1, ey);
+
+  //Left _lines:
+  if (toDraw & LeftT)
+    paint.drawLine(x, cy-1, cx-2, cy-1);
+  if (toDraw & LeftC)
+    paint.drawLine(x, cy, cx-2, cy);
+  if (toDraw & LeftB)
+    paint.drawLine(x, cy+1, cx-2, cy+1);
+
+  //Right _lines:
+  if (toDraw & RightT)
+    paint.drawLine(cx+2, cy-1, ex, cy-1);
+  if (toDraw & RightC)
+    paint.drawLine(cx+2, cy, ex, cy);
+  if (toDraw & RightB)
+    paint.drawLine(cx+2, cy+1, ex, cy+1);
+
+  //Intersection points.
+  if (toDraw & Int11)
+    paint.drawPoint(cx-1, cy-1);
+  if (toDraw & Int12)
+    paint.drawPoint(cx, cy-1);
+  if (toDraw & Int13)
+    paint.drawPoint(cx+1, cy-1);
+
+  if (toDraw & Int21)
+    paint.drawPoint(cx-1, cy);
+  if (toDraw & Int22)
+    paint.drawPoint(cx, cy);
+  if (toDraw & Int23)
+    paint.drawPoint(cx+1, cy);
+
+  if (toDraw & Int31)
+    paint.drawPoint(cx-1, cy+1);
+  if (toDraw & Int32)
+    paint.drawPoint(cx, cy+1);
+  if (toDraw & Int33)
+    paint.drawPoint(cx+1, cy+1);
+
+}
+
+void TerminalView::drawLineCharString(	QPainter& painter, int x, int y, const QString& str,
+                                       const Character* attributes)
+{
+  const QPen& currentPen = painter.pen();
+
+  if ( attributes->rendition & RE_BOLD )
+    {
+      QPen boldPen(currentPen);
+      boldPen.setWidth(3);
+      painter.setPen( boldPen );
+    }
+
+  for (int i=0 ; i < str.length(); i++)
+    {
+      uchar code = str[i].cell();
+      if (LineChars[code])
+        drawLineChar(painter, x + (_fontWidth*i), y, _fontWidth, _fontHeight, code);
+    }
+
+  painter.setPen( currentPen );
+}
+
+void TerminalView::setKeyboardCursorShape(KeyboardCursorShape shape)
+{
+  _cursorShape = shape;
+}
+TerminalView::KeyboardCursorShape TerminalView::keyboardCursorShape() const
+{
+  return _cursorShape;
+}
+void TerminalView::setKeyboardCursorColor(bool useForegroundColor, const QColor& color)
+{
+  if (useForegroundColor)
+    _cursorColor = QColor(); // an invalid color means that
+  // the foreground color of the
+  // current character should
+  // be used
+
+  else
+    _cursorColor = color;
+}
+QColor TerminalView::keyboardCursorColor() const
+{
+  return _cursorColor;
+}
+
+void TerminalView::drawBackground(QPainter& painter, const QRect& rect, const QColor& backgroundColor)
+{
+  // the area of the widget showing the contents of the terminal display is drawn
+  // using the background color from the color scheme set with setColorTable()
+  //
+  // the area of the widget behind the scroll-bar is drawn using the background
+  // brush from the scroll-bar's palette, to give the effect of the scroll-bar
+  // being outside of the terminal display and visual consistency with other KDE
+  // applications.
+  //
+  QRect scrollBarArea = _scrollBar->isVisible() ?
+        rect.intersected(_scrollBar->geometry()) :
+        QRect();
+
+  QRegion contentsRegion = QRegion(rect).subtracted(scrollBarArea);
+  QRect contentsRect = contentsRegion.boundingRect();
+
+  painter.fillRect(contentsRect, backgroundColor);
+  painter.fillRect(scrollBarArea,_scrollBar->palette().background());
+}
+
+void TerminalView::drawCursor(QPainter& painter,
+                              const QRect& rect,
+                              const QColor& foregroundColor,
+                              const QColor& /*backgroundColor*/,
+                              bool& invertCharacterColor)
+{
+  QRect cursorRect = rect;
+  cursorRect.setHeight(_fontHeight - _lineSpacing - 1);
+
+  if (!_cursorBlinking)
+    {
+      if ( _cursorColor.isValid() )
+        painter.setPen(_cursorColor);
+      else {
+          painter.setPen(foregroundColor);
+        }
+
+      if ( _cursorShape == BlockCursor )
+        {
+          // draw the cursor outline, adjusting the area so that
+          // it is draw entirely inside 'rect'
+          int penWidth = qMax(1,painter.pen().width());
+
+          painter.drawRect(cursorRect.adjusted(penWidth/2,
+                                               penWidth/2,
+                                               - penWidth/2 - penWidth%2,
+                                               - penWidth/2 - penWidth%2));
+          if ( hasFocus() )
+            {
+              painter.fillRect(cursorRect, _cursorColor.isValid() ? _cursorColor : foregroundColor);
+
+              if ( !_cursorColor.isValid() )
+                {
+                  // invert the colour used to draw the text to ensure that the character at
+                  // the cursor position is readable
+                  invertCharacterColor = true;
+                }
+            }
+        }
+      else if ( _cursorShape == UnderlineCursor )
+        painter.drawLine(cursorRect.left(),
+                         cursorRect.bottom(),
+                         cursorRect.right(),
+                         cursorRect.bottom());
+      else if ( _cursorShape == IBeamCursor )
+        painter.drawLine(cursorRect.left(),
+                         cursorRect.top(),
+                         cursorRect.left(),
+                         cursorRect.bottom());
+
+    }
+}
+
+void TerminalView::drawCharacters(QPainter& painter,
+                                  const QRect& rect,
+                                  const QString& text,
+                                  const Character* style,
+                                  bool invertCharacterColor)
+{
+  // don't draw text which is currently blinking
+  if ( _blinking && (style->rendition & RE_BLINK) )
+    return;
+
+  // setup bold and underline
+  bool useBold = style->rendition & RE_BOLD || style->isBold(_colorTable) || font().bold();
+  bool useUnderline = style->rendition & RE_UNDERLINE || font().underline();
+
+  QFont font = painter.font();
+  if (    font.bold() != useBold
+          || font.underline() != useUnderline )
+    {
+      font.setBold(useBold);
+      font.setUnderline(useUnderline);
+      painter.setFont(font);
+    }
+
+  const CharacterColor& textColor = ( invertCharacterColor ? style->backgroundColor : style->foregroundColor );
+  const QColor color = textColor.color(_colorTable);
+
+  QPen pen = painter.pen();
+  if ( pen.color() != color )
+    {
+      pen.setColor(color);
+      painter.setPen(color);
+    }
+  // draw text
+  if ( isLineCharString(text) ) {
+      drawLineCharString(painter,rect.x(),rect.y(),text,style);
+    }
+  else
+    {
+      // the drawText(rect,flags,string) overload is used here with null flags
+      // instead of drawText(rect,string) because the (rect,string) overload causes
+      // the application's default layout direction to be used instead of
+      // the widget-specific layout direction, which should always be
+      // Qt::LeftToRight for this widget
+      painter.drawText(rect,0,text);
+    }
+}
+
+void TerminalView::drawTextFragment(QPainter& painter ,
+                                    const QRect& rect,
+                                    const QString& text,
+                                    const Character* style)
+{
+  painter.save();
+
+  // setup painter
+  const QColor foregroundColor = style->foregroundColor.color(_colorTable);
+  const QColor backgroundColor = style->backgroundColor.color(_colorTable);
+
+  // draw background if different from the display's background color
+  if ( backgroundColor != palette().background().color() )
+    drawBackground(painter,rect,backgroundColor);
+
+  // draw cursor shape if the current character is the cursor
+  // this may alter the foreground and background colors
+  bool invertCharacterColor = false;
+
+  if ( style->rendition & RE_CURSOR )
+    drawCursor(painter,rect,foregroundColor,backgroundColor,invertCharacterColor);
+  // draw text
+  drawCharacters(painter,rect,text,style,invertCharacterColor);
+
+  painter.restore();
+}
+
+void TerminalView::setRandomSeed(uint randomSeed) { _randomSeed = randomSeed; }
+uint TerminalView::randomSeed() const { return _randomSeed; }
+
+#if 0
+/*!
+    Set XIM Position
+*/
+void TerminalDisplay::setCursorPos(const int curx, const int cury)
+{
+  QPoint tL  = contentsRect().topLeft();
+  int    tLx = tL.x();
+  int    tLy = tL.y();
+
+  int xpos, ypos;
+  ypos = _topMargin + tLy + _fontHeight*(cury-1) + _fontAscent;
+  xpos = _leftMargin + tLx + _fontWidth*curx;
+  //setMicroFocusHint(xpos, ypos, 0, _fontHeight); //### ???
+  // fprintf(stderr, "x/y = %d/%d\txpos/ypos = %d/%d\n", curx, cury, xpos, ypos);
+  _cursorLine = cury;
+  _cursorCol = curx;
+}
+#endif
+
+// scrolls the image by 'lines', down if lines > 0 or up otherwise.
+//
+// the terminal emulation keeps track of the scrolling of the character
+// image as it receives input, and when the view is updated, it calls scrollImage()
+// with the final scroll amount.  this improves performance because scrolling the
+// display is much cheaper than re-rendering all the text for the
+// part of the image which has moved up or down.
+// Instead only new lines have to be drawn
+//
+// note:  it is important that the area of the display which is
+// scrolled aligns properly with the character grid -
+// which has a top left point at (_leftMargin,_topMargin) ,
+// a cell width of _fontWidth and a cell height of _fontHeight).
+void TerminalView::scrollImage(int lines , const QRect& screenWindowRegion)
+{
+  // if the flow control warning is enabled this will interfere with the
+  // scrolling optimisations and cause artifacts.  the simple solution here
+  // is to just disable the optimisation whilst it is visible
+  if ( _outputSuspendedLabel && _outputSuspendedLabel->isVisible() ) {
+      return;
+    }
+
+  // constrain the region to the display
+  // the bottom of the region is capped to the number of lines in the display's
+  // internal image - 2, so that the height of 'region' is strictly less
+  // than the height of the internal image.
+  QRect region = screenWindowRegion;
+  region.setBottom( qMin(region.bottom(),this->_lines-2) );
+
+  if (    lines == 0
+          || _image == 0
+          || !region.isValid()
+          || (region.top() + abs(lines)) >= region.bottom()
+          || this->_lines <= region.height() ) return;
+
+  QRect scrollRect;
+
+  void* firstCharPos = &_image[ region.top() * this->_columns ];
+  void* lastCharPos = &_image[ (region.top() + abs(lines)) * this->_columns ];
+
+  int top = _topMargin + (region.top() * _fontHeight);
+  int linesToMove = region.height() - abs(lines);
+  int bytesToMove = linesToMove *
+      this->_columns *
+      sizeof(Character);
+
+  Q_ASSERT( linesToMove > 0 );
+  Q_ASSERT( bytesToMove > 0 );
+
+  //scroll internal image
+  if ( lines > 0 )
+    {
+      // check that the memory areas that we are going to move are valid
+      Q_ASSERT( (char*)lastCharPos + bytesToMove <
+                (char*)(_image + (this->_lines * this->_columns)) );
+
+      Q_ASSERT( (lines*this->_columns) < _imageSize );
+
+      //scroll internal image down
+      memmove( firstCharPos , lastCharPos , bytesToMove );
+
+      //set region of display to scroll, making sure that
+      //the region aligns correctly to the character grid
+      scrollRect = QRect( _leftMargin , top,
+                          this->_usedColumns * _fontWidth ,
+                          linesToMove * _fontHeight );
+    }
+  else
+    {
+      // check that the memory areas that we are going to move are valid
+      Q_ASSERT( (char*)firstCharPos + bytesToMove <
+                (char*)(_image + (this->_lines * this->_columns)) );
+
+      //scroll internal image up
+      memmove( lastCharPos , firstCharPos , bytesToMove );
+
+      //set region of the display to scroll, making sure that
+      //the region aligns correctly to the character grid
+      QPoint topPoint( _leftMargin , top + abs(lines)*_fontHeight );
+
+      scrollRect = QRect( topPoint ,
+                          QSize( this->_usedColumns*_fontWidth ,
+                                 linesToMove * _fontHeight ));
+    }
+
+  //scroll the display vertically to match internal _image
+  scroll( 0 , _fontHeight * (-lines) , scrollRect );
+}
+
+QRegion TerminalView::hotSpotRegion() const
+{
+  QRegion region;
+  foreach( Filter::HotSpot* hotSpot , _filterChain->hotSpots() )
+    {
+      QRect rect;
+      rect.setLeft(hotSpot->startColumn());
+      rect.setTop(hotSpot->startLine());
+      rect.setRight(hotSpot->endColumn());
+      rect.setBottom(hotSpot->endLine());
+
+      region |= imageToWidget(rect);
+    }
+  return region;
+}
+
+void TerminalView::processFilters()
+{
+  if (!_screenWindow)
+    return;
+
+  QRegion preUpdateHotSpots = hotSpotRegion();
+
+  // use _screenWindow->getImage() here rather than _image because
+  // other classes may call processFilters() when this display's
+  // ScreenWindow emits a scrolled() signal - which will happen before
+  // updateImage() is called on the display and therefore _image is
+  // out of date at this point
+  _filterChain->setImage( _screenWindow->getImage(),
+                          _screenWindow->windowLines(),
+                          _screenWindow->windowColumns(),
+                          _screenWindow->getLineProperties() );
+  _filterChain->process();
+
+  QRegion postUpdateHotSpots = hotSpotRegion();
+
+  update( preUpdateHotSpots | postUpdateHotSpots );
+}
+
+void TerminalView::updateImage()
+{
+  if ( !_screenWindow )
+    return;
+  updateLineProperties();
+
+  // optimization - scroll the existing image where possible and
+  // avoid expensive text drawing for parts of the image that
+  // can simply be moved up or down
+  scrollImage( _screenWindow->scrollCount() ,
+               _screenWindow->scrollRegion() );
+  _screenWindow->resetScrollCount();
+
+  Character* const newimg = _screenWindow->getImage();
+  int lines = _screenWindow->windowLines() + 1;
+  int columns = _screenWindow->windowColumns();
+
+  setScroll( _screenWindow->currentLine() , _screenWindow->lineCount() );
+
+  if (!_image)
+    updateImageSize(); // Create _image
+
+  Q_ASSERT( this->_usedLines <= this->_lines );
+  Q_ASSERT( this->_usedColumns <= this->_columns );
+
+  int y,x,len;
+
+  QPoint tL  = contentsRect().topLeft();
+
+  int    tLx = tL.x();
+  int    tLy = tL.y();
+  _hasBlinker = false;
+
+  CharacterColor cf;       // undefined
+  CharacterColor _clipboard;       // undefined
+  int cr  = -1;   // undefined
+
+  const int linesToUpdate = qMin(this->_lines, qMax(0,lines  ));
+  const int columnsToUpdate = qMin(this->_columns,qMax(0,columns));
+
+  QChar *disstrU = new QChar[columnsToUpdate];
+  char *dirtyMask = new char[columnsToUpdate+2];
+  QRegion dirtyRegion;
+
+  // debugging variable, this records the number of lines that are found to
+  // be 'dirty' ( ie. have changed from the old _image to the new _image ) and
+  // which therefore need to be repainted
+  int dirtyLineCount = 0;
+
+  for (y = 0; y < linesToUpdate; y++)
+    {
+      const Character*       currentLine = &_image[y*this->_columns];
+      const Character* const newLine = &newimg[y*columns];
+
+      bool updateLine = false;
+
+      // The dirty mask indicates which characters need repainting. We also
+      // mark surrounding neighbours dirty, in case the character exceeds
+      // its cell boundaries
+      memset(dirtyMask, 0, columnsToUpdate+2);
+
+      for( x = 0 ; x < columnsToUpdate ; x++)
+        {
+          if ( newLine[x] != currentLine[x] )
+            {
+              dirtyMask[x] = true;
+            }
+        }
+
+      if (!_resizing) // not while _resizing, we're expecting a paintEvent
+        for (x = 0; x < columnsToUpdate; x++)
+          {
+            _hasBlinker |= (newLine[x].rendition & RE_BLINK);
+
+            // Start drawing if this character or the next one differs.
+            // We also take the next one into account to handle the situation
+            // where characters exceed their cell width.
+            if (dirtyMask[x])
+              {
+                quint16 c = newLine[x+0].character;
+                if ( !c )
+                  continue;
+                int p = 0;
+                disstrU[p++] = c; //fontMap(c);
+                bool lineDraw = isLineChar(c);
+                bool doubleWidth = (x+1 == columnsToUpdate) ? false : (newLine[x+1].character == 0);
+                cr = newLine[x].rendition;
+                _clipboard = newLine[x].backgroundColor;
+                if (newLine[x].foregroundColor != cf) cf = newLine[x].foregroundColor;
+                int lln = columnsToUpdate - x;
+                for (len = 1; len < lln; len++)
+                  {
+                    const Character& ch = newLine[x+len];
+
+                    if (!ch.character)
+                      continue; // Skip trailing part of multi-col chars.
+
+                    bool nextIsDoubleWidth = (x+len+1 == columnsToUpdate) ? false : (newLine[x+len+1].character == 0);
+
+                    if (  ch.foregroundColor != cf ||
+                          ch.backgroundColor != _clipboard ||
+                          ch.rendition != cr ||
+                          !dirtyMask[x+len] ||
+                          isLineChar(c) != lineDraw ||
+                          nextIsDoubleWidth != doubleWidth )
+                      break;
+
+                    disstrU[p++] = c; //fontMap(c);
+                  }
+
+                QString unistr(disstrU, p);
+
+                bool saveFixedFont = _fixedFont;
+                if (lineDraw)
+                  _fixedFont = false;
+                if (doubleWidth)
+                  _fixedFont = false;
+
+                updateLine = true;
+
+                _fixedFont = saveFixedFont;
+                x += len - 1;
+              }
+
+          }
+
+      //both the top and bottom halves of double height _lines must always be redrawn
+      //although both top and bottom halves contain the same characters, only
+      //the top one is actually
+      //drawn.
+      if (_lineProperties.count() > y)
+        updateLine |= (_lineProperties[y] & LINE_DOUBLEHEIGHT);
+
+      // if the characters on the line are different in the old and the new _image
+      // then this line must be repainted.
+      if (updateLine)
+        {
+          dirtyLineCount++;
+
+          // add the area occupied by this line to the region which needs to be
+          // repainted
+          QRect dirtyRect = QRect( _leftMargin+tLx ,
+                                   _topMargin+tLy+_fontHeight*y ,
+                                   _fontWidth * columnsToUpdate ,
+                                   _fontHeight );
+
+          dirtyRegion |= dirtyRect;
+        }
+
+      // replace the line of characters in the old _image with the
+      // current line of the new _image
+      memcpy((void*)currentLine,(const void*)newLine,columnsToUpdate*sizeof(Character));
+    }
+
+  // if the new _image is smaller than the previous _image, then ensure that the area
+  // outside the new _image is cleared
+  if ( linesToUpdate < _usedLines )
+    {
+      dirtyRegion |= QRect(   _leftMargin+tLx ,
+                              _topMargin+tLy+_fontHeight*linesToUpdate ,
+                              _fontWidth * this->_columns ,
+                              _fontHeight * (_usedLines-linesToUpdate) );
+    }
+  _usedLines = linesToUpdate;
+
+  if ( columnsToUpdate < _usedColumns )
+    {
+      dirtyRegion |= QRect(   _leftMargin+tLx+columnsToUpdate*_fontWidth ,
+                              _topMargin+tLy ,
+                              _fontWidth * (_usedColumns-columnsToUpdate) ,
+                              _fontHeight * this->_lines );
+    }
+  _usedColumns = columnsToUpdate;
+
+  dirtyRegion |= _inputMethodData.previousPreeditRect;
+
+  // update the parts of the display which have changed
+  update(dirtyRegion);
+
+  if ( _hasBlinker && !_blinkTimer->isActive()) _blinkTimer->start( BLINK_DELAY );
+  if (!_hasBlinker && _blinkTimer->isActive()) { _blinkTimer->stop(); _blinking = false; }
+  delete[] dirtyMask;
+  delete[] disstrU;
+
+}
+
+void TerminalView::showResizeNotification()
+{
+  if (_terminalSizeHint && isVisible())
+    {
+      if (_terminalSizeStartup) {
+          _terminalSizeStartup=false;
+          return;
+        }
+      if (!_resizeWidget)
+        {
+          _resizeWidget = new QLabel(("Size: XXX x XXX"), this);
+          _resizeWidget->setMinimumWidth(_resizeWidget->fontMetrics().width(("Size: XXX x XXX")));
+          _resizeWidget->setMinimumHeight(_resizeWidget->sizeHint().height());
+          _resizeWidget->setAlignment(Qt::AlignCenter);
+
+          _resizeWidget->setStyleSheet("background-color:palette(window);border-style:solid;border-width:1px;border-color:palette(dark)");
+
+          _resizeTimer = new QTimer(this);
+          _resizeTimer->setSingleShot(true);
+          connect(_resizeTimer, SIGNAL(timeout()), _resizeWidget, SLOT(hide()));
+
+        }
+      QString sizeStr;
+      sizeStr.sprintf("Size: %d x %d", _columns, _lines);
+      _resizeWidget->setText(sizeStr);
+      _resizeWidget->move((width()-_resizeWidget->width())/2,
+                          (height()-_resizeWidget->height())/2+20);
+      _resizeWidget->show();
+      _resizeTimer->start(1000);
+    }
+}
+
+void TerminalView::setBlinkingCursor(bool blink)
+{
+  _hasBlinkingCursor=blink;
+
+  if (blink && !_blinkCursorTimer->isActive())
+    _blinkCursorTimer->start(BLINK_DELAY);
+
+  if (!blink && _blinkCursorTimer->isActive())
+    {
+      _blinkCursorTimer->stop();
+      if (_cursorBlinking)
+        blinkCursorEvent();
+      else
+        _cursorBlinking = false;
+    }
+}
+
+void TerminalView::paintEvent( QPaintEvent* pe )
+{
+  updateImage();
+  //qDebug("%s %d paintEvent", __FILE__, __LINE__);
+  QPainter paint(this);
+  //qDebug("%s %d paintEvent %d %d", __FILE__, __LINE__, paint.window().top(), paint.window().right());
+
+  foreach (QRect rect, (pe->region() & contentsRect()).rects())
+    {
+      drawBackground(paint,rect,palette().background().color());
+      drawContents(paint, rect);
+    }
+  //    drawBackground(paint,contentsRect(),palette().background().color(),	true /* use opacity setting */);
+  //    drawContents(paint, contentsRect());
+  drawInputMethodPreeditString(paint,preeditRect());
+  paintFilters(paint);
+  paint.end();
+}
+
+QPoint TerminalView::cursorPosition() const
+{
+  if (_screenWindow)
+    return _screenWindow->cursorPosition();
+  else
+    return QPoint(0,0);
+}
+
+QRect TerminalView::preeditRect() const
+{
+  const int preeditLength = string_width(_inputMethodData.preeditString);
+
+  if ( preeditLength == 0 )
+    return QRect();
+
+  return QRect(_leftMargin + _fontWidth*cursorPosition().x(),
+               _topMargin + _fontHeight*cursorPosition().y(),
+               _fontWidth*preeditLength,
+               _fontHeight);
+}
+
+void TerminalView::drawInputMethodPreeditString(QPainter& painter , const QRect& rect)
+{
+  if ( _inputMethodData.preeditString.isEmpty() ) {
+      return;
+    }
+  const QPoint cursorPos = cursorPosition();
+
+  bool invertColors = false;
+  const QColor background = _colorTable[DEFAULT_BACK_COLOR].color;
+  const QColor foreground = _colorTable[DEFAULT_FORE_COLOR].color;
+  const Character* style = &_image[loc(cursorPos.x(),cursorPos.y())];
+
+  drawBackground(painter,rect,background);
+  drawCursor(painter,rect,foreground,background,invertColors);
+  drawCharacters(painter,rect,_inputMethodData.preeditString,style,invertColors);
+
+  _inputMethodData.previousPreeditRect = rect;
+}
+
+FilterChain* TerminalView::filterChain() const
+{
+  return _filterChain;
+}
+
+void TerminalView::paintFilters(QPainter& painter)
+{
+  //qDebug("%s %d paintFilters", __FILE__, __LINE__);
+
+  // get color of character under mouse and use it to draw
+  // lines for filters
+  QPoint cursorPos = mapFromGlobal(QCursor::pos());
+  int cursorLine;
+  int cursorColumn;
+  getCharacterPosition( cursorPos , cursorLine , cursorColumn );
+  Character cursorCharacter = _image[loc(cursorColumn,cursorLine)];
+
+  painter.setPen( QPen(cursorCharacter.foregroundColor.color(colorTable())) );
+
+  // iterate over hotspots identified by the display's currently active filters
+  // and draw appropriate visuals to indicate the presence of the hotspot
+
+  QList<Filter::HotSpot*> spots = _filterChain->hotSpots();
+  QListIterator<Filter::HotSpot*> iter(spots);
+  while (iter.hasNext())
+    {
+      Filter::HotSpot* spot = iter.next();
+
+      for ( int line = spot->startLine() ; line <= spot->endLine() ; line++ )
+        {
+          int startColumn = 0;
+          int endColumn = _columns-1; // TODO use number of _columns which are actually
+          // occupied on this line rather than the width of the
+          // display in _columns
+
+          // ignore whitespace at the end of the lines
+          while ( QChar(_image[loc(endColumn,line)].character).isSpace() && endColumn > 0 )
+            endColumn--;
+
+          // increment here because the column which we want to set 'endColumn' to
+          // is the first whitespace character at the end of the line
+          endColumn++;
+
+          if ( line == spot->startLine() )
+            startColumn = spot->startColumn();
+          if ( line == spot->endLine() )
+            endColumn = spot->endColumn();
+
+          // subtract one pixel from
+          // the right and bottom so that
+          // we do not overdraw adjacent
+          // hotspots
+          //
+          // subtracting one pixel from all sides also prevents an edge case where
+          // moving the mouse outside a link could still leave it underlined
+          // because the check below for the position of the cursor
+          // finds it on the border of the target area
+          QRect r;
+          r.setCoords( startColumn*_fontWidth + 1, line*_fontHeight + 1,
+                       endColumn*_fontWidth - 1, (line+1)*_fontHeight - 1 );
+
+          // Underline link hotspots
+          if ( spot->type() == Filter::HotSpot::Link )
+            {
+              QFontMetrics metrics(font());
+
+              // find the baseline (which is the invisible line that the characters in the font sit on,
+              // with some having tails dangling below)
+              int baseline = r.bottom() - metrics.descent();
+              // find the position of the underline below that
+              int underlinePos = baseline + metrics.underlinePos();
+
+              if ( r.contains( mapFromGlobal(QCursor::pos()) ) )
+                painter.drawLine( r.left() , underlinePos ,
+                                  r.right() , underlinePos );
+            }
+          // Marker hotspots simply have a transparent rectanglular shape
+          // drawn on top of them
+          else if ( spot->type() == Filter::HotSpot::Marker )
+            {
+              //TODO - Do not use a hardcoded colour for this
+              painter.fillRect(r,QBrush(QColor(255,0,0,120)));
+            }
+        }
+    }
+}
+void TerminalView::drawContents(QPainter &paint, const QRect &rect)
+{
+  //qDebug("%s %d drawContents and rect x=%d y=%d w=%d h=%d", __FILE__, __LINE__, rect.x(), rect.y(),rect.width(),rect.height());
+
+  QPoint topLeft  = contentsRect().topLeft();
+  // Take the topmost vertical position for the view.
+  int topLeftY = topLeft.y();
+
+  // In Konsole, the view has been centered. Don't do that here, since there
+  // are strange hopping effects during a resize when the view does no match
+  // exactly the widget width.
+  // int topLeftX = (_contentWidth - _usedColumns * _fontWidth) / 2;
+  int topLeftX = 0;
+
+  int leftUpperX = qMin(_usedColumns-1, qMax(0, qRound((rect.left()   - topLeftX - _leftMargin ) / _fontWidth)));
+  int leftUpperY = qMin(_usedLines-1,  qMax(0, qRound((rect.top()    - topLeftY - _topMargin  ) / _fontHeight)));
+  int rightLowerX = qMin(_usedColumns-1, qMax(0, qRound((rect.right()  - topLeftX - _leftMargin ) / _fontWidth)));
+  int rightLowerY = qMin(_usedLines-1,  qMax(0, qRound((rect.bottom() - topLeftY - _topMargin  ) / _fontHeight)));
+
+  const int bufferSize = _usedColumns;
+  QChar *disstrU = new QChar[bufferSize];
+  for (int y = leftUpperY; y <= rightLowerY; y++)
+    {
+      quint16 c = _image[loc(leftUpperX,y)].character;
+      int x = leftUpperX;
+      if(!c && x)
+        x--; // Search for start of multi-column character
+      for (; x <= rightLowerX; x++)
+        {
+          int len = 1;
+          int p = 0;
+
+          // is this a single character or a sequence of characters ?
+          if ( _image[loc(x,y)].rendition & RE_EXTENDED_CHAR )
+            {
+              // sequence of characters
+              ushort extendedCharLength = 0;
+              ushort* chars = ExtendedCharTable::instance
+                  .lookupExtendedChar(_image[loc(x,y)].charSequence,extendedCharLength);
+              for ( int index = 0 ; index < extendedCharLength ; index++ )
+                {
+                  Q_ASSERT( p < bufferSize );
+                  disstrU[p++] = chars[index];
+                }
+            }
+          else
+            {
+              // single character
+              c = _image[loc(x,y)].character;
+              if (c)
+                {
+                  Q_ASSERT( p < bufferSize );
+                  disstrU[p++] = c; //fontMap(c);
+                }
+            }
+
+          bool lineDraw = isLineChar(c);
+          bool doubleWidth = (_image[ qMin(loc(x,y)+1,_imageSize) ].character == 0);
+          CharacterColor currentForeground = _image[loc(x,y)].foregroundColor;
+          CharacterColor currentBackground = _image[loc(x,y)].backgroundColor;
+          quint8 currentRendition = _image[loc(x,y)].rendition;
+
+          while (x+len <= rightLowerX &&
+                 _image[loc(x+len,y)].foregroundColor == currentForeground &&
+                 _image[loc(x+len,y)].backgroundColor == currentBackground &&
+                 _image[loc(x+len,y)].rendition == currentRendition &&
+                 (_image[ qMin(loc(x+len,y)+1,_imageSize) ].character == 0) == doubleWidth &&
+                 isLineChar( c = _image[loc(x+len,y)].character) == lineDraw) // Assignment!
+            {
+              if (c)
+                disstrU[p++] = c; //fontMap(c);
+              if (doubleWidth) // assert((_image[loc(x+len,y)+1].character == 0)), see above if condition
+                len++; // Skip trailing part of multi-column character
+              len++;
+            }
+          if ((x+len < _usedColumns) && (!_image[loc(x+len,y)].character))
+            len++; // Adjust for trailing part of multi-column character
+
+          bool save__fixedFont = _fixedFont;
+          if (lineDraw)
+            _fixedFont = false;
+          if (doubleWidth)
+            _fixedFont = false;
+          QString unistr(disstrU,p);
+
+          if (y < _lineProperties.size())
+            {
+              if (_lineProperties[y] & LINE_DOUBLEWIDTH) {
+                  paint.scale(2,1);
+                }
+
+              if (_lineProperties[y] & LINE_DOUBLEHEIGHT) {
+                  paint.scale(1,2);
+                }
+            }
+
+          // calculate the area in which the text will be drawn
+          QRect textArea = QRect( _leftMargin+topLeftX+_fontWidth*x ,
+                                  _topMargin+topLeftY+_fontHeight*y ,
+                                  _fontWidth*len,
+                                  _fontHeight);
+
+          // move the calculated area to take account of scaling applied to the painter.
+          // the position of the area from the origin (0,0) is scaled
+          // by the opposite of whatever
+          // transformation has been applied to the painter.  this ensures that
+          // painting does actually start from textArea.topLeft()
+          // (instead of textArea.topLeft() * painter-scale)
+          QMatrix inverted = paint.matrix().inverted();
+          textArea.moveCenter( inverted.map(textArea.center()) );
+
+
+          //paint text fragment
+          drawTextFragment(	paint,
+                              textArea,
+                              unistr,
+                              &_image[loc(x,y)] );
+
+
+          _fixedFont = save__fixedFont;
+
+          //reset back to single-width, single-height _lines
+          paint.resetMatrix();
+
+          if (y < _lineProperties.size()-1)
+            {
+              //double-height _lines are represented by two adjacent _lines
+              //containing the same characters
+              //both _lines will have the LINE_DOUBLEHEIGHT attribute.
+              //If the current line has the LINE_DOUBLEHEIGHT attribute,
+              //we can therefore skip the next line
+              if (_lineProperties[y] & LINE_DOUBLEHEIGHT)
+                y++;
+            }
+          x += len - 1;
+        } // for x
+    } // for y
+  delete [] disstrU;
+}
+
+void TerminalView::blinkEvent()
+{
+  _blinking = !_blinking;
+
+  //TODO:  Optimise to only repaint the areas of the widget
+  // where there is blinking text
+  // rather than repainting the whole widget.
+  update();
+}
+
+QRect TerminalView::imageToWidget(const QRect& imageArea) const
+{
+  //qDebug("%s %d imageToWidget", __FILE__, __LINE__);
+  QRect result;
+  result.setLeft( _leftMargin + _fontWidth * imageArea.left() );
+  result.setTop( _topMargin + _fontHeight * imageArea.top() );
+  result.setWidth( _fontWidth * imageArea.width() );
+  result.setHeight( _fontHeight * imageArea.height() );
+
+  return result;
+}
+
+void TerminalView::blinkCursorEvent()
+{
+  _cursorBlinking = !_cursorBlinking;
+
+  QRect cursorRect = imageToWidget( QRect(cursorPosition(),QSize(1,1)) );
+
+  update(cursorRect);
+}
+
+/* ------------------------------------------------------------------------- */
+/*                                                                           */
+/*                                  Resizing                                 */
+/*                                                                           */
+/* ------------------------------------------------------------------------- */
+
+void TerminalView::resizeEvent(QResizeEvent*)
+{
+  updateImageSize();
+}
+
+void TerminalView::propagateSize()
+{
+  if (_isFixedSize)
+    {
+      setSize(_columns, _lines);
+      QWidget::setFixedSize(sizeHint());
+      parentWidget()->adjustSize();
+      parentWidget()->setFixedSize(parentWidget()->sizeHint());
+      return;
+    }
+  if (_image)
+    updateImageSize();
+}
+
+void TerminalView::updateImageSize()
+{
+  //qDebug("%s %d updateImageSize", __FILE__, __LINE__);
+  Character* oldimg = _image;
+  int oldlin = _lines;
+  int oldcol = _columns;
+
+  makeImage();
+
+
+  // copy the old image to reduce flicker
+  int lines = qMin(oldlin,_lines);
+  int columns = qMin(oldcol,_columns);
+
+  //qDebug("%s %d updateImageSize", __FILE__, __LINE__);
+  if (oldimg)
+    {
+      for (int line = 0; line < lines; line++)
+        {
+          memcpy((void*)&_image[_columns*line],
+                 (void*)&oldimg[oldcol*line],columns*sizeof(Character));
+        }
+      delete[] oldimg;
+    }
+
+  //qDebug("%s %d updateImageSize", __FILE__, __LINE__);
+  if (_screenWindow)
+    _screenWindow->setWindowLines(_lines);
+
+  _resizing = (oldlin!=_lines) || (oldcol!=_columns);
+
+  if ( _resizing )
+    {
+      //qDebug("%s %d updateImageSize", __FILE__, __LINE__);
+      showResizeNotification();
+      emit changedContentSizeSignal(_contentHeight, _contentWidth); // expose resizeEvent
+    }
+  //qDebug("%s %d updateImageSize", __FILE__, __LINE__);
+
+  _resizing = false;
+}
+
+//showEvent and hideEvent are reimplemented here so that it appears to other classes that the
+//display has been resized when the display is hidden or shown.
+//
+//this allows
+//TODO: Perhaps it would be better to have separate signals for show and hide instead of using
+//the same signal as the one for a content size change
+void TerminalView::showEvent(QShowEvent*)
+{
+  emit changedContentSizeSignal(_contentHeight,_contentWidth);
+}
+void TerminalView::hideEvent(QHideEvent*)
+{
+  emit changedContentSizeSignal(_contentHeight,_contentWidth);
+}
+
+/* ------------------------------------------------------------------------- */
+/*                                                                           */
+/*                                Scrollbar                                  */
+/*                                                                           */
+/* ------------------------------------------------------------------------- */
+
+void TerminalView::scrollBarPositionChanged(int)
+{
+  if ( !_screenWindow )
+    return;
+
+  _screenWindow->scrollTo( _scrollBar->value() );
+
+  // if the thumb has been moved to the bottom of the _scrollBar then set
+  // the display to automatically track new output,
+  // that is, scroll down automatically
+  // to how new _lines as they are added
+  const bool atEndOfOutput = (_scrollBar->value() == _scrollBar->maximum());
+  _screenWindow->setTrackOutput( atEndOfOutput );
+
+  updateImage();
+}
+
+void TerminalView::setScroll(int cursor, int slines)
+{
+  //qDebug("%s %d setScroll", __FILE__, __LINE__);
+  // update _scrollBar if the range or value has changed,
+  // otherwise return
+  //
+  // setting the range or value of a _scrollBar will always trigger
+  // a repaint, so it should be avoided if it is not necessary
+  if ( _scrollBar->minimum() == 0                 &&
+       _scrollBar->maximum() == (slines - _lines) &&
+       _scrollBar->value()   == cursor )
+    {
+      return;
+    }
+
+  disconnect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int)));
+  _scrollBar->setRange(0,slines - _lines);
+  _scrollBar->setSingleStep(1);
+  _scrollBar->setPageStep(_lines);
+  _scrollBar->setValue(cursor);
+  connect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int)));
+}
+
+void TerminalView::setScrollBarPosition(ScrollBarPosition position)
+{
+  if (_scrollbarLocation == position) {
+      //      return;
+    }
+
+  if ( position == NoScrollBar )
+    _scrollBar->hide();
+  else
+    _scrollBar->show();
+
+  _topMargin = _leftMargin = 1;
+  _scrollbarLocation = position;
+
+  propagateSize();
+  update();
+}
+
+void TerminalView::mousePressEvent(QMouseEvent* ev)
+{
+  if ( _possibleTripleClick && (ev->button()==Qt::LeftButton) ) {
+      mouseTripleClickEvent(ev);
+      return;
+    }
+
+  if ( !contentsRect().contains(ev->pos()) ) return;
+
+  if ( !_screenWindow ) return;
+
+  int charLine;
+  int charColumn;
+  getCharacterPosition(ev->pos(),charLine,charColumn);
+  QPoint pos = QPoint(charColumn,charLine);
+
+  if ( ev->button() == Qt::LeftButton)
+    {
+      _lineSelectionMode = false;
+      _wordSelectionMode = false;
+
+      emit isBusySelecting(true); // Keep it steady...
+      // Drag only when the Control key is hold
+      bool selected = false;
+
+      // The receiver of the testIsSelected() signal will adjust
+      // 'selected' accordingly.
+      //emit testIsSelected(pos.x(), pos.y(), selected);
+
+      selected =  _screenWindow->isSelected(pos.x(),pos.y());
+
+      if ((!_ctrlDrag || ev->modifiers() & Qt::ControlModifier) && selected ) {
+          // The user clicked inside selected text
+          dragInfo.state = diPending;
+          dragInfo.start = ev->pos();
+        }
+      else {
+          // No reason to ever start a drag event
+          dragInfo.state = diNone;
+
+          _preserveLineBreaks = !( ( ev->modifiers() & Qt::ControlModifier ) && !(ev->modifiers() & Qt::AltModifier) );
+          _columnSelectionMode = (ev->modifiers() & Qt::AltModifier) && (ev->modifiers() & Qt::ControlModifier);
+
+          if (_mouseMarks || (ev->modifiers() & Qt::ShiftModifier))
+            {
+              _screenWindow->clearSelection();
+
+              //emit clearSelectionSignal();
+              pos.ry() += _scrollBar->value();
+              _iPntSel = _pntSel = pos;
+              _actSel = 1; // left mouse button pressed but nothing selected yet.
+
+            }
+          else
+            {
+              emit mouseSignal( 0, charColumn + 1, charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , 0);
+            }
+        }
+    }
+  else if ( ev->button() == Qt::MidButton )
+    {
+      if ( _mouseMarks || (!_mouseMarks && (ev->modifiers() & Qt::ShiftModifier)) )
+        emitSelection(true,ev->modifiers() & Qt::ControlModifier);
+      else
+        emit mouseSignal( 1, charColumn +1, charLine +1 +_scrollBar->value() -_scrollBar->maximum() , 0);
+    }
+  else if ( ev->button() == Qt::RightButton )
+    {
+      if (_mouseMarks || (ev->modifiers() & Qt::ShiftModifier))
+        {
+          emit configureRequest( this,
+                                 ev->modifiers() & (Qt::ShiftModifier|Qt::ControlModifier),
+                                 ev->pos()
+                                 );
+        }
+      else
+        emit mouseSignal( 2, charColumn +1, charLine +1 +_scrollBar->value() -_scrollBar->maximum() , 0);
+    }
+
+  QWidget::mousePressEvent (ev);
+}
+
+QList<QAction*> TerminalView::filterActions(const QPoint& position)
+{
+  int charLine, charColumn;
+  getCharacterPosition(position,charLine,charColumn);
+
+  Filter::HotSpot* spot = _filterChain->hotSpotAt(charLine,charColumn);
+
+  return spot ? spot->actions() : QList<QAction*>();
+}
+
+void TerminalView::mouseMoveEvent(QMouseEvent* ev)
+{
+  int charLine = 0;
+  int charColumn = 0;
+
+  getCharacterPosition(ev->pos(),charLine,charColumn);
+
+  // handle filters
+  // change link hot-spot appearance on mouse-over
+  Filter::HotSpot* spot = _filterChain->hotSpotAt(charLine,charColumn);
+  if ( spot && spot->type() == Filter::HotSpot::Link)
+    {
+      QRect previousHotspotArea = _mouseOverHotspotArea;
+      _mouseOverHotspotArea.setCoords( qMin(spot->startColumn() , spot->endColumn()) * _fontWidth,
+                                       spot->startLine() * _fontHeight,
+                                       qMax(spot->startColumn() , spot->endColumn()) * _fontHeight,
+                                       (spot->endLine()+1) * _fontHeight );
+
+      // display tooltips when mousing over links
+      // TODO: Extend this to work with filter types other than links
+      const QString& tooltip = spot->tooltip();
+      if ( !tooltip.isEmpty() )
+        {
+          QToolTip::showText( mapToGlobal(ev->pos()) , tooltip , this , _mouseOverHotspotArea );
+        }
+
+      update( _mouseOverHotspotArea | previousHotspotArea );
+    }
+  else if ( _mouseOverHotspotArea.isValid() )
+    {
+      update( _mouseOverHotspotArea );
+      // set hotspot area to an invalid rectangle
+      _mouseOverHotspotArea = QRect();
+    }
+
+  // for auto-hiding the cursor, we need mouseTracking
+  if (ev->buttons() == Qt::NoButton ) return;
+
+  // if the terminal is interested in mouse movements
+  // then emit a mouse movement signal, unless the shift
+  // key is being held down, which overrides this.
+  if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier))
+    {
+      int button = 3;
+      if (ev->buttons() & Qt::LeftButton)
+        button = 0;
+      if (ev->buttons() & Qt::MidButton)
+        button = 1;
+      if (ev->buttons() & Qt::RightButton)
+        button = 2;
+
+
+      emit mouseSignal( button,
+                        charColumn + 1,
+                        charLine + 1 +_scrollBar->value() -_scrollBar->maximum(),
+                        1 );
+
+      return;
+    }
+
+  if (dragInfo.state == diPending)
+    {
+      // we had a mouse down, but haven't confirmed a drag yet
+      // if the mouse has moved sufficiently, we will confirm
+
+      int distance = 10; //KGlobalSettings::dndEventDelay();
+      if ( ev->x() > dragInfo.start.x() + distance || ev->x() < dragInfo.start.x() - distance ||
+           ev->y() > dragInfo.start.y() + distance || ev->y() < dragInfo.start.y() - distance)
+        {
+          // we've left the drag square, we can start a real drag operation now
+          emit isBusySelecting(false); // Ok.. we can breath again.
+
+          _screenWindow->clearSelection();
+          doDrag();
+        }
+      return;
+    }
+  else if (dragInfo.state == diDragging)
+    {
+      // this isn't technically needed because mouseMoveEvent is suppressed during
+      // Qt drag operations, replaced by dragMoveEvent
+      return;
+    }
+
+  if (_actSel == 0) return;
+
+  // don't extend selection while pasting
+  if (ev->buttons() & Qt::MidButton) return;
+
+  extendSelection( ev->pos() );
+}
+
+#if 0
+void TerminalDisplay::setSelectionEnd()
+{
+  extendSelection( _configureRequestPoint );
+}
+#endif
+
+void TerminalView::extendSelection(const QPoint& position) {
+  QPoint pos = position;
+
+  if (!_screenWindow) {
+      return;
+    }
+
+  QPoint tL  = contentsRect().topLeft();
+  int    tLx = tL.x();
+  int    tLy = tL.y();
+  int    scroll = _scrollBar->value();
+
+  // we're in the process of moving the mouse with the left button pressed
+  // the mouse cursor will kept caught within the bounds of the text in
+  // this widget.
+
+  // Adjust position within text area bounds. See FIXME above.
+  if (pos.x() < tLx + _leftMargin) {
+      pos.setX(tLx + _leftMargin);
+    }
+  if (pos.x() > tLx + _leftMargin + _usedColumns * _fontWidth - 1) {
+      pos.setX(tLx + _leftMargin + _usedColumns * _fontWidth);
+    }
+  if (pos.y() < tLy + _topMargin) {
+      pos.setY(tLy + _topMargin);
+    }
+  if (pos.y() > tLy + _topMargin + _usedLines * _fontHeight - 1) {
+      pos.setY(tLy + _topMargin + _usedLines * _fontHeight - 1);
+    }
+
+  if (pos.y() == tLy + _topMargin + _usedLines * _fontHeight - 1) {
+      _scrollBar->setValue(_scrollBar->value() + yMouseScroll); // scrollforward
+    }
+  if (pos.y() == tLy + _topMargin) {
+      _scrollBar->setValue(_scrollBar->value() - yMouseScroll); // scrollback
+    }
+
+  int charColumn = 0;
+  int charLine = 0;
+  getCharacterPosition(pos, charLine, charColumn);
+
+  QPoint here = QPoint(charColumn, charLine);
+  QPoint ohere(here);
+  QPoint _iPntSelCorr = _iPntSel;
+  _iPntSelCorr.ry() -= _scrollBar->value();
+  QPoint _pntSelCorr = _pntSel;
+  _pntSelCorr.ry() -= _scrollBar->value();
+  bool swapping = false;
+
+  if (_wordSelectionMode) {
+      // Extend to word boundaries
+      int i = 0;
+      int selClass = 0;
+
+      bool left_not_right = (here.y() < _iPntSelCorr.y() ||
+                             (here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x()));
+      bool old_left_not_right = (_pntSelCorr.y() < _iPntSelCorr.y() ||
+                                 (_pntSelCorr.y() == _iPntSelCorr.y() && _pntSelCorr.x() < _iPntSelCorr.x()));
+      swapping = left_not_right != old_left_not_right;
+
+      // Find left (left_not_right ? from here : from start)
+      QPoint left = left_not_right ? here : _iPntSelCorr;
+      i = loc(left.x(), left.y());
+      if (i >= 0 && i <= _imageSize) {
+          selClass = charClass(_image[i].character);
+          while (((left.x() > 0) || (left.y() > 0 && (_lineProperties[left.y() - 1] & LINE_WRAPPED)))
+                 && charClass(_image[i - 1].character) == selClass) {
+              i--;
+              if (left.x() > 0) {
+                  left.rx()--;
+                } else {
+                  left.rx() = _usedColumns - 1;
+                  left.ry()--;
+                }
+            }
+        }
+
+      // Find left (left_not_right ? from start : from here)
+      QPoint right = left_not_right ? _iPntSelCorr : here;
+      i = loc(right.x(), right.y());
+      if (i >= 0 && i <= _imageSize) {
+          selClass = charClass(_image[i].character);
+          while (((right.x() < _usedColumns - 1) || (right.y() < _usedLines - 1 && (_lineProperties[right.y()] & LINE_WRAPPED)))
+                 && charClass(_image[i + 1].character) == selClass) {
+              i++;
+              if (right.x() < _usedColumns - 1) {
+                  right.rx()++;
+                } else {
+                  right.rx() = 0;
+                  right.ry()++;
+                }
+            }
+        }
+
+      // Pick which is start (ohere) and which is extension (here)
+      if (left_not_right) {
+          here = left;
+          ohere = right;
+        } else {
+          here = right;
+          ohere = left;
+        }
+      ohere.rx()++;
+    }
+
+  if (_lineSelectionMode) {
+      // Extend to complete line
+      bool above_not_below = (here.y() < _iPntSelCorr.y());
+
+      QPoint above = above_not_below ? here : _iPntSelCorr;
+      QPoint below = above_not_below ? _iPntSelCorr : here;
+
+      while (above.y() > 0 && (_lineProperties[above.y() - 1] & LINE_WRAPPED)) {
+          above.ry()--;
+        }
+      while (below.y() < _usedLines - 1 && (_lineProperties[below.y()] & LINE_WRAPPED)) {
+          below.ry()++;
+        }
+
+      above.setX(0);
+      below.setX(_usedColumns - 1);
+
+      // Pick which is start (ohere) and which is extension (here)
+      if (above_not_below) {
+          here = above;
+          ohere = below;
+        } else {
+          here = below;
+          ohere = above;
+        }
+
+      QPoint newSelBegin = QPoint(ohere.x(), ohere.y());
+      swapping = !(_tripleSelBegin == newSelBegin);
+      _tripleSelBegin = newSelBegin;
+
+      ohere.rx()++;
+    }
+
+  int offset = 0;
+  if (!_wordSelectionMode && !_lineSelectionMode) {
+      int i = 0;
+      int selClass = 0;
+
+      bool left_not_right = (here.y() < _iPntSelCorr.y() ||
+                             (here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x()));
+      bool old_left_not_right = (_pntSelCorr.y() < _iPntSelCorr.y() ||
+                                 (_pntSelCorr.y() == _iPntSelCorr.y() && _pntSelCorr.x() < _iPntSelCorr.x()));
+      swapping = left_not_right != old_left_not_right;
+
+      // Find left (left_not_right ? from here : from start)
+      QPoint left = left_not_right ? here : _iPntSelCorr;
+
+      // Find left (left_not_right ? from start : from here)
+      QPoint right = left_not_right ? _iPntSelCorr : here;
+      if (right.x() > 0 && !_columnSelectionMode) {
+          i = loc(right.x(), right.y());
+          if (i >= 0 && i <= _imageSize) {
+              selClass = charClass(_image[i - 1].character);
+              if (selClass == ' ') {
+                  while (right.x() < _usedColumns - 1 && charClass(_image[i + 1].character) == selClass && (right.y() < _usedLines - 1) &&
+                         !(_lineProperties[right.y()] & LINE_WRAPPED)) {
+                      i++;
+                      right.rx()++;
+                    }
+                  if (right.x() < _usedColumns - 1) {
+                      right = left_not_right ? _iPntSelCorr : here;
+                    } else {
+                      right.rx()++;  // will be balanced later because of offset=-1;
+                    }
+                }
+            }
+        }
+
+      // Pick which is start (ohere) and which is extension (here)
+      if (left_not_right) {
+          here = left;
+          ohere = right;
+          offset = 0;
+        } else {
+          here = right;
+          ohere = left;
+          offset = -1;
+        }
+    }
+
+  if ((here == _pntSelCorr) && (scroll == _scrollBar->value())) {
+      return; // not moved
+    }
+
+  if (here == ohere) {
+      return; // It's not left, it's not right.
+    }
+
+  if (_actSel < 2 || swapping) {
+      if (_columnSelectionMode && !_lineSelectionMode && !_wordSelectionMode) {
+          _screenWindow->setSelectionStart(ohere.x(), ohere.y(), true);
+        } else {
+          _screenWindow->setSelectionStart(ohere.x() - 1 - offset , ohere.y(), false);
+        }
+
+    }
+
+  _actSel = 2; // within selection
+  _pntSel = here;
+  _pntSel.ry() += _scrollBar->value();
+
+  if (_columnSelectionMode && !_lineSelectionMode && !_wordSelectionMode) {
+      _screenWindow->setSelectionEnd(here.x(), here.y());
+    } else {
+      _screenWindow->setSelectionEnd(here.x() + offset, here.y());
+    }
+}
+
+void TerminalView::mouseReleaseEvent(QMouseEvent* ev)
+{
+  if ( !_screenWindow )
+    return;
+
+  int charLine;
+  int charColumn;
+  getCharacterPosition(ev->pos(),charLine,charColumn);
+
+  if ( ev->button() == Qt::LeftButton)
+    {
+      emit isBusySelecting(false);
+      if(dragInfo.state == diPending)
+        {
+          // We had a drag event pending but never confirmed.  Kill selection
+          _screenWindow->clearSelection();
+          //emit clearSelectionSignal();
+        }
+      else
+        {
+          if ( _actSel > 1 )
+            {
+              setSelection(  _screenWindow->selectedText(_preserveLineBreaks)  );
+            }
+
+          _actSel = 0;
+
+          //FIXME: emits a release event even if the mouse is
+          //       outside the range. The procedure used in `mouseMoveEvent'
+          //       applies here, too.
+
+          if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier))
+            emit mouseSignal( 3, // release
+                              charColumn + 1,
+                              charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , 0);
+        }
+      dragInfo.state = diNone;
+    }
+
+
+  if ( !_mouseMarks &&
+       ((ev->button() == Qt::RightButton && !(ev->modifiers() & Qt::ShiftModifier))
+        || ev->button() == Qt::MidButton) )
+    {
+      emit mouseSignal( 3,
+                        charColumn + 1,
+                        charLine + 1 +_scrollBar->value() -_scrollBar->maximum() ,
+                        0);
+    }
+
+  QWidget::mouseReleaseEvent(ev);
+}
+
+void TerminalView::getCharacterPosition(const QPoint& widgetPoint,int& line,int& column) const
+{
+
+  column = (widgetPoint.x() + _fontWidth/2 -contentsRect().left()-_leftMargin) / _fontWidth;
+  line = (widgetPoint.y()-contentsRect().top()-_topMargin) / _fontHeight;
+
+  if ( line < 0 )
+    line = 0;
+  if ( column < 0 )
+    column = 0;
+
+  if ( line >= _usedLines )
+    line = _usedLines-1;
+
+  // the column value returned can be equal to _usedColumns, which
+  // is the position just after the last character displayed in a line.
+  //
+  // this is required so that the user can select characters in the right-most
+  // column (or left-most for right-to-left input)
+  if ( column > _usedColumns )
+    column = _usedColumns;
+}
+
+void TerminalView::updateLineProperties()
+{
+  if ( !_screenWindow )
+    return;
+
+  _lineProperties = _screenWindow->getLineProperties();
+}
+
+void TerminalView::mouseDoubleClickEvent(QMouseEvent* ev)
+{
+  if ( ev->button() != Qt::LeftButton) return;
+  if ( !_screenWindow ) return;
+
+  int charLine = 0;
+  int charColumn = 0;
+
+  getCharacterPosition(ev->pos(),charLine,charColumn);
+
+  QPoint pos(charColumn,charLine);
+
+  // pass on double click as two clicks.
+  if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier))
+    {
+      // Send just _ONE_ click event, since the first click of the double click
+      // was already sent by the click handler
+      emit mouseSignal( 0,
+                        pos.x()+1,
+                        pos.y()+1 +_scrollBar->value() -_scrollBar->maximum(),
+                        0 ); // left button
+      return;
+    }
+
+  _screenWindow->clearSelection();
+  QPoint bgnSel = pos;
+  QPoint endSel = pos;
+  int i = loc(bgnSel.x(),bgnSel.y());
+  _iPntSel = bgnSel;
+  _iPntSel.ry() += _scrollBar->value();
+
+  _wordSelectionMode = true;
+
+  // find word boundaries...
+  int selClass = charClass(_image[i].character);
+  {
+    // find the start of the word
+    int x = bgnSel.x();
+    while ( ((x>0) || (bgnSel.y()>0 && (_lineProperties[bgnSel.y()-1] & LINE_WRAPPED) ))
+            && charClass(_image[i-1].character) == selClass )
+      {
+        i--;
+        if (x>0)
+          x--;
+        else
+          {
+            x=_usedColumns-1;
+            bgnSel.ry()--;
+          }
+      }
+
+    bgnSel.setX(x);
+    _screenWindow->setSelectionStart( bgnSel.x() , bgnSel.y() , false );
+
+    // find the end of the word
+    i = loc( endSel.x(), endSel.y() );
+    x = endSel.x();
+    while( ((x<_usedColumns-1) || (endSel.y()<_usedLines-1 && (_lineProperties[endSel.y()] & LINE_WRAPPED) ))
+           && charClass(_image[i+1].character) == selClass )
+      {
+        i++;
+        if (x<_usedColumns-1)
+          x++;
+        else
+          {
+            x=0;
+            endSel.ry()++;
+          }
+      }
+
+    endSel.setX(x);
+
+    // In word selection mode don't select @ (64) if at end of word.
+    if ( ( QChar( _image[i].character ) == '@' ) && ( ( endSel.x() - bgnSel.x() ) > 0 ) )
+      endSel.setX( x - 1 );
+
+
+    _actSel = 2; // within selection
+
+    _screenWindow->setSelectionEnd( endSel.x() , endSel.y() );
+
+    setSelection( _screenWindow->selectedText(_preserveLineBreaks) );
+  }
+
+  _possibleTripleClick=true;
+
+  QTimer::singleShot(QApplication::doubleClickInterval(),this,
+                     SLOT(tripleClickTimeout()));
+}
+
+void TerminalView::wheelEvent( QWheelEvent* ev )
+{
+  if (ev->orientation() != Qt::Vertical)
+    return;
+
+  if ( _mouseMarks )
+    _scrollBar->event(ev);
+  else
+    {
+      int charLine;
+      int charColumn;
+      getCharacterPosition( ev->pos() , charLine , charColumn );
+
+      emit mouseSignal( ev->delta() > 0 ? 4 : 5,
+                        charColumn + 1,
+                        charLine + 1 +_scrollBar->value() -_scrollBar->maximum() ,
+                        0);
+    }
+}
+
+void TerminalView::tripleClickTimeout()
+{
+  _possibleTripleClick=false;
+}
+
+void TerminalView::mouseTripleClickEvent(QMouseEvent* ev)
+{
+  if ( !_screenWindow ) return;
+
+  int charLine;
+  int charColumn;
+  getCharacterPosition(ev->pos(),charLine,charColumn);
+  _iPntSel = QPoint(charColumn,charLine);
+
+  _screenWindow->clearSelection();
+
+  _lineSelectionMode = true;
+  _wordSelectionMode = false;
+
+  _actSel = 2; // within selection
+  emit isBusySelecting(true); // Keep it steady...
+
+  while (_iPntSel.y()>0 && (_lineProperties[_iPntSel.y()-1] & LINE_WRAPPED) )
+    _iPntSel.ry()--;
+
+  if (_tripleClickMode == SelectForwardsFromCursor) {
+      // find word boundary start
+      int i = loc(_iPntSel.x(),_iPntSel.y());
+      int selClass = charClass(_image[i].character);
+      int x = _iPntSel.x();
+
+      while ( ((x>0) ||
+               (_iPntSel.y()>0 && (_lineProperties[_iPntSel.y()-1] & LINE_WRAPPED) )
+               )
+              && charClass(_image[i-1].character) == selClass )
+        {
+          i--;
+          if (x>0)
+            x--;
+          else
+            {
+              x=_columns-1;
+              _iPntSel.ry()--;
+            }
+        }
+
+      _screenWindow->setSelectionStart( x , _iPntSel.y() , false );
+      _tripleSelBegin = QPoint( x, _iPntSel.y() );
+    }
+  else if (_tripleClickMode == SelectWholeLine) {
+      _screenWindow->setSelectionStart( 0 , _iPntSel.y() , false );
+      _tripleSelBegin = QPoint( 0, _iPntSel.y() );
+    }
+
+  while (_iPntSel.y()<_lines-1 && (_lineProperties[_iPntSel.y()] & LINE_WRAPPED) )
+    _iPntSel.ry()++;
+
+  _screenWindow->setSelectionEnd( _columns - 1 , _iPntSel.y() );
+
+  setSelection(_screenWindow->selectedText(_preserveLineBreaks));
+
+  _iPntSel.ry() += _scrollBar->value();
+
+  emit tripleClicked( _screenWindow->selectedText( _preserveLineBreaks ) );
+}
+
+
+bool TerminalView::focusNextPrevChild( bool next )
+{
+  if (next)
+    return false; // This disables changing the active part in konqueror
+  // when pressing Tab
+  return QWidget::focusNextPrevChild( next );
+}
+
+
+int TerminalView::charClass(quint16 ch) const
+{
+  QChar qch=QChar(ch);
+  if ( qch.isSpace() ) return ' ';
+
+  if ( qch.isLetterOrNumber() || _wordCharacters.contains(qch, Qt::CaseInsensitive ) )
+    return 'a';
+
+  // Everything else is weird
+  return 1;
+}
+
+void TerminalView::setWordCharacters(const QString& wc)
+{
+  _wordCharacters = wc;
+}
+
+void TerminalView::setUsesMouse(bool on)
+{
+  _mouseMarks = on;
+  setCursor( _mouseMarks ? Qt::IBeamCursor : Qt::ArrowCursor );
+}
+bool TerminalView::usesMouse() const
+{
+  return _mouseMarks;
+}
+
+/* ------------------------------------------------------------------------- */
+/*                                                                           */
+/*                               Clipboard                                   */
+/*                                                                           */
+/* ------------------------------------------------------------------------- */
+
+#undef KeyPress
+
+void TerminalView::emitSelection(bool useXselection,bool appendReturn)
+{
+  if ( !_screenWindow )
+    return;
+
+  // Paste Clipboard by simulating keypress events
+  QString text = QApplication::clipboard()->text(useXselection ? QClipboard::Selection :
+                                                                 QClipboard::Clipboard);
+  if(appendReturn)
+    text.append("\r");
+  if ( ! text.isEmpty() )
+    {
+      text.replace("\n", "\r");
+      QKeyEvent e(QEvent::KeyPress, 0, Qt::NoModifier, text);
+      emit keyPressedSignal(&e); // expose as a big fat keypress event
+
+      _screenWindow->clearSelection();
+    }
+}
+
+void TerminalView::setSelection(const QString& t)
+{
+  QApplication::clipboard()->setText(t, QClipboard::Selection);
+}
+
+void TerminalView::copyClipboard()
+{
+  if ( !_screenWindow )
+    return;
+
+  QString text = _screenWindow->selectedText(_preserveLineBreaks);
+  QApplication::clipboard()->setText(text);
+}
+
+void TerminalView::pasteClipboard()
+{
+  emitSelection(false,false);
+}
+
+void TerminalView::pasteSelection()
+{
+  emitSelection(true,false);
+}
+
+/* ------------------------------------------------------------------------- */
+/*                                                                           */
+/*                                Keyboard                                   */
+/*                                                                           */
+/* ------------------------------------------------------------------------- */
+
+void TerminalView::keyPressEvent( QKeyEvent* event )
+{
+  //qDebug("%s %d keyPressEvent and key is %d", __FILE__, __LINE__, event->key());
+
+  bool emitKeyPressSignal = true;
+
+  // Keyboard-based navigation
+  if ( event->modifiers() == Qt::ShiftModifier )
+    {
+      bool update = true;
+
+      if ( event->key() == Qt::Key_PageUp )
+        {
+          //qDebug("%s %d pageup", __FILE__, __LINE__);
+          _screenWindow->scrollBy( ScreenWindow::ScrollPages , -1 );
+        }
+      else if ( event->key() == Qt::Key_PageDown )
+        {
+          //qDebug("%s %d pagedown", __FILE__, __LINE__);
+          _screenWindow->scrollBy( ScreenWindow::ScrollPages , 1 );
+        }
+      else if ( event->key() == Qt::Key_Up )
+        {
+          //qDebug("%s %d keyup", __FILE__, __LINE__);
+          _screenWindow->scrollBy( ScreenWindow::ScrollLines , -1 );
+        }
+      else if ( event->key() == Qt::Key_Down )
+        {
+          //qDebug("%s %d keydown", __FILE__, __LINE__);
+          _screenWindow->scrollBy( ScreenWindow::ScrollLines , 1 );
+        }
+      else {
+          update = false;
+        }
+
+      if ( update )
+        {
+          //qDebug("%s %d updating", __FILE__, __LINE__);
+          _screenWindow->setTrackOutput( _screenWindow->atEndOfOutput() );
+
+          updateLineProperties();
+          updateImage();
+
+          // do not send key press to terminal
+          emitKeyPressSignal = false;
+        }
+    }
+
+  _screenWindow->setTrackOutput( true );
+
+  _actSel=0; // Key stroke implies a screen update, so TerminalDisplay won't
+  // know where the current selection is.
+
+  if (_hasBlinkingCursor)
+    {
+      _blinkCursorTimer->start(BLINK_DELAY);
+      if (_cursorBlinking)
+        blinkCursorEvent();
+      else
+        _cursorBlinking = false;
+    }
+
+  if ( emitKeyPressSignal && !_readonly )
+    emit keyPressedSignal(event);
+
+  if (_readonly) {
+      event->ignore();
+    }
+  else {
+      event->accept();
+    }
+}
+
+void TerminalView::inputMethodEvent( QInputMethodEvent* event )
+{
+  QKeyEvent keyEvent(QEvent::KeyPress,0,Qt::NoModifier,event->commitString());
+  emit keyPressedSignal(&keyEvent);
+
+  _inputMethodData.preeditString = event->preeditString();
+  update(preeditRect() | _inputMethodData.previousPreeditRect);
+
+  event->accept();
+}
+QVariant TerminalView::inputMethodQuery( Qt::InputMethodQuery query ) const
+{
+  const QPoint cursorPos = _screenWindow ? _screenWindow->cursorPosition() : QPoint(0,0);
+  switch ( query )
+    {
+    case Qt::ImMicroFocus:
+      return imageToWidget(QRect(cursorPos.x(),cursorPos.y(),1,1));
+      break;
+    case Qt::ImFont:
+      return font();
+      break;
+    case Qt::ImCursorPosition:
+      // return the cursor position within the current line
+      return cursorPos.x();
+      break;
+    case Qt::ImSurroundingText:
+      {
+        // return the text from the current line
+        QString lineText;
+        QTextStream stream(&lineText);
+        PlainTextDecoder decoder;
+        decoder.begin(&stream);
+        decoder.decodeLine(&_image[loc(0,cursorPos.y())],_usedColumns,_lineProperties[cursorPos.y()]);
+        decoder.end();
+        return lineText;
+      }
+      break;
+    case Qt::ImCurrentSelection:
+      return QString();
+      break;
+    default:
+      break;
+    }
+
+  return QVariant();
+}
+
+bool TerminalView::event( QEvent *e )
+{
+  if ( e->type() == QEvent::ShortcutOverride )
+    {
+      QKeyEvent* keyEvent = static_cast<QKeyEvent *>( e );
+
+      // a check to see if keyEvent->text() is empty is used
+      // to avoid intercepting the press of the modifier key on its own.
+      //
+      // this is important as it allows a press and release of the Alt key
+      // on its own to focus the menu bar, making it possible to
+      // work with the menu without using the mouse
+      if ( (keyEvent->modifiers() == Qt::AltModifier) &&
+           !keyEvent->text().isEmpty() )
+        {
+          keyEvent->accept();
+          return true;
+        }
+
+      // Override any of the following shortcuts because
+      // they are needed by the terminal
+      int keyCode = keyEvent->key() | keyEvent->modifiers();
+      switch ( keyCode )
+        {
+        // list is taken from the QLineEdit::event() code
+        case Qt::Key_Tab:
+        case Qt::Key_Delete:
+        case Qt::Key_Home:
+        case Qt::Key_End:
+        case Qt::Key_Backspace:
+        case Qt::Key_Left:
+        case Qt::Key_Right:
+          keyEvent->accept();
+          return true;
+        }
+    }
+  return QWidget::event( e );
+}
+
+void TerminalView::setBellMode(int mode)
+{
+  _bellMode=mode;
+}
+
+void TerminalView::enableBell()
+{
+  _allowBell = true;
+}
+
+void TerminalView::swapColorTable()
+{
+  ColorEntry color = _colorTable[1];
+  _colorTable[1]=_colorTable[0];
+  _colorTable[0]= color;
+  _colorsInverted = !_colorsInverted;
+  update();
+}
+
+void TerminalView::clearImage()
+{
+  // We initialize _image[_imageSize] too. See makeImage()
+  for (int i = 0; i <= _imageSize; i++)
+    {
+      _image[i].character = ' ';
+      _image[i].foregroundColor = CharacterColor(COLOR_SPACE_DEFAULT,
+                                                 DEFAULT_FORE_COLOR);
+      _image[i].backgroundColor = CharacterColor(COLOR_SPACE_DEFAULT,
+                                                 DEFAULT_BACK_COLOR);
+      _image[i].rendition = DEFAULT_RENDITION;
+    }
+}
+
+void TerminalView::calcGeometry()
+{
+  _scrollBar->resize(QApplication::style()->pixelMetric(QStyle::PM_ScrollBarExtent),
+                     contentsRect().height());
+  switch(_scrollbarLocation)
+    {
+    case NoScrollBar :
+      _leftMargin = DEFAULT_LEFT_MARGIN;
+      _contentWidth = contentsRect().width() - 2 * DEFAULT_LEFT_MARGIN;
+      break;
+    case ScrollBarLeft :
+      _leftMargin = DEFAULT_LEFT_MARGIN + _scrollBar->width();
+      _contentWidth = contentsRect().width() - 2 * DEFAULT_LEFT_MARGIN - _scrollBar->width();
+      _scrollBar->move(contentsRect().topLeft());
+      break;
+    case ScrollBarRight:
+      _leftMargin = DEFAULT_LEFT_MARGIN;
+      _contentWidth = contentsRect().width()  - 2 * DEFAULT_LEFT_MARGIN - _scrollBar->width();
+      _scrollBar->move(contentsRect().topRight() - QPoint(_scrollBar->width()-1,0));
+      break;
+    }
+
+  _topMargin = DEFAULT_TOP_MARGIN;
+  _contentHeight = contentsRect().height() - 2 * DEFAULT_TOP_MARGIN + /* mysterious */ 1;
+
+  if (!_isFixedSize)
+    {
+      // ensure that display is always at least one column wide
+      _columns = qMax(1,qRound(_contentWidth / _fontWidth));
+      _usedColumns = qMin(_usedColumns,_columns);
+
+      // ensure that display is always at least one line high
+      _lines = qMax(1, qRound(_contentHeight / _fontHeight));
+      _usedLines = qMin(_usedLines,_lines);
+    }
+}
+
+void TerminalView::makeImage()
+{
+  //qDebug("%s %d makeImage", __FILE__, __LINE__);
+  calcGeometry();
+
+  // confirm that array will be of non-zero size, since the painting code
+  // assumes a non-zero array length
+  Q_ASSERT( _lines > 0 && _columns > 0 );
+  Q_ASSERT( _usedLines <= _lines && _usedColumns <= _columns );
+
+  _imageSize=_lines*_columns;
+
+  // We over-commit one character so that we can be more relaxed in dealing with
+  // certain boundary conditions: _image[_imageSize] is a valid but unused position
+  _image = new Character[_imageSize+1];
+
+  clearImage();
+}
+
+// calculate the needed size
+void TerminalView::setSize(int columns, int lines)
+{
+  //FIXME - Not quite correct, a small amount of additional space
+  // will be used for margins, the scrollbar etc.
+  // we need to allow for this so that '_size' does allow
+  // enough room for the specified number of columns and lines to fit
+
+  QSize newSize = QSize( columns * _fontWidth  ,
+                         lines * _fontHeight   );
+
+  if ( newSize != size() )
+    {
+      _size = newSize;
+      updateGeometry();
+    }
+}
+
+void TerminalView::setFixedSize(int cols, int lins)
+{
+  _isFixedSize = true;
+
+  //ensure that display is at least one line by one column in size
+  _columns = qMax(1,cols);
+  _lines = qMax(1,lins);
+  _usedColumns = qMin(_usedColumns,_columns);
+  _usedLines = qMin(_usedLines,_lines);
+
+  if (_image)
+    {
+      delete[] _image;
+      makeImage();
+    }
+  setSize(cols, lins);
+  QWidget::setFixedSize(_size);
+}
+
+QSize TerminalView::sizeHint() const
+{
+  return _size;
+}
+
+
+/* --------------------------------------------------------------------- */
+/*                                                                       */
+/* Drag & Drop                                                           */
+/*                                                                       */
+/* --------------------------------------------------------------------- */
+
+void TerminalView::dragEnterEvent(QDragEnterEvent* event)
+{
+  if (event->mimeData()->hasFormat("text/plain"))
+    event->acceptProposedAction();
+}
+
+void TerminalView::dropEvent(QDropEvent* event)
+{
+  //  KUrl::List urls = KUrl::List::fromMimeData(event->mimeData());
+
+  QString dropText;
+  /*  if (!urls.isEmpty())
+  {
+    for ( int i = 0 ; i < urls.count() ; i++ )
+    {
+        KUrl url = KIO::NetAccess::mostLocalUrl( urls[i] , 0 );
+        QString urlText;
+
+        if (url.isLocalFile())
+            urlText = url.path();
+        else
+            urlText = url.url();
+
+        // in future it may be useful to be able to insert file names with drag-and-drop
+        // without quoting them (this only affects paths with spaces in)
+        urlText = KShell::quoteArg(urlText);
+
+        dropText += urlText;
+
+        if ( i != urls.count()-1 )
+            dropText += ' ';
+    }
+  }
+  else
+  {
+    dropText = event->mimeData()->text();
+  }
+*/
+  if(event->mimeData()->hasFormat("text/plain"))
+    {
+      emit sendStringToEmu(dropText.toLocal8Bit());
+    }
+}
+
+void TerminalView::doDrag()
+{
+  dragInfo.state = diDragging;
+  dragInfo.dragObject = new QDrag(this);
+  QMimeData *mimeData = new QMimeData;
+  mimeData->setText(QApplication::clipboard()->text(QClipboard::Selection));
+  dragInfo.dragObject->setMimeData(mimeData);
+  dragInfo.dragObject->start(Qt::CopyAction);
+  // Don't delete the QTextDrag object.  Qt will delete it when it's done with it.
+}
+
+void TerminalView::outputSuspended(bool suspended)
+{
+  //create the label when this function is first called
+  if (!_outputSuspendedLabel)
+    {
+      //This label includes a link to an English language website
+      //describing the 'flow control' (Xon/Xoff) feature found in almost
+      //all terminal emulators.
+      //If there isn't a suitable article available in the target language the link
+      //can simply be removed.
+      _outputSuspendedLabel = new QLabel( ("<qt>Output has been "
+                                           "<a href=\"http://en.wikipedia.org/wiki/XON\">suspended</a>"
+                                           " by pressing Ctrl+S."
+                                           "  Press <b>Ctrl+Q</b> to resume.</qt>"),
+                                          this );
+
+      QPalette palette(_outputSuspendedLabel->palette());
+
+      palette.setColor(QPalette::Normal, QPalette::WindowText, QColor(Qt::white));
+      palette.setColor(QPalette::Normal, QPalette::Window, QColor(Qt::black));
+      //            KColorScheme::adjustForeground(palette,KColorScheme::NeutralText);
+      //		KColorScheme::adjustBackground(palette,KColorScheme::NeutralBackground);
+      _outputSuspendedLabel->setPalette(palette);
+      _outputSuspendedLabel->setAutoFillBackground(true);
+      _outputSuspendedLabel->setBackgroundRole(QPalette::Base);
+      _outputSuspendedLabel->setFont(QApplication::font());
+      _outputSuspendedLabel->setMargin(5);
+
+      //enable activation of "Xon/Xoff" link in label
+      _outputSuspendedLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse |
+                                                     Qt::LinksAccessibleByKeyboard);
+      _outputSuspendedLabel->setOpenExternalLinks(true);
+      _outputSuspendedLabel->setVisible(false);
+
+      _gridLayout->addWidget(_outputSuspendedLabel);
+      _gridLayout->addItem( new QSpacerItem(0,0,QSizePolicy::Expanding,
+                                            QSizePolicy::Expanding),
+                            1,0);
+
+    }
+
+  _outputSuspendedLabel->setVisible(suspended);
+}
+
+uint TerminalView::lineSpacing() const
+{
+  return _lineSpacing;
+}
+
+void TerminalView::setLineSpacing(uint i)
+{
+  _lineSpacing = i;
+  setVTFont(font()); // Trigger an update.
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/TerminalView.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,727 @@
+/*
+    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
+    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    Copyright (C) 2012 Jacob Dawid <jacob.dawid@googlemail.com>
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+#ifndef TERMINALVIEW_H
+#define TERMINALVIEW_H
+
+// Qt
+#include <QtGui/QColor>
+#include <QtCore/QPointer>
+#include <QtGui/QWidget>
+
+// Konsole
+#include "unix/Filter.h"
+#include "unix/Character.h"
+
+class QDrag;
+class QDragEnterEvent;
+class QDropEvent;
+class QLabel;
+class QTimer;
+class QEvent;
+class QFrame;
+class QGridLayout;
+class QKeyEvent;
+class QScrollBar;
+class QShowEvent;
+class QHideEvent;
+class QWidget;
+
+extern unsigned short vt100_graphics[32];
+
+class ScreenWindow;
+
+/**
+ * A widget which displays output from a terminal emulation and sends input keypresses and mouse activity
+ * to the terminal.
+ *
+ * When the terminal emulation receives new output from the program running in the terminal,
+ * it will update the display by calling updateImage().
+ *
+ * TODO More documentation
+ */
+class TerminalView : public QWidget
+{
+   Q_OBJECT
+
+public:
+    /** Constructs a new terminal display widget with the specified parent. */
+    TerminalView(QWidget *parent = 0);
+    virtual ~TerminalView();
+
+    /** Returns the terminal color palette used by the display. */
+    const ColorEntry* colorTable() const;
+    /** Sets the terminal color palette used by the display. */
+    void setColorTable(const ColorEntry table[]);
+    /**
+     * Sets the seed used to generate random colors for the display
+     * (in color schemes that support them).
+     */
+    void setRandomSeed(uint seed);
+    /**
+     * Returns the seed used to generate random colors for the display
+     * (in color schemes that support them).
+     */
+    uint randomSeed() const;
+
+
+    /**
+     * This enum describes the location where the scroll bar is positioned in the display widget.
+     */
+    enum ScrollBarPosition
+    {
+        /** Do not show the scroll bar. */
+        NoScrollBar=0,
+        /** Show the scroll bar on the left side of the display. */
+        ScrollBarLeft=1,
+        /** Show the scroll bar on the right side of the display. */
+        ScrollBarRight=2
+    };
+    /**
+     * Specifies whether the terminal display has a vertical scroll bar, and if so whether it
+     * is shown on the left or right side of the display.
+     */
+    void setScrollBarPosition(ScrollBarPosition position);
+
+    /**
+     * Sets the current position and range of the display's scroll bar.
+     *
+     * @param cursor The position of the scroll bar's thumb.
+     * @param lines The maximum value of the scroll bar.
+     */
+    void setScroll(int cursor, int lines);
+
+    /**
+     * Returns the display's filter chain.  When the image for the display is updated,
+     * the text is passed through each filter in the chain.  Each filter can define
+     * hotspots which correspond to certain strings (such as URLs or particular words).
+     * Depending on the type of the hotspots created by the filter ( returned by Filter::Hotspot::type() )
+     * the view will draw visual cues such as underlines on mouse-over for links or translucent
+     * rectangles for markers.
+     *
+     * To add a new filter to the view, call:
+     *      viewWidget->filterChain()->addFilter( filterObject );
+     */
+    FilterChain* filterChain() const;
+
+    /**
+     * Updates the filters in the display's filter chain.  This will cause
+     * the hotspots to be updated to match the current image.
+     *
+     * WARNING:  This function can be expensive depending on the
+     * image size and number of filters in the filterChain()
+     *
+     * TODO - This API does not really allow efficient usage.  Revise it so
+     * that the processing can be done in a better way.
+     *
+     * eg:
+     *      - Area of interest may be known ( eg. mouse cursor hovering
+     *      over an area )
+     */
+    void processFilters();
+
+    /**
+     * Returns a list of menu actions created by the filters for the content
+     * at the given @p position.
+     */
+    QList<QAction*> filterActions(const QPoint& position);
+
+    /** Returns true if the cursor is set to blink or false otherwise. */
+    bool blinkingCursor() { return _hasBlinkingCursor; }
+    /** Specifies whether or not the cursor blinks. */
+    void setBlinkingCursor(bool blink);
+
+    void setCtrlDrag(bool enable) { _ctrlDrag=enable; }
+    bool ctrlDrag() { return _ctrlDrag; }
+
+   /**
+     *  This enum describes the methods for selecting text when
+    *  the user triple-clicks within the display.
+    */
+   enum TripleClickMode
+   {
+      /** Select the whole line underneath the cursor. */
+      SelectWholeLine,
+      /** Select from the current cursor position to the end of the line. */
+      SelectForwardsFromCursor
+   };
+    /** Sets how the text is selected when the user triple clicks within the display. */
+    void setTripleClickMode(TripleClickMode mode) { _tripleClickMode = mode; }
+   /** See setTripleClickSelectionMode() */
+    TripleClickMode tripleClickMode() { return _tripleClickMode; }
+
+    void setLineSpacing(uint);
+    uint lineSpacing() const;
+
+    void emitSelection(bool useXselection,bool appendReturn);
+
+    /**
+     * This enum describes the available shapes for the keyboard cursor.
+     * See setKeyboardCursorShape()
+     */
+    enum KeyboardCursorShape
+    {
+        /** A rectangular block which covers the entire area of the cursor character. */
+        BlockCursor,
+        /**
+         * A single flat line which occupies the space at the bottom of the cursor
+         * character's area.
+         */
+        UnderlineCursor,
+        /**
+         * An cursor shaped like the capital letter 'I', similar to the IBeam
+         * cursor used in Qt/KDE text editors.
+         */
+        IBeamCursor
+    };
+    /**
+     * Sets the shape of the keyboard cursor.  This is the cursor drawn
+     * at the position in the terminal where keyboard input will appear.
+     *
+     * In addition the terminal display widget also has a cursor for
+     * the mouse pointer, which can be set using the QWidget::setCursor()
+     * method.
+     *
+     * Defaults to BlockCursor
+     */
+    void setKeyboardCursorShape(KeyboardCursorShape shape);
+    /**
+     * Returns the shape of the keyboard cursor.  See setKeyboardCursorShape()
+     */
+    KeyboardCursorShape keyboardCursorShape() const;
+
+    /**
+     * Sets the color used to draw the keyboard cursor.
+     *
+     * The keyboard cursor defaults to using the foreground color of the character
+     * underneath it.
+     *
+     * @param useForegroundColor If true, the cursor color will change to match
+     * the foreground color of the character underneath it as it is moved, in this
+     * case, the @p color parameter is ignored and the color of the character
+     * under the cursor is inverted to ensure that it is still readable.
+     * @param color The color to use to draw the cursor.  This is only taken into
+     * account if @p useForegroundColor is false.
+     */
+    void setKeyboardCursorColor(bool useForegroundColor , const QColor& color);
+
+    /**
+     * Returns the color of the keyboard cursor, or an invalid color if the keyboard
+     * cursor color is set to change according to the foreground color of the character
+     * underneath it.
+     */
+    QColor keyboardCursorColor() const;
+
+    /**
+     * Returns the number of lines of text which can be displayed in the widget.
+     *
+     * This will depend upon the height of the widget and the current font.
+     * See fontHeight()
+     */
+    int  lines()   { return _lines;   }
+    /**
+     * Returns the number of characters of text which can be displayed on
+     * each line in the widget.
+     *
+     * This will depend upon the width of the widget and the current font.
+     * See fontWidth()
+     */
+    int  columns() { return _columns; }
+
+    /**
+     * Returns the height of the characters in the font used to draw the text in the display.
+     */
+    int  fontHeight()   { return _fontHeight;   }
+    /**
+     * Returns the width of the characters in the display.
+     * This assumes the use of a fixed-width font.
+     */
+    int  fontWidth()    { return _fontWidth; }
+
+    void setSize(int cols, int lins);
+    void setFixedSize(int cols, int lins);
+
+    // reimplemented
+    QSize sizeHint() const;
+
+    /**
+     * Sets which characters, in addition to letters and numbers,
+     * are regarded as being part of a word for the purposes
+     * of selecting words in the display by double clicking on them.
+     *
+     * The word boundaries occur at the first and last characters which
+     * are either a letter, number, or a character in @p wc
+     *
+     * @param wc An array of characters which are to be considered parts
+     * of a word ( in addition to letters and numbers ).
+     */
+    void setWordCharacters(const QString& wc);
+    /**
+     * Returns the characters which are considered part of a word for the
+     * purpose of selecting words in the display with the mouse.
+     *
+     * @see setWordCharacters()
+     */
+    QString wordCharacters() { return _wordCharacters; }
+
+    /**
+     * Sets the type of effect used to alert the user when a 'bell' occurs in the
+     * terminal session.
+     *
+     * The terminal session can trigger the bell effect by calling bell() with
+     * the alert message.
+     */
+    void setBellMode(int mode);
+    /**
+     * Returns the type of effect used to alert the user when a 'bell' occurs in
+     * the terminal session.
+     *
+     * See setBellMode()
+     */
+    int bellMode() { return _bellMode; }
+
+    /**
+     * This enum describes the different types of sounds and visual effects which
+     * can be used to alert the user when a 'bell' occurs in the terminal
+     * session.
+     */
+    enum BellMode
+    {
+        /** A system beep. */
+        SystemBeepBell=0,
+        /**
+         * KDE notification.  This may play a sound, show a passive popup
+         * or perform some other action depending on the user's settings.
+         */
+        NotifyBell=1,
+        /** A silent, visual bell (eg. inverting the display's colors briefly) */
+        VisualBell=2,
+        /** No bell effects */
+        NoBell=3
+    };
+
+    void setSelection(const QString &t);
+
+    /**
+     * Reimplemented.  Has no effect.  Use setVTFont() to change the font
+     * used to draw characters in the display.
+     */
+    virtual void setFont(const QFont &);
+
+
+    /** Returns the font used to draw characters in the display */
+    QFont getVTFont() { return font(); }
+
+    /**
+     * Sets the font used to draw the display.  Has no effect if @p font
+     * is larger than the size of the display itself.
+     */
+    void setVTFont(const QFont& font);
+
+
+    /**
+     * Specified whether terminal widget should be at read-only mode
+     * Defaults to false.
+     */
+    void setReadOnly( bool readonly) { _readonly = readonly; }
+
+    /**
+     * Specified whether anti-aliasing of text in the terminal display
+     * is enabled or not.  Defaults to enabled.
+     */
+    static void setAntialias( bool antialias ) { _antialiasText = antialias; }
+    /**
+     * Returns true if anti-aliasing of text in the terminal is enabled.
+     */
+    static bool antialias()                 { return _antialiasText;   }
+
+    /**
+     * Sets whether or not the current height and width of the
+     * terminal in lines and columns is displayed whilst the widget
+     * is being resized.
+     */
+    void setTerminalSizeHint(bool on) { _terminalSizeHint=on; }
+    /**
+     * Returns whether or not the current height and width of
+     * the terminal in lines and columns is displayed whilst the widget
+     * is being resized.
+     */
+    bool terminalSizeHint() { return _terminalSizeHint; }
+    /**
+     * Sets whether the terminal size display is shown briefly
+     * after the widget is first shown.
+     *
+     * See setTerminalSizeHint() , isTerminalSizeHint()
+     */
+    void setTerminalSizeStartup(bool on) { _terminalSizeStartup=on; }
+
+    /**
+     * Sets the terminal screen section which is displayed in this widget.
+     * When updateImage() is called, the display fetches the latest character image from the
+     * the associated terminal screen window.
+     *
+     * In terms of the model-view paradigm, the ScreenWindow is the model which is rendered
+     * by the TerminalDisplay.
+     */
+    void setScreenWindow( ScreenWindow* window );
+    /** Returns the terminal screen section which is displayed in this widget.  See setScreenWindow() */
+    ScreenWindow* screenWindow() const;
+
+public slots:
+
+    /**
+     * Causes the terminal display to fetch the latest character image from the associated
+     * terminal screen ( see setScreenWindow() ) and redraw the display.
+     */
+    void updateImage();
+    /**
+     * Causes the terminal display to fetch the latest line status flags from the
+     * associated terminal screen ( see setScreenWindow() ).
+     */
+    void updateLineProperties();
+
+    /** Copies the selected text to the clipboard. */
+    void copyClipboard();
+    /**
+     * Pastes the content of the clipboard into the
+     * display.
+     */
+    void pasteClipboard();
+    /**
+     * Pastes the content of the selection into the
+     * display.
+     */
+    void pasteSelection();
+
+	 /**
+	 * Causes the widget to display or hide a message informing the user that terminal
+	 * output has been suspended (by using the flow control key combination Ctrl+S)
+	 *
+	 * @param suspended True if terminal output has been suspended and the warning message should
+	 *				 	be shown or false to indicate that terminal output has been resumed and that
+	 *				 	the warning message should disappear.
+	 */
+	void outputSuspended(bool suspended);
+
+    /**
+     * Sets whether the program whoose output is being displayed in the view
+     * is interested in mouse events.
+     *
+     * If this is set to true, mouse signals will be emitted by the view when the user clicks, drags
+     * or otherwise moves the mouse inside the view.
+     * The user interaction needed to create selections will also change, and the user will be required
+     * to hold down the shift key to create a selection or perform other mouse activities inside the
+     * view area - since the program running in the terminal is being allowed to handle normal mouse
+     * events itself.
+     *
+     * @param usesMouse Set to true if the program running in the terminal is interested in mouse events
+     * or false otherwise.
+     */
+    void setUsesMouse(bool usesMouse);
+
+    /** See setUsesMouse() */
+    bool usesMouse() const;
+
+signals:
+
+    /**
+     * Emitted when the user presses a key whilst the terminal widget has focus.
+     */
+    void keyPressedSignal(QKeyEvent *e);
+
+    /**
+     * A mouse event occurred.
+     * @param button The mouse button (0 for left button, 1 for middle button, 2 for right button, 3 for release)
+     * @param column The character column where the event occurred
+     * @param line The character row where the event occurred
+     * @param eventType The type of event.  0 for a mouse press / release or 1 for mouse motion
+     */
+    void mouseSignal(int button, int column, int line, int eventType);
+    void changedFontMetricSignal(int height, int width);
+    void changedContentSizeSignal(int height, int width);
+
+    /**
+     * Emitted when the user right clicks on the display, or right-clicks with the Shift
+     * key held down if usesMouse() is true.
+     *
+     * This can be used to display a context menu.
+     */
+    void configureRequest( TerminalView*, int state, const QPoint& position );
+
+   void isBusySelecting(bool);
+   void sendStringToEmu(const char*);
+
+   void tripleClicked( const QString& text );
+
+protected:
+    virtual bool event( QEvent * );
+
+    virtual void paintEvent( QPaintEvent * );
+
+    virtual void showEvent(QShowEvent*);
+    virtual void hideEvent(QHideEvent*);
+    virtual void resizeEvent(QResizeEvent*);
+
+    virtual void fontChange(const QFont &font);
+
+    virtual void keyPressEvent(QKeyEvent* event);
+    virtual void mouseDoubleClickEvent(QMouseEvent* ev);
+    virtual void mousePressEvent( QMouseEvent* );
+    virtual void mouseReleaseEvent( QMouseEvent* );
+    virtual void mouseMoveEvent( QMouseEvent* );
+    virtual void extendSelection( const QPoint& pos );
+    virtual void wheelEvent( QWheelEvent* );
+
+    virtual bool focusNextPrevChild( bool next );
+
+    // drag and drop
+    virtual void dragEnterEvent(QDragEnterEvent* event);
+    virtual void dropEvent(QDropEvent* event);
+    void doDrag();
+    enum DragState { diNone, diPending, diDragging };
+
+    struct _dragInfo {
+      DragState       state;
+      QPoint          start;
+      QDrag           *dragObject;
+    } dragInfo;
+
+    virtual int charClass(quint16) const;
+
+    void clearImage();
+
+    void mouseTripleClickEvent(QMouseEvent* ev);
+
+    // reimplemented
+    virtual void inputMethodEvent ( QInputMethodEvent* event );
+    virtual QVariant inputMethodQuery( Qt::InputMethodQuery query ) const;
+
+protected slots:
+
+    void scrollBarPositionChanged(int value);
+    void blinkEvent();
+    void blinkCursorEvent();
+
+    //Renables bell noises and visuals.  Used to disable further bells for a short period of time
+    //after emitting the first in a sequence of bell events.
+    void enableBell();
+
+private slots:
+
+    void swapColorTable();
+    void tripleClickTimeout();  // resets possibleTripleClick
+
+private:
+
+    // -- Drawing helpers --
+
+    // divides the part of the display specified by 'rect' into
+    // fragments according to their colors and styles and calls
+    // drawTextFragment() to draw the fragments
+    void drawContents(QPainter &paint, const QRect &rect);
+    // draws a section of text, all the text in this section
+    // has a common color and style
+    void drawTextFragment(QPainter& painter, const QRect& rect,
+                          const QString& text, const Character* style);
+    // draws the background for a text fragment
+    // if useOpacitySetting is true then the color's alpha value will be set to
+    // the display's transparency (set with setOpacity()), otherwise the background
+    // will be drawn fully opaque
+    void drawBackground(QPainter& painter, const QRect& rect, const QColor& color);
+    // draws the cursor character
+    void drawCursor(QPainter& painter, const QRect& rect , const QColor& foregroundColor,
+                                       const QColor& backgroundColor , bool& invertColors);
+    // draws the characters or line graphics in a text fragment
+    void drawCharacters(QPainter& painter, const QRect& rect,  const QString& text,
+                                           const Character* style, bool invertCharacterColor);
+    // draws a string of line graphics
+   void drawLineCharString(QPainter& painter, int x, int y,
+                            const QString& str, const Character* attributes);
+
+    // draws the preedit string for input methods
+    void drawInputMethodPreeditString(QPainter& painter , const QRect& rect);
+
+    // --
+
+    // maps an area in the character image to an area on the widget
+    QRect imageToWidget(const QRect& imageArea) const;
+
+    // maps a point on the widget to the position ( ie. line and column )
+    // of the character at that point.
+    void getCharacterPosition(const QPoint& widgetPoint,int& line,int& column) const;
+
+    // the area where the preedit string for input methods will be draw
+    QRect preeditRect() const;
+
+    // shows a notification window in the middle of the widget indicating the terminal's
+    // current size in columns and lines
+    void showResizeNotification();
+
+    // scrolls the image by a number of lines.
+    // 'lines' may be positive ( to scroll the image down )
+    // or negative ( to scroll the image up )
+    // 'region' is the part of the image to scroll - currently only
+    // the top, bottom and height of 'region' are taken into account,
+    // the left and right are ignored.
+    void scrollImage(int lines , const QRect& region);
+
+    void calcGeometry();
+    void propagateSize();
+    void updateImageSize();
+    void makeImage();
+
+    void paintFilters(QPainter& painter);
+
+	// returns a region covering all of the areas of the widget which contain
+	// a hotspot
+	QRegion hotSpotRegion() const;
+
+	// returns the position of the cursor in columns and lines
+	QPoint cursorPosition() const;
+
+    // the window onto the terminal screen which this display
+    // is currently showing.
+    QPointer<ScreenWindow> _screenWindow;
+
+    bool _allowBell;
+
+    QGridLayout* _gridLayout;
+
+    bool _fixedFont; // has fixed pitch
+
+    double  _fontHeight;     // height
+    double  _fontWidth;     // width
+    //type double to decrease rounding errors
+
+    int  _fontAscent;     // ascend
+
+    int _leftMargin;    // offset
+    int _topMargin;    // offset
+
+    int _lines;      // the number of lines that can be displayed in the widget
+    int _columns;    // the number of columns that can be displayed in the widget
+
+    int _usedLines;  // the number of lines that are actually being used, this will be less
+                    // than 'lines' if the character image provided with setImage() is smaller
+                    // than the maximum image size which can be displayed
+
+    int _usedColumns; // the number of columns that are actually being used, this will be less
+                     // than 'columns' if the character image provided with setImage() is smaller
+                     // than the maximum image size which can be displayed
+
+    int _contentHeight;
+    int _contentWidth;
+    Character* _image; // [lines][columns]
+               // only the area [usedLines][usedColumns] in the image contains valid data
+
+    int _imageSize;
+    QVector<LineProperty> _lineProperties;
+
+    ColorEntry _colorTable[TABLE_COLORS];
+    uint _randomSeed;
+
+    bool _resizing;
+    bool _terminalSizeHint;
+    bool _terminalSizeStartup;
+    bool _mouseMarks;
+
+    QPoint  _iPntSel; // initial selection point
+    QPoint  _pntSel; // current selection point
+    QPoint  _tripleSelBegin; // help avoid flicker
+    int     _actSel; // selection state
+    bool    _wordSelectionMode;
+    bool    _lineSelectionMode;
+    bool    _preserveLineBreaks;
+    bool    _columnSelectionMode;
+
+    QClipboard*  _clipboard;
+    QScrollBar* _scrollBar;
+    ScrollBarPosition _scrollbarLocation;
+    QString     _wordCharacters;
+    int         _bellMode;
+
+    bool _blinking;   // hide text in paintEvent
+    bool _hasBlinker; // has characters to blink
+    bool _cursorBlinking;     // hide cursor in paintEvent
+    bool _hasBlinkingCursor;  // has blinking cursor enabled
+    bool _ctrlDrag;           // require Ctrl key for drag
+    TripleClickMode _tripleClickMode;
+    bool _isFixedSize; //Columns / lines are locked.
+    QTimer* _blinkTimer;  // active when hasBlinker
+    QTimer* _blinkCursorTimer;  // active when hasBlinkingCursor
+
+//    KMenu* _drop;
+    QString _dropText;
+    int _dndFileCount;
+
+    bool _possibleTripleClick;  // is set in mouseDoubleClickEvent and deleted
+                               // after QApplication::doubleClickInterval() delay
+
+
+    QLabel* _resizeWidget;
+    QTimer* _resizeTimer;
+
+   bool _flowControlWarningEnabled;
+
+    //widgets related to the warning message that appears when the user presses Ctrl+S to suspend
+    //terminal output - informing them what has happened and how to resume output
+    QLabel* _outputSuspendedLabel;
+
+    uint _lineSpacing;
+
+    bool _colorsInverted; // true during visual bell
+
+    QSize _size;
+
+    QRgb _blendColor;
+
+    // list of filters currently applied to the display.  used for links and
+    // search highlight
+    TerminalImageFilterChain* _filterChain;
+    QRect _mouseOverHotspotArea;
+
+    KeyboardCursorShape _cursorShape;
+
+    // custom cursor color.  if this is invalid then the foreground
+    // color of the character under the cursor is used
+    QColor _cursorColor;
+
+
+    struct InputMethodData
+    {
+        QString preeditString;
+        QRect previousPreeditRect;
+    };
+    InputMethodData _inputMethodData;
+
+    static bool _antialiasText;   // do we antialias or not
+
+    //the delay in milliseconds between redrawing blinking text
+    static const int BLINK_DELAY = 500;
+   static const int DEFAULT_LEFT_MARGIN = 2;
+   static const int DEFAULT_TOP_MARGIN = 2;
+
+    bool _readonly;
+};
+
+#endif // TERMINALVIEW_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/Vt102Emulation.cpp	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,1261 @@
+/*
+    This file is part of Konsole, an X terminal.
+    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+// Own
+#include "unix/Vt102Emulation.h"
+
+#if defined(__osf__) || defined(__APPLE__)
+#define AVOID_XKB
+#endif
+
+// this allows konsole to be compiled without XKB and XTEST extensions
+// even though it might be available on a particular system.
+#if defined(AVOID_XKB)
+#undef HAVE_XKB
+#endif
+
+// Standard
+#include <stdio.h>
+#include <unistd.h>
+#include <assert.h>
+
+// Qt
+#include <QtCore/QEvent>
+#include <QtGui/QKeyEvent>
+#include <QtCore/QByteRef>
+
+// Konsole
+#include "unix/KeyboardTranslator.h"
+#include "unix/Screen.h"
+
+#if defined(HAVE_XKB)
+void scrolllock_set_off();
+void scrolllock_set_on();
+#endif
+
+
+/* VT102 Terminal Emulation
+
+   This class puts together the screens, the pty and the widget to a
+   complete terminal emulation. Beside combining it's componentes, it
+   handles the emulations's protocol.
+
+   This module consists of the following sections:
+
+   - Constructor/Destructor
+   - Incoming Bytes Event pipeline
+   - Outgoing Bytes
+     - Mouse Events
+     - Keyboard Events
+   - Modes and Charset State
+   - Diagnostics
+*/
+
+/* ------------------------------------------------------------------------- */
+/*                                                                           */
+/*                       Constructor / Destructor                            */
+/*                                                                           */
+/* ------------------------------------------------------------------------- */
+
+
+Vt102Emulation::Vt102Emulation()
+    : Emulation(),
+     _titleUpdateTimer(new QTimer(this))
+{
+  _titleUpdateTimer->setSingleShot(true);
+
+  QObject::connect(_titleUpdateTimer , SIGNAL(timeout()) , this , SLOT(updateTitle()));
+
+  initTokenizer();
+  reset();
+}
+
+Vt102Emulation::~Vt102Emulation()
+{
+}
+
+void Vt102Emulation::clearEntireScreen()
+{
+  _currentScreen->clearEntireScreen();
+
+  bufferedUpdate();
+}
+
+void Vt102Emulation::reset()
+{
+  //kDebug(1211)<<"Vt102Emulation::reset() resetToken()";
+  resetToken();
+  //kDebug(1211)<<"Vt102Emulation::reset() resetModes()";
+  resetModes();
+  //kDebug(1211)<<"Vt102Emulation::reset() resetCharSet()";
+  resetCharset(0);
+  //kDebug(1211)<<"Vt102Emulation::reset() reset screen0()";
+  _screen[0]->reset();
+  //kDebug(1211)<<"Vt102Emulation::reset() resetCharSet()";
+  resetCharset(1);
+  //kDebug(1211)<<"Vt102Emulation::reset() reset _screen 1";
+  _screen[1]->reset();
+  //kDebug(1211)<<"Vt102Emulation::reset() setCodec()";
+  setCodec(LocaleCodec);
+  //kDebug(1211)<<"Vt102Emulation::reset() done";
+
+  bufferedUpdate();
+}
+
+/* ------------------------------------------------------------------------- */
+/*                                                                           */
+/*                     Processing the incoming byte stream                   */
+/*                                                                           */
+/* ------------------------------------------------------------------------- */
+
+/* Incoming Bytes Event pipeline
+
+   This section deals with decoding the incoming character stream.
+   Decoding means here, that the stream is first separated into `tokens'
+   which are then mapped to a `meaning' provided as operations by the
+   `Screen' class or by the emulation class itself.
+
+   The pipeline proceeds as follows:
+
+   - Tokenizing the ESC codes (onReceiveChar)
+   - VT100 code page translation of plain characters (applyCharset)
+   - Interpretation of ESC codes (tau)
+
+   The escape codes and their meaning are described in the
+   technical reference of this program.
+*/
+
+// Tokens ------------------------------------------------------------------ --
+
+/*
+   Since the tokens are the central notion if this section, we've put them
+   in front. They provide the syntactical elements used to represent the
+   terminals operations as byte sequences.
+
+   They are encodes here into a single machine word, so that we can later
+   switch over them easily. Depending on the token itself, additional
+   argument variables are filled with parameter values.
+
+   The tokens are defined below:
+
+   - CHR        - Printable characters     (32..255 but DEL (=127))
+   - CTL        - Control characters       (0..31 but ESC (= 27), DEL)
+   - ESC        - Escape codes of the form <ESC><CHR but `[]()+*#'>
+   - ESC_DE     - Escape codes of the form <ESC><any of `()+*#%'> C
+   - CSI_PN     - Escape codes of the form <ESC>'['     {Pn} ';' {Pn} C
+   - CSI_PS     - Escape codes of the form <ESC>'['     {Pn} ';' ...  C
+   - CSI_PR     - Escape codes of the form <ESC>'[' '?' {Pn} ';' ...  C
+   - CSI_PE     - Escape codes of the form <ESC>'[' '!' {Pn} ';' ...  C
+   - VT52       - VT52 escape codes
+                  - <ESC><Chr>
+                  - <ESC>'Y'{Pc}{Pc}
+   - XTE_HA     - Xterm hacks              <ESC>`]' {Pn} `;' {Text} <BEL>
+                  note that this is handled differently
+
+   The last two forms allow list of arguments. Since the elements of
+   the lists are treated individually the same way, they are passed
+   as individual tokens to the interpretation. Further, because the
+   meaning of the parameters are names (althought represented as numbers),
+   they are includes within the token ('N').
+
+*/
+
+#define TY_CONSTR(T,A,N) ( ((((int)N) & 0xffff) << 16) | ((((int)A) & 0xff) << 8) | (((int)T) & 0xff) )
+
+#define TY_CHR(   )     TY_CONSTR(0,0,0)
+#define TY_CTL(A  )     TY_CONSTR(1,A,0)
+#define TY_ESC(A  )     TY_CONSTR(2,A,0)
+#define TY_ESC_CS(A,B)  TY_CONSTR(3,A,B)
+#define TY_ESC_DE(A  )  TY_CONSTR(4,A,0)
+#define TY_CSI_PS(A,N)  TY_CONSTR(5,A,N)
+#define TY_CSI_PN(A  )  TY_CONSTR(6,A,0)
+#define TY_CSI_PR(A,N)  TY_CONSTR(7,A,N)
+
+#define TY_VT52(A  )    TY_CONSTR(8,A,0)
+
+#define TY_CSI_PG(A  )  TY_CONSTR(9,A,0)
+
+#define TY_CSI_PE(A  )  TY_CONSTR(10,A,0)
+
+// Tokenizer --------------------------------------------------------------- --
+
+/* The tokenizers state
+
+   The state is represented by the buffer (pbuf, ppos),
+   and accompanied by decoded arguments kept in (argv,argc).
+   Note that they are kept internal in the tokenizer.
+*/
+
+void Vt102Emulation::resetToken()
+{
+  ppos = 0; argc = 0; argv[0] = 0; argv[1] = 0;
+}
+
+void Vt102Emulation::addDigit(int dig)
+{
+  argv[argc] = 10*argv[argc] + dig;
+}
+
+void Vt102Emulation::addArgument()
+{
+  argc = qMin(argc+1,MAXARGS-1);
+  argv[argc] = 0;
+}
+
+void Vt102Emulation::pushToToken(int cc)
+{
+  pbuf[ppos] = cc;
+  ppos = qMin(ppos+1,MAXPBUF-1);
+}
+
+// Character Classes used while decoding
+
+#define CTL  1
+#define CHR  2
+#define CPN  4
+#define DIG  8
+#define SCS 16
+#define GRP 32
+#define CPS 64
+
+void Vt102Emulation::initTokenizer()
+{ int i; quint8* s;
+  for(i =  0;                      i < 256; i++) tbl[ i]  = 0;
+  for(i =  0;                      i <  32; i++) tbl[ i] |= CTL;
+  for(i = 32;                      i < 256; i++) tbl[ i] |= CHR;
+  for(s = (quint8*)"@ABCDGHILMPSTXZcdfry"; *s; s++) tbl[*s] |= CPN;
+// resize = \e[8;<row>;<col>t
+  for(s = (quint8*)"t"; *s; s++) tbl[*s] |= CPS;
+  for(s = (quint8*)"0123456789"        ; *s; s++) tbl[*s] |= DIG;
+  for(s = (quint8*)"()+*%"             ; *s; s++) tbl[*s] |= SCS;
+  for(s = (quint8*)"()+*#[]%"          ; *s; s++) tbl[*s] |= GRP;
+  resetToken();
+}
+
+/* Ok, here comes the nasty part of the decoder.
+
+   Instead of keeping an explicit state, we deduce it from the
+   token scanned so far. It is then immediately combined with
+   the current character to form a scanning decision.
+
+   This is done by the following defines.
+
+   - P is the length of the token scanned so far.
+   - L (often P-1) is the position on which contents we base a decision.
+   - C is a character or a group of characters (taken from 'tbl').
+
+   Note that they need to applied in proper order.
+*/
+
+#define lec(P,L,C) (p == (P) &&                     s[(L)]         == (C))
+#define lun(     ) (p ==  1  &&                       cc           >= 32 )
+#define les(P,L,C) (p == (P) && s[L] < 256  && (tbl[s[(L)]] & (C)) == (C))
+#define eec(C)     (p >=  3  &&        cc                          == (C))
+#define ees(C)     (p >=  3  && cc < 256 &&    (tbl[  cc  ] & (C)) == (C))
+#define eps(C)     (p >=  3  && s[2] != '?' && s[2] != '!' && s[2] != '>' && cc < 256 && (tbl[  cc  ] & (C)) == (C))
+#define epp( )     (p >=  3  && s[2] == '?'                              )
+#define epe( )     (p >=  3  && s[2] == '!'                              )
+#define egt(     ) (p >=  3  && s[2] == '>'                              )
+#define Xpe        (ppos>=2  && pbuf[1] == ']'                           )
+#define Xte        (Xpe                        &&     cc           ==  7 )
+#define ces(C)     (            cc < 256 &&    (tbl[  cc  ] & (C)) == (C) && !Xte)
+
+#define ESC 27
+#define CNTL(c) ((c)-'@')
+
+// process an incoming unicode character
+
+void Vt102Emulation::receiveChar(int cc)
+{
+  int i;
+  if (cc == 127) return; //VT100: ignore.
+
+  if (ces(    CTL))
+  { // DEC HACK ALERT! Control Characters are allowed *within* esc sequences in VT100
+    // This means, they do neither a resetToken nor a pushToToken. Some of them, do
+    // of course. Guess this originates from a weakly layered handling of the X-on
+    // X-off protocol, which comes really below this level.
+    if (cc == CNTL('X') || cc == CNTL('Z') || cc == ESC) resetToken(); //VT100: CAN or SUB
+    if (cc != ESC)    { tau( TY_CTL(cc+'@' ),   0,  0); return; }
+  }
+
+  pushToToken(cc); // advance the state
+
+  int* s = pbuf;
+  int  p = ppos;
+
+  if (getMode(MODE_Ansi)) // decide on proper action
+  {
+    if (lec(1,0,ESC)) {                                                       return; }
+    if (lec(1,0,ESC+128)) { s[0] = ESC; receiveChar('[');                   return; }
+    if (les(2,1,GRP)) {                                                       return; }
+    if (Xte         ) { XtermHack();                            resetToken(); return; }
+    if (Xpe         ) {                                                       return; }
+    if (lec(3,2,'?')) {                                                       return; }
+    if (lec(3,2,'>')) {                                                       return; }
+    if (lec(3,2,'!')) {                                                       return; }
+    if (lun(       )) { tau( TY_CHR(), applyCharset(cc), 0); resetToken(); return; }
+    if (lec(2,0,ESC)) { tau( TY_ESC(s[1]),   0,  0);       resetToken(); return; }
+    if (les(3,1,SCS)) { tau( TY_ESC_CS(s[1],s[2]),   0,  0);  resetToken(); return; }
+    if (lec(3,1,'#')) { tau( TY_ESC_DE(s[2]),   0,  0);       resetToken(); return; }
+    if (eps(    CPN)) { tau( TY_CSI_PN(cc), argv[0],argv[1]);   resetToken(); return; }
+
+// resize = \e[8;<row>;<col>t
+    if (eps(    CPS)) { tau( TY_CSI_PS(cc, argv[0]), argv[1], argv[2]);   resetToken(); return; }
+
+    if (epe(       )) { tau( TY_CSI_PE(cc),     0,  0);       resetToken(); return; }
+    if (ees(    DIG)) { addDigit(cc-'0');                                     return; }
+    if (eec(    ';')) { addArgument();                                        return; }
+    for (i=0;i<=argc;i++)
+    if ( epp(     ))  { tau( TY_CSI_PR(cc,argv[i]),   0,  0); }
+    else if(egt(    ))   { tau( TY_CSI_PG(cc     ),   0,  0); } // spec. case for ESC]>0c or ESC]>c
+    else if (cc == 'm' && argc - i >= 4 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 2)
+    { // ESC[ ... 48;2;<red>;<green>;<blue> ... m -or- ESC[ ... 38;2;<red>;<green>;<blue> ... m
+      i += 2;
+      tau( TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_RGB, (argv[i] << 16) | (argv[i+1] << 8) | argv[i+2]);
+      i += 2;
+    }
+    else if (cc == 'm' && argc - i >= 2 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 5)
+    { // ESC[ ... 48;5;<index> ... m -or- ESC[ ... 38;5;<index> ... m
+      i += 2;
+      tau( TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_256, argv[i]);
+    }
+    else              { tau( TY_CSI_PS(cc,argv[i]),   0,  0); }
+    resetToken();
+  }
+  else // mode VT52
+  {
+    if (lec(1,0,ESC))                                                      return;
+    if (les(1,0,CHR)) { tau( TY_CHR(       ), s[0],  0); resetToken(); return; }
+    if (lec(2,1,'Y'))                                                      return;
+    if (lec(3,1,'Y'))                                                      return;
+    if (p < 4)        { tau( TY_VT52(s[1]   ),   0,  0); resetToken(); return; }
+                        tau( TY_VT52(s[1]   ), s[2],s[3]); resetToken(); return;
+  }
+}
+
+void Vt102Emulation::XtermHack()
+{ int i,arg = 0;
+  for (i = 2; i < ppos && '0'<=pbuf[i] && pbuf[i]<'9' ; i++)
+    arg = 10*arg + (pbuf[i]-'0');
+  if (pbuf[i] != ';') { ReportErrorToken(); return; }
+  QChar *str = new QChar[ppos-i-2];
+  for (int j = 0; j < ppos-i-2; j++) str[j] = pbuf[i+1+j];
+  QString unistr(str,ppos-i-2);
+
+  // arg == 1 doesn't change the title. In XTerm it only changes the icon name
+  // (btw: arg=0 changes title and icon, arg=1 only icon, arg=2 only title
+//  emit changeTitle(arg,unistr);
+  _pendingTitleUpdates[arg] = unistr;
+  _titleUpdateTimer->start(20);
+
+  delete [] str;
+}
+
+void Vt102Emulation::updateTitle()
+{
+    QListIterator<int> iter( _pendingTitleUpdates.keys() );
+    while (iter.hasNext()) {
+        int arg = iter.next();
+        emit titleChanged( arg , _pendingTitleUpdates[arg] );
+    }
+
+    _pendingTitleUpdates.clear();
+}
+
+// Interpreting Codes ---------------------------------------------------------
+
+/*
+   Now that the incoming character stream is properly tokenized,
+   meaning is assigned to them. These are either operations of
+   the current _screen, or of the emulation class itself.
+
+   The token to be interpreteted comes in as a machine word
+   possibly accompanied by two parameters.
+
+   Likewise, the operations assigned to, come with up to two
+   arguments. One could consider to make up a proper table
+   from the function below.
+
+   The technical reference manual provides more information
+   about this mapping.
+*/
+
+void Vt102Emulation::tau( int token, int p, int q )
+{
+#if 0
+int N = (token>>0)&0xff;
+int A = (token>>8)&0xff;
+switch( N )
+{
+   case 0: printf("%c", (p < 128) ? p : '?');
+           break;
+   case 1: if (A == 'J') printf("\r");
+           else if (A == 'M') printf("\n");
+           else printf("CTL-%c ", (token>>8)&0xff);
+           break;
+   case 2: printf("ESC-%c ", (token>>8)&0xff);
+           break;
+   case 3: printf("ESC_CS-%c-%c ", (token>>8)&0xff, (token>>16)&0xff);
+           break;
+   case 4: printf("ESC_DE-%c ", (token>>8)&0xff);
+           break;
+   case 5: printf("CSI-PS-%c-%d", (token>>8)&0xff, (token>>16)&0xff );
+           break;
+   case 6: printf("CSI-PN-%c [%d]", (token>>8)&0xff, p);
+           break;
+   case 7: printf("CSI-PR-%c-%d", (token>>8)&0xff, (token>>16)&0xff );
+           break;
+   case 8: printf("VT52-%c", (token>>8)&0xff);
+           break;
+   case 9: printf("CSI-PG-%c", (token>>8)&0xff);
+           break;
+   case 10: printf("CSI-PE-%c", (token>>8)&0xff);
+           break;
+}
+#endif
+
+  switch (token)
+  {
+
+    case TY_CHR(         ) : _currentScreen->ShowCharacter        (p         ); break; //UTF16
+
+    //             127 DEL    : ignored on input
+
+    case TY_CTL('@'      ) : /* NUL: ignored                      */ break;
+    case TY_CTL('A'      ) : /* SOH: ignored                      */ break;
+    case TY_CTL('B'      ) : /* STX: ignored                      */ break;
+    case TY_CTL('C'      ) : /* ETX: ignored                      */ break;
+    case TY_CTL('D'      ) : /* EOT: ignored                      */ break;
+    case TY_CTL('E'      ) :      reportAnswerBack     (          ); break; //VT100
+    case TY_CTL('F'      ) : /* ACK: ignored                      */ break;
+    case TY_CTL('G'      ) : emit stateSet(NOTIFYBELL);
+                                break; //VT100
+    case TY_CTL('H'      ) : _currentScreen->BackSpace            (          ); break; //VT100
+    case TY_CTL('I'      ) : _currentScreen->Tabulate             (          ); break; //VT100
+    case TY_CTL('J'      ) : _currentScreen->NewLine              (          ); break; //VT100
+    case TY_CTL('K'      ) : _currentScreen->NewLine              (          ); break; //VT100
+    case TY_CTL('L'      ) : _currentScreen->NewLine              (          ); break; //VT100
+    case TY_CTL('M'      ) : _currentScreen->Return               (          ); break; //VT100
+
+    case TY_CTL('N'      ) :      useCharset           (         1); break; //VT100
+    case TY_CTL('O'      ) :      useCharset           (         0); break; //VT100
+
+    case TY_CTL('P'      ) : /* DLE: ignored                      */ break;
+    case TY_CTL('Q'      ) : /* DC1: XON continue                 */ break; //VT100
+    case TY_CTL('R'      ) : /* DC2: ignored                      */ break;
+    case TY_CTL('S'      ) : /* DC3: XOFF halt                    */ break; //VT100
+    case TY_CTL('T'      ) : /* DC4: ignored                      */ break;
+    case TY_CTL('U'      ) : /* NAK: ignored                      */ break;
+    case TY_CTL('V'      ) : /* SYN: ignored                      */ break;
+    case TY_CTL('W'      ) : /* ETB: ignored                      */ break;
+    case TY_CTL('X'      ) : _currentScreen->ShowCharacter        (    0x2592); break; //VT100
+    case TY_CTL('Y'      ) : /* EM : ignored                      */ break;
+    case TY_CTL('Z'      ) : _currentScreen->ShowCharacter        (    0x2592); break; //VT100
+    case TY_CTL('['      ) : /* ESC: cannot be seen here.         */ break;
+    case TY_CTL('\\'     ) : /* FS : ignored                      */ break;
+    case TY_CTL(']'      ) : /* GS : ignored                      */ break;
+    case TY_CTL('^'      ) : /* RS : ignored                      */ break;
+    case TY_CTL('_'      ) : /* US : ignored                      */ break;
+
+    case TY_ESC('D'      ) : _currentScreen->index                (          ); break; //VT100
+    case TY_ESC('E'      ) : _currentScreen->NextLine             (          ); break; //VT100
+    case TY_ESC('H'      ) : _currentScreen->changeTabStop        (true      ); break; //VT100
+    case TY_ESC('M'      ) : _currentScreen->reverseIndex         (          ); break; //VT100
+    case TY_ESC('Z'      ) :      reportTerminalType   (          ); break;
+    case TY_ESC('c'      ) :      reset                (          ); break;
+
+    case TY_ESC('n'      ) :      useCharset           (         2); break;
+    case TY_ESC('o'      ) :      useCharset           (         3); break;
+    case TY_ESC('7'      ) :      saveCursor           (          ); break;
+    case TY_ESC('8'      ) :      restoreCursor        (          ); break;
+
+    case TY_ESC('='      ) :          setMode      (MODE_AppKeyPad); break;
+    case TY_ESC('>'      ) :        resetMode      (MODE_AppKeyPad); break;
+    case TY_ESC('<'      ) :          setMode      (MODE_Ansi     ); break; //VT100
+
+    case TY_ESC_CS('(', '0') :      setCharset           (0,    '0'); break; //VT100
+    case TY_ESC_CS('(', 'A') :      setCharset           (0,    'A'); break; //VT100
+    case TY_ESC_CS('(', 'B') :      setCharset           (0,    'B'); break; //VT100
+
+    case TY_ESC_CS(')', '0') :      setCharset           (1,    '0'); break; //VT100
+    case TY_ESC_CS(')', 'A') :      setCharset           (1,    'A'); break; //VT100
+    case TY_ESC_CS(')', 'B') :      setCharset           (1,    'B'); break; //VT100
+
+    case TY_ESC_CS('*', '0') :      setCharset           (2,    '0'); break; //VT100
+    case TY_ESC_CS('*', 'A') :      setCharset           (2,    'A'); break; //VT100
+    case TY_ESC_CS('*', 'B') :      setCharset           (2,    'B'); break; //VT100
+
+    case TY_ESC_CS('+', '0') :      setCharset           (3,    '0'); break; //VT100
+    case TY_ESC_CS('+', 'A') :      setCharset           (3,    'A'); break; //VT100
+    case TY_ESC_CS('+', 'B') :      setCharset           (3,    'B'); break; //VT100
+
+    case TY_ESC_CS('%', 'G') :      setCodec             (Utf8Codec   ); break; //LINUX
+    case TY_ESC_CS('%', '@') :      setCodec             (LocaleCodec ); break; //LINUX
+
+    case TY_ESC_DE('3'      ) : /* Double height line, top half    */
+                                _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true );
+                                _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true );
+                                    break;
+    case TY_ESC_DE('4'      ) : /* Double height line, bottom half */
+                                _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true );
+                                _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true );
+                                    break;
+    case TY_ESC_DE('5'      ) : /* Single width, single height line*/
+                                _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , false);
+                                _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false);
+                                break;
+    case TY_ESC_DE('6'      ) : /* Double width, single height line*/
+                                _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true);
+                                _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false);
+                                break;
+    case TY_ESC_DE('8'      ) : _currentScreen->helpAlign            (          ); break;
+
+// resize = \e[8;<row>;<col>t
+    case TY_CSI_PS('t',   8) : setImageSize( q /* colums */, p /* lines */ );    break;
+
+// change tab text color : \e[28;<color>t  color: 0-16,777,215
+    case TY_CSI_PS('t',   28) : emit changeTabTextColorRequest      ( p        );          break;
+
+    case TY_CSI_PS('K',   0) : _currentScreen->clearToEndOfLine     (          ); break;
+    case TY_CSI_PS('K',   1) : _currentScreen->clearToBeginOfLine   (          ); break;
+    case TY_CSI_PS('K',   2) : _currentScreen->clearEntireLine      (          ); break;
+    case TY_CSI_PS('J',   0) : _currentScreen->clearToEndOfScreen   (          ); break;
+    case TY_CSI_PS('J',   1) : _currentScreen->clearToBeginOfScreen (          ); break;
+    case TY_CSI_PS('J',   2) : _currentScreen->clearEntireScreen    (          ); break;
+    case TY_CSI_PS('g',   0) : _currentScreen->changeTabStop        (false     ); break; //VT100
+    case TY_CSI_PS('g',   3) : _currentScreen->clearTabStops        (          ); break; //VT100
+    case TY_CSI_PS('h',   4) : _currentScreen->    setMode      (MODE_Insert   ); break;
+    case TY_CSI_PS('h',  20) :          setMode      (MODE_NewLine  ); break;
+    case TY_CSI_PS('i',   0) : /* IGNORE: attached printer          */ break; //VT100
+    case TY_CSI_PS('l',   4) : _currentScreen->  resetMode      (MODE_Insert   ); break;
+    case TY_CSI_PS('l',  20) :        resetMode      (MODE_NewLine  ); break;
+    case TY_CSI_PS('s',   0) :      saveCursor           (          ); break;
+    case TY_CSI_PS('u',   0) :      restoreCursor        (          ); break;
+
+    case TY_CSI_PS('m',   0) : _currentScreen->setDefaultRendition  (          ); break;
+    case TY_CSI_PS('m',   1) : _currentScreen->  setRendition     (RE_BOLD     ); break; //VT100
+    case TY_CSI_PS('m',   4) : _currentScreen->  setRendition     (RE_UNDERLINE); break; //VT100
+    case TY_CSI_PS('m',   5) : _currentScreen->  setRendition     (RE_BLINK    ); break; //VT100
+    case TY_CSI_PS('m',   7) : _currentScreen->  setRendition     (RE_REVERSE  ); break;
+    case TY_CSI_PS('m',  10) : /* IGNORED: mapping related          */ break; //LINUX
+    case TY_CSI_PS('m',  11) : /* IGNORED: mapping related          */ break; //LINUX
+    case TY_CSI_PS('m',  12) : /* IGNORED: mapping related          */ break; //LINUX
+    case TY_CSI_PS('m',  22) : _currentScreen->resetRendition     (RE_BOLD     ); break;
+    case TY_CSI_PS('m',  24) : _currentScreen->resetRendition     (RE_UNDERLINE); break;
+    case TY_CSI_PS('m',  25) : _currentScreen->resetRendition     (RE_BLINK    ); break;
+    case TY_CSI_PS('m',  27) : _currentScreen->resetRendition     (RE_REVERSE  ); break;
+
+    case TY_CSI_PS('m',   30) : _currentScreen->setForeColor         (COLOR_SPACE_SYSTEM,  0); break;
+    case TY_CSI_PS('m',   31) : _currentScreen->setForeColor         (COLOR_SPACE_SYSTEM,  1); break;
+    case TY_CSI_PS('m',   32) : _currentScreen->setForeColor         (COLOR_SPACE_SYSTEM,  2); break;
+    case TY_CSI_PS('m',   33) : _currentScreen->setForeColor         (COLOR_SPACE_SYSTEM,  3); break;
+    case TY_CSI_PS('m',   34) : _currentScreen->setForeColor         (COLOR_SPACE_SYSTEM,  4); break;
+    case TY_CSI_PS('m',   35) : _currentScreen->setForeColor         (COLOR_SPACE_SYSTEM,  5); break;
+    case TY_CSI_PS('m',   36) : _currentScreen->setForeColor         (COLOR_SPACE_SYSTEM,  6); break;
+    case TY_CSI_PS('m',   37) : _currentScreen->setForeColor         (COLOR_SPACE_SYSTEM,  7); break;
+
+    case TY_CSI_PS('m',   38) : _currentScreen->setForeColor         (p,       q); break;
+
+    case TY_CSI_PS('m',   39) : _currentScreen->setForeColor         (COLOR_SPACE_DEFAULT,  0); break;
+
+    case TY_CSI_PS('m',   40) : _currentScreen->setBackColor         (COLOR_SPACE_SYSTEM,  0); break;
+    case TY_CSI_PS('m',   41) : _currentScreen->setBackColor         (COLOR_SPACE_SYSTEM,  1); break;
+    case TY_CSI_PS('m',   42) : _currentScreen->setBackColor         (COLOR_SPACE_SYSTEM,  2); break;
+    case TY_CSI_PS('m',   43) : _currentScreen->setBackColor         (COLOR_SPACE_SYSTEM,  3); break;
+    case TY_CSI_PS('m',   44) : _currentScreen->setBackColor         (COLOR_SPACE_SYSTEM,  4); break;
+    case TY_CSI_PS('m',   45) : _currentScreen->setBackColor         (COLOR_SPACE_SYSTEM,  5); break;
+    case TY_CSI_PS('m',   46) : _currentScreen->setBackColor         (COLOR_SPACE_SYSTEM,  6); break;
+    case TY_CSI_PS('m',   47) : _currentScreen->setBackColor         (COLOR_SPACE_SYSTEM,  7); break;
+
+    case TY_CSI_PS('m',   48) : _currentScreen->setBackColor         (p,       q); break;
+
+    case TY_CSI_PS('m',   49) : _currentScreen->setBackColor         (COLOR_SPACE_DEFAULT,  1); break;
+
+    case TY_CSI_PS('m',   90) : _currentScreen->setForeColor         (COLOR_SPACE_SYSTEM,  8); break;
+    case TY_CSI_PS('m',   91) : _currentScreen->setForeColor         (COLOR_SPACE_SYSTEM,  9); break;
+    case TY_CSI_PS('m',   92) : _currentScreen->setForeColor         (COLOR_SPACE_SYSTEM, 10); break;
+    case TY_CSI_PS('m',   93) : _currentScreen->setForeColor         (COLOR_SPACE_SYSTEM, 11); break;
+    case TY_CSI_PS('m',   94) : _currentScreen->setForeColor         (COLOR_SPACE_SYSTEM, 12); break;
+    case TY_CSI_PS('m',   95) : _currentScreen->setForeColor         (COLOR_SPACE_SYSTEM, 13); break;
+    case TY_CSI_PS('m',   96) : _currentScreen->setForeColor         (COLOR_SPACE_SYSTEM, 14); break;
+    case TY_CSI_PS('m',   97) : _currentScreen->setForeColor         (COLOR_SPACE_SYSTEM, 15); break;
+
+    case TY_CSI_PS('m',  100) : _currentScreen->setBackColor         (COLOR_SPACE_SYSTEM,  8); break;
+    case TY_CSI_PS('m',  101) : _currentScreen->setBackColor         (COLOR_SPACE_SYSTEM,  9); break;
+    case TY_CSI_PS('m',  102) : _currentScreen->setBackColor         (COLOR_SPACE_SYSTEM, 10); break;
+    case TY_CSI_PS('m',  103) : _currentScreen->setBackColor         (COLOR_SPACE_SYSTEM, 11); break;
+    case TY_CSI_PS('m',  104) : _currentScreen->setBackColor         (COLOR_SPACE_SYSTEM, 12); break;
+    case TY_CSI_PS('m',  105) : _currentScreen->setBackColor         (COLOR_SPACE_SYSTEM, 13); break;
+    case TY_CSI_PS('m',  106) : _currentScreen->setBackColor         (COLOR_SPACE_SYSTEM, 14); break;
+    case TY_CSI_PS('m',  107) : _currentScreen->setBackColor         (COLOR_SPACE_SYSTEM, 15); break;
+
+    case TY_CSI_PS('n',   5) :      reportStatus         (          ); break;
+    case TY_CSI_PS('n',   6) :      reportCursorPosition (          ); break;
+    case TY_CSI_PS('q',   0) : /* IGNORED: LEDs off                 */ break; //VT100
+    case TY_CSI_PS('q',   1) : /* IGNORED: LED1 on                  */ break; //VT100
+    case TY_CSI_PS('q',   2) : /* IGNORED: LED2 on                  */ break; //VT100
+    case TY_CSI_PS('q',   3) : /* IGNORED: LED3 on                  */ break; //VT100
+    case TY_CSI_PS('q',   4) : /* IGNORED: LED4 on                  */ break; //VT100
+    case TY_CSI_PS('x',   0) :      reportTerminalParms  (         2); break; //VT100
+    case TY_CSI_PS('x',   1) :      reportTerminalParms  (         3); break; //VT100
+
+    case TY_CSI_PN('@'      ) : _currentScreen->insertChars          (p         ); break;
+    case TY_CSI_PN('A'      ) : _currentScreen->cursorUp             (p         ); break; //VT100
+    case TY_CSI_PN('B'      ) : _currentScreen->cursorDown           (p         ); break; //VT100
+    case TY_CSI_PN('C'      ) : _currentScreen->cursorRight          (p         ); break; //VT100
+    case TY_CSI_PN('D'      ) : _currentScreen->cursorLeft           (p         ); break; //VT100
+    case TY_CSI_PN('G'      ) : _currentScreen->setCursorX           (p         ); break; //LINUX
+    case TY_CSI_PN('H'      ) : _currentScreen->setCursorYX          (p,      q); break; //VT100
+    case TY_CSI_PN('I'      ) : _currentScreen->Tabulate             (p         ); break;
+    case TY_CSI_PN('L'      ) : _currentScreen->insertLines          (p         ); break;
+    case TY_CSI_PN('M'      ) : _currentScreen->deleteLines          (p         ); break;
+    case TY_CSI_PN('P'      ) : _currentScreen->deleteChars          (p         ); break;
+    case TY_CSI_PN('S'      ) : _currentScreen->scrollUp             (p         ); break;
+    case TY_CSI_PN('T'      ) : _currentScreen->scrollDown           (p         ); break;
+    case TY_CSI_PN('X'      ) : _currentScreen->eraseChars           (p         ); break;
+    case TY_CSI_PN('Z'      ) : _currentScreen->backTabulate         (p         ); break;
+    case TY_CSI_PN('c'      ) :      reportTerminalType   (          ); break; //VT100
+    case TY_CSI_PN('d'      ) : _currentScreen->setCursorY           (p         ); break; //LINUX
+    case TY_CSI_PN('f'      ) : _currentScreen->setCursorYX          (p,      q); break; //VT100
+    case TY_CSI_PN('r'      ) :      setMargins           (p,      q); break; //VT100
+    case TY_CSI_PN('y'      ) : /* IGNORED: Confidence test          */ break; //VT100
+
+    case TY_CSI_PR('h',   1) :          setMode      (MODE_AppCuKeys); break; //VT100
+    case TY_CSI_PR('l',   1) :        resetMode      (MODE_AppCuKeys); break; //VT100
+    case TY_CSI_PR('s',   1) :         saveMode      (MODE_AppCuKeys); break; //FIXME
+    case TY_CSI_PR('r',   1) :      restoreMode      (MODE_AppCuKeys); break; //FIXME
+
+    case TY_CSI_PR('l',   2) :        resetMode      (MODE_Ansi     ); break; //VT100
+
+    case TY_CSI_PR('h',   3) : clearScreenAndSetColumns(132);          break; //VT100
+    case TY_CSI_PR('l',   3) : clearScreenAndSetColumns(80);           break; //VT100
+
+    case TY_CSI_PR('h',   4) : /* IGNORED: soft scrolling           */ break; //VT100
+    case TY_CSI_PR('l',   4) : /* IGNORED: soft scrolling           */ break; //VT100
+
+    case TY_CSI_PR('h',   5) : _currentScreen->    setMode      (MODE_Screen   ); break; //VT100
+    case TY_CSI_PR('l',   5) : _currentScreen->  resetMode      (MODE_Screen   ); break; //VT100
+
+    case TY_CSI_PR('h',   6) : _currentScreen->    setMode      (MODE_Origin   ); break; //VT100
+    case TY_CSI_PR('l',   6) : _currentScreen->  resetMode      (MODE_Origin   ); break; //VT100
+    case TY_CSI_PR('s',   6) : _currentScreen->   saveMode      (MODE_Origin   ); break; //FIXME
+    case TY_CSI_PR('r',   6) : _currentScreen->restoreMode      (MODE_Origin   ); break; //FIXME
+
+    case TY_CSI_PR('h',   7) : _currentScreen->    setMode      (MODE_Wrap     ); break; //VT100
+    case TY_CSI_PR('l',   7) : _currentScreen->  resetMode      (MODE_Wrap     ); break; //VT100
+    case TY_CSI_PR('s',   7) : _currentScreen->   saveMode      (MODE_Wrap     ); break; //FIXME
+    case TY_CSI_PR('r',   7) : _currentScreen->restoreMode      (MODE_Wrap     ); break; //FIXME
+
+    case TY_CSI_PR('h',   8) : /* IGNORED: autorepeat on            */ break; //VT100
+    case TY_CSI_PR('l',   8) : /* IGNORED: autorepeat off           */ break; //VT100
+    case TY_CSI_PR('s',   8) : /* IGNORED: autorepeat on            */ break; //VT100
+    case TY_CSI_PR('r',   8) : /* IGNORED: autorepeat off           */ break; //VT100
+
+    case TY_CSI_PR('h',   9) : /* IGNORED: interlace                */ break; //VT100
+    case TY_CSI_PR('l',   9) : /* IGNORED: interlace                */ break; //VT100
+    case TY_CSI_PR('s',   9) : /* IGNORED: interlace                */ break; //VT100
+    case TY_CSI_PR('r',   9) : /* IGNORED: interlace                */ break; //VT100
+
+    case TY_CSI_PR('h',  12) : /* IGNORED: Cursor blink             */ break; //att610
+    case TY_CSI_PR('l',  12) : /* IGNORED: Cursor blink             */ break; //att610
+    case TY_CSI_PR('s',  12) : /* IGNORED: Cursor blink             */ break; //att610
+    case TY_CSI_PR('r',  12) : /* IGNORED: Cursor blink             */ break; //att610
+
+    case TY_CSI_PR('h',  25) :          setMode      (MODE_Cursor   ); break; //VT100
+    case TY_CSI_PR('l',  25) :        resetMode      (MODE_Cursor   ); break; //VT100
+    case TY_CSI_PR('s',  25) :         saveMode      (MODE_Cursor   ); break; //VT100
+    case TY_CSI_PR('r',  25) :      restoreMode      (MODE_Cursor   ); break; //VT100
+
+    case TY_CSI_PR('h',  41) : /* IGNORED: obsolete more(1) fix     */ break; //XTERM
+    case TY_CSI_PR('l',  41) : /* IGNORED: obsolete more(1) fix     */ break; //XTERM
+    case TY_CSI_PR('s',  41) : /* IGNORED: obsolete more(1) fix     */ break; //XTERM
+    case TY_CSI_PR('r',  41) : /* IGNORED: obsolete more(1) fix     */ break; //XTERM
+
+    case TY_CSI_PR('h',  47) :          setMode      (MODE_AppScreen); break; //VT100
+    case TY_CSI_PR('l',  47) :        resetMode      (MODE_AppScreen); break; //VT100
+    case TY_CSI_PR('s',  47) :         saveMode      (MODE_AppScreen); break; //XTERM
+    case TY_CSI_PR('r',  47) :      restoreMode      (MODE_AppScreen); break; //XTERM
+
+    case TY_CSI_PR('h',  67) : /* IGNORED: DECBKM                   */ break; //XTERM
+    case TY_CSI_PR('l',  67) : /* IGNORED: DECBKM                   */ break; //XTERM
+    case TY_CSI_PR('s',  67) : /* IGNORED: DECBKM                   */ break; //XTERM
+    case TY_CSI_PR('r',  67) : /* IGNORED: DECBKM                   */ break; //XTERM
+
+    // XTerm defines the following modes:
+    // SET_VT200_MOUSE             1000
+    // SET_VT200_HIGHLIGHT_MOUSE   1001
+    // SET_BTN_EVENT_MOUSE         1002
+    // SET_ANY_EVENT_MOUSE         1003
+    //
+
+    //Note about mouse modes:
+    //There are four mouse modes which xterm-compatible terminals can support - 1000,1001,1002,1003
+    //Konsole currently supports mode 1000 (basic mouse press and release) and mode 1002 (dragging the mouse).
+    //TODO:  Implementation of mouse modes 1001 (something called hilight tracking) and
+    //1003 (a slight variation on dragging the mouse)
+    //
+
+    case TY_CSI_PR('h', 1000) :          setMode      (MODE_Mouse1000); break; //XTERM
+    case TY_CSI_PR('l', 1000) :        resetMode      (MODE_Mouse1000); break; //XTERM
+    case TY_CSI_PR('s', 1000) :         saveMode      (MODE_Mouse1000); break; //XTERM
+    case TY_CSI_PR('r', 1000) :      restoreMode      (MODE_Mouse1000); break; //XTERM
+
+    case TY_CSI_PR('h', 1001) : /* IGNORED: hilite mouse tracking    */ break; //XTERM
+    case TY_CSI_PR('l', 1001) :        resetMode      (MODE_Mouse1001); break; //XTERM
+    case TY_CSI_PR('s', 1001) : /* IGNORED: hilite mouse tracking    */ break; //XTERM
+    case TY_CSI_PR('r', 1001) : /* IGNORED: hilite mouse tracking    */ break; //XTERM
+
+    case TY_CSI_PR('h', 1002) :          setMode      (MODE_Mouse1002); break; //XTERM
+    case TY_CSI_PR('l', 1002) :        resetMode      (MODE_Mouse1002); break; //XTERM
+    case TY_CSI_PR('s', 1002) :         saveMode      (MODE_Mouse1002); break; //XTERM
+    case TY_CSI_PR('r', 1002) :      restoreMode      (MODE_Mouse1002); break; //XTERM
+
+    case TY_CSI_PR('h', 1003) :          setMode      (MODE_Mouse1003); break; //XTERM
+    case TY_CSI_PR('l', 1003) :        resetMode      (MODE_Mouse1003); break; //XTERM
+    case TY_CSI_PR('s', 1003) :         saveMode      (MODE_Mouse1003); break; //XTERM
+    case TY_CSI_PR('r', 1003) :      restoreMode      (MODE_Mouse1003); break; //XTERM
+    case TY_CSI_PR('h', 1034) : /* IGNORED: 8bitinput activation     */ break; //XTERM
+
+    case TY_CSI_PR('h', 1047) :          setMode      (MODE_AppScreen); break; //XTERM
+    case TY_CSI_PR('l', 1047) : _screen[1]->clearEntireScreen(); resetMode(MODE_AppScreen); break; //XTERM
+    case TY_CSI_PR('s', 1047) :         saveMode      (MODE_AppScreen); break; //XTERM
+    case TY_CSI_PR('r', 1047) :      restoreMode      (MODE_AppScreen); break; //XTERM
+
+    //FIXME: Unitoken: save translations
+    case TY_CSI_PR('h', 1048) :      saveCursor           (          ); break; //XTERM
+    case TY_CSI_PR('l', 1048) :      restoreCursor        (          ); break; //XTERM
+    case TY_CSI_PR('s', 1048) :      saveCursor           (          ); break; //XTERM
+    case TY_CSI_PR('r', 1048) :      restoreCursor        (          ); break; //XTERM
+
+    //FIXME: every once new sequences like this pop up in xterm.
+    //       Here's a guess of what they could mean.
+    case TY_CSI_PR('h', 1049) : saveCursor(); _screen[1]->clearEntireScreen(); setMode(MODE_AppScreen); break; //XTERM
+    case TY_CSI_PR('l', 1049) : resetMode(MODE_AppScreen); restoreCursor(); break; //XTERM
+
+    //FIXME: weird DEC reset sequence
+    case TY_CSI_PE('p'      ) : /* IGNORED: reset         (        ) */ break;
+
+    //FIXME: when changing between vt52 and ansi mode evtl do some resetting.
+    case TY_VT52('A'      ) : _currentScreen->cursorUp             (         1); break; //VT52
+    case TY_VT52('B'      ) : _currentScreen->cursorDown           (         1); break; //VT52
+    case TY_VT52('C'      ) : _currentScreen->cursorRight          (         1); break; //VT52
+    case TY_VT52('D'      ) : _currentScreen->cursorLeft           (         1); break; //VT52
+
+    case TY_VT52('F'      ) :      setAndUseCharset     (0,    '0'); break; //VT52
+    case TY_VT52('G'      ) :      setAndUseCharset     (0,    'B'); break; //VT52
+
+    case TY_VT52('H'      ) : _currentScreen->setCursorYX          (1,1       ); break; //VT52
+    case TY_VT52('I'      ) : _currentScreen->reverseIndex         (          ); break; //VT52
+    case TY_VT52('J'      ) : _currentScreen->clearToEndOfScreen   (          ); break; //VT52
+    case TY_VT52('K'      ) : _currentScreen->clearToEndOfLine     (          ); break; //VT52
+    case TY_VT52('Y'      ) : _currentScreen->setCursorYX          (p-31,q-31 ); break; //VT52
+    case TY_VT52('Z'      ) :      reportTerminalType   (           ); break; //VT52
+    case TY_VT52('<'      ) :          setMode      (MODE_Ansi     ); break; //VT52
+    case TY_VT52('='      ) :          setMode      (MODE_AppKeyPad); break; //VT52
+    case TY_VT52('>'      ) :        resetMode      (MODE_AppKeyPad); break; //VT52
+
+    case TY_CSI_PG('c'      ) :  reportSecondaryAttributes(          ); break; //VT100
+
+    default : ReportErrorToken();    break;
+  };
+}
+
+void Vt102Emulation::clearScreenAndSetColumns(int columnCount)
+{
+    setImageSize(_currentScreen->getLines(),columnCount);
+    clearEntireScreen();
+    setDefaultMargins();
+    _currentScreen->setCursorYX(0,0);
+}
+
+/* ------------------------------------------------------------------------- */
+/*                                                                           */
+/*                          Terminal to Host protocol                        */
+/*                                                                           */
+/* ------------------------------------------------------------------------- */
+
+/*
+   Outgoing bytes originate from several sources:
+
+   - Replies to Enquieries.
+   - Mouse Events
+   - Keyboard Events
+*/
+
+/*!
+*/
+
+void Vt102Emulation::sendString(const char* s , int length)
+{
+  if ( length >= 0 )
+    emit sendData(s,length);
+  else
+    emit sendData(s,strlen(s));
+}
+
+// Replies ----------------------------------------------------------------- --
+
+// This section copes with replies send as response to an enquiery control code.
+
+/*!
+*/
+
+void Vt102Emulation::reportCursorPosition()
+{ char tmp[20];
+  sprintf(tmp,"\033[%d;%dR",_currentScreen->getCursorY()+1,_currentScreen->getCursorX()+1);
+  sendString(tmp);
+}
+
+/*
+   What follows here is rather obsolete and faked stuff.
+   The correspondent enquieries are neverthenless issued.
+*/
+
+/*!
+*/
+
+void Vt102Emulation::reportTerminalType()
+{
+  // Primary device attribute response (Request was: ^[[0c or ^[[c (from TT321 Users Guide))
+  //   VT220:  ^[[?63;1;2;3;6;7;8c   (list deps on emul. capabilities)
+  //   VT100:  ^[[?1;2c
+  //   VT101:  ^[[?1;0c
+  //   VT102:  ^[[?6v
+  if (getMode(MODE_Ansi))
+    sendString("\033[?1;2c");     // I'm a VT100
+  else
+    sendString("\033/Z");         // I'm a VT52
+}
+
+void Vt102Emulation::reportSecondaryAttributes()
+{
+  // Seconday device attribute response (Request was: ^[[>0c or ^[[>c)
+  if (getMode(MODE_Ansi))
+    sendString("\033[>0;115;0c"); // Why 115?  ;)
+  else
+    sendString("\033/Z");         // FIXME I don't think VT52 knows about it but kept for
+                                  // konsoles backward compatibility.
+}
+
+void Vt102Emulation::reportTerminalParms(int p)
+// DECREPTPARM
+{ char tmp[100];
+  sprintf(tmp,"\033[%d;1;1;112;112;1;0x",p); // not really true.
+  sendString(tmp);
+}
+
+/*!
+*/
+
+void Vt102Emulation::reportStatus()
+{
+  sendString("\033[0n"); //VT100. Device status report. 0 = Ready.
+}
+
+/*!
+*/
+
+#define ANSWER_BACK "" // This is really obsolete VT100 stuff.
+
+void Vt102Emulation::reportAnswerBack()
+{
+  sendString(ANSWER_BACK);
+}
+
+// Mouse Handling ---------------------------------------------------------- --
+
+/*!
+    Mouse clicks are possibly reported to the client
+    application if it has issued interest in them.
+    They are normally consumed by the widget for copy
+    and paste, but may be propagated from the widget
+    when gui->setMouseMarks is set via setMode(MODE_Mouse1000).
+
+    `x',`y' are 1-based.
+    `ev' (event) indicates the button pressed (0-2)
+                 or a general mouse release (3).
+
+    eventType represents the kind of mouse action that occurred:
+        0 = Mouse button press or release
+    1 = Mouse drag
+*/
+
+void Vt102Emulation::sendMouseEvent( int cb, int cx, int cy , int eventType )
+{ char tmp[20];
+  if (  cx<1 || cy<1 ) return;
+  // normal buttons are passed as 0x20 + button,
+  // mouse wheel (buttons 4,5) as 0x5c + button
+  if (cb >= 4) cb += 0x3c;
+
+  //Mouse motion handling
+  if ( (getMode(MODE_Mouse1002) || getMode(MODE_Mouse1003)) && eventType == 1 )
+      cb += 0x20; //add 32 to signify motion event
+
+  sprintf(tmp,"\033[M%c%c%c",cb+0x20,cx+0x20,cy+0x20);
+  sendString(tmp);
+}
+
+// Keyboard Handling ------------------------------------------------------- --
+
+#define encodeMode(M,B) BITS(B,getMode(M))
+#define encodeStat(M,B) BITS(B,((ev->modifiers() & (M)) == (M)))
+
+void Vt102Emulation::sendText( const QString& text )
+{
+  if (!text.isEmpty()) {
+    QKeyEvent event(QEvent::KeyPress,
+                    0,
+                    Qt::NoModifier,
+                    text);
+    sendKeyEvent(&event); // expose as a big fat keypress event
+  }
+
+}
+
+void Vt102Emulation::sendKeyEvent( QKeyEvent* event )
+{
+    Qt::KeyboardModifiers modifiers = event->modifiers();
+    KeyboardTranslator::States states = KeyboardTranslator::NoState;
+
+    // get current states
+    if ( getMode(MODE_NewLine)  ) states |= KeyboardTranslator::NewLineState;
+    if ( getMode(MODE_Ansi)     ) states |= KeyboardTranslator::AnsiState;
+    if ( getMode(MODE_AppCuKeys)) states |= KeyboardTranslator::CursorKeysState;
+    if ( getMode(MODE_AppScreen)) states |= KeyboardTranslator::AlternateScreenState;
+
+    // lookup key binding
+    if ( _keyTranslator )
+    {
+    KeyboardTranslator::Entry entry = _keyTranslator->findEntry(
+                                                event->key() ,
+                                                modifiers,
+                                                states );
+
+        // send result to terminal
+        QByteArray textToSend;
+
+        // special handling for the Alt (aka. Meta) modifier.  pressing
+        // Alt+[Character] results in Esc+[Character] being sent
+        // (unless there is an entry defined for this particular combination
+        //  in the keyboard modifier)
+        bool wantsAltModifier = entry.modifiers() & entry.modifierMask() & Qt::AltModifier;
+        bool wantsAnyModifier = entry.state() & entry.stateMask() & KeyboardTranslator::AnyModifierState;
+
+        if ( modifiers & Qt::AltModifier && !(wantsAltModifier || wantsAnyModifier)
+             && !event->text().isEmpty() )
+        {
+            textToSend.prepend("\033");
+        }
+
+        if ( entry.command() != KeyboardTranslator::NoCommand )
+        {
+            if (entry.command() & KeyboardTranslator::EraseCommand)
+                textToSend += getErase();
+            // TODO command handling
+        }
+        else if ( !entry.text().isEmpty() )
+        {
+            textToSend += _codec->fromUnicode(entry.text(true,modifiers));
+        }
+        else
+            textToSend += _codec->fromUnicode(event->text());
+
+        sendData( textToSend.constData() , textToSend.length() );
+    }
+    else
+    {
+        // print an error message to the terminal if no key translator has been
+        // set
+        QString translatorError =  ("No keyboard translator available.  "
+                                         "The information needed to convert key presses "
+                                         "into characters to send to the terminal "
+                                         "is missing.");
+
+        reset();
+        receiveData( translatorError.toAscii().constData() , translatorError.count() );
+    }
+}
+
+/* ------------------------------------------------------------------------- */
+/*                                                                           */
+/*                                VT100 Charsets                             */
+/*                                                                           */
+/* ------------------------------------------------------------------------- */
+
+// Character Set Conversion ------------------------------------------------ --
+
+/*
+   The processing contains a VT100 specific code translation layer.
+   It's still in use and mainly responsible for the line drawing graphics.
+
+   These and some other glyphs are assigned to codes (0x5f-0xfe)
+   normally occupied by the latin letters. Since this codes also
+   appear within control sequences, the extra code conversion
+   does not permute with the tokenizer and is placed behind it
+   in the pipeline. It only applies to tokens, which represent
+   plain characters.
+
+   This conversion it eventually continued in TerminalDisplay.C, since
+   it might involve VT100 enhanced fonts, which have these
+   particular glyphs allocated in (0x00-0x1f) in their code page.
+*/
+
+#define CHARSET _charset[_currentScreen==_screen[1]]
+
+// Apply current character map.
+
+unsigned short Vt102Emulation::applyCharset(unsigned short c)
+{
+  if (CHARSET.graphic && 0x5f <= c && c <= 0x7e) return vt100_graphics[c-0x5f];
+  if (CHARSET.pound                && c == '#' ) return 0xa3; //This mode is obsolete
+  return c;
+}
+
+/*
+   "Charset" related part of the emulation state.
+   This configures the VT100 _charset filter.
+
+   While most operation work on the current _screen,
+   the following two are different.
+*/
+
+void Vt102Emulation::resetCharset(int scrno)
+{
+  _charset[scrno].cu_cs   = 0;
+  strncpy(_charset[scrno].charset,"BBBB",4);
+  _charset[scrno].sa_graphic = false;
+  _charset[scrno].sa_pound   = false;
+  _charset[scrno].graphic = false;
+  _charset[scrno].pound   = false;
+}
+
+void Vt102Emulation::setCharset(int n, int cs) // on both screens.
+{
+  _charset[0].charset[n&3] = cs; useCharset(_charset[0].cu_cs);
+  _charset[1].charset[n&3] = cs; useCharset(_charset[1].cu_cs);
+}
+
+void Vt102Emulation::setAndUseCharset(int n, int cs)
+{
+  CHARSET.charset[n&3] = cs;
+  useCharset(n&3);
+}
+
+void Vt102Emulation::useCharset(int n)
+{
+  CHARSET.cu_cs   = n&3;
+  CHARSET.graphic = (CHARSET.charset[n&3] == '0');
+  CHARSET.pound   = (CHARSET.charset[n&3] == 'A'); //This mode is obsolete
+}
+
+void Vt102Emulation::setDefaultMargins()
+{
+    _screen[0]->setDefaultMargins();
+    _screen[1]->setDefaultMargins();
+}
+
+void Vt102Emulation::setMargins(int t, int b)
+{
+  _screen[0]->setMargins(t, b);
+  _screen[1]->setMargins(t, b);
+}
+
+/*! Save the cursor position and the rendition attribute settings. */
+
+void Vt102Emulation::saveCursor()
+{
+  CHARSET.sa_graphic = CHARSET.graphic;
+  CHARSET.sa_pound   = CHARSET.pound; //This mode is obsolete
+  // we are not clear about these
+  //sa_charset = charsets[cScreen->_charset];
+  //sa_charset_num = cScreen->_charset;
+  _currentScreen->saveCursor();
+}
+
+/*! Restore the cursor position and the rendition attribute settings. */
+
+void Vt102Emulation::restoreCursor()
+{
+  CHARSET.graphic = CHARSET.sa_graphic;
+  CHARSET.pound   = CHARSET.sa_pound; //This mode is obsolete
+  _currentScreen->restoreCursor();
+}
+
+/* ------------------------------------------------------------------------- */
+/*                                                                           */
+/*                                Mode Operations                            */
+/*                                                                           */
+/* ------------------------------------------------------------------------- */
+
+/*
+   Some of the emulations state is either added to the state of the screens.
+
+   This causes some scoping problems, since different emulations choose to
+   located the mode either to the current _screen or to both.
+
+   For strange reasons, the extend of the rendition attributes ranges over
+   all screens and not over the actual _screen.
+
+   We decided on the precise precise extend, somehow.
+*/
+
+// "Mode" related part of the state. These are all booleans.
+
+void Vt102Emulation::resetModes()
+{
+  resetMode(MODE_Mouse1000); saveMode(MODE_Mouse1000);
+  resetMode(MODE_Mouse1001); saveMode(MODE_Mouse1001);
+  resetMode(MODE_Mouse1002); saveMode(MODE_Mouse1002);
+  resetMode(MODE_Mouse1003); saveMode(MODE_Mouse1003);
+
+  resetMode(MODE_AppScreen); saveMode(MODE_AppScreen);
+  // here come obsolete modes
+  resetMode(MODE_AppCuKeys); saveMode(MODE_AppCuKeys);
+  resetMode(MODE_NewLine  );
+    setMode(MODE_Ansi     );
+}
+
+void Vt102Emulation::setMode(int m)
+{
+  _currParm.mode[m] = true;
+  switch (m)
+  {
+    case MODE_Mouse1000:
+    case MODE_Mouse1001:
+    case MODE_Mouse1002:
+    case MODE_Mouse1003:
+        emit programUsesMouseChanged(false);
+    break;
+
+    case MODE_AppScreen : _screen[1]->clearSelection();
+                          setScreen(1);
+    break;
+  }
+  if (m < MODES_SCREEN || m == MODE_NewLine)
+  {
+    _screen[0]->setMode(m);
+    _screen[1]->setMode(m);
+  }
+}
+
+void Vt102Emulation::resetMode(int m)
+{
+  _currParm.mode[m] = false;
+  switch (m)
+  {
+    case MODE_Mouse1000 :
+    case MODE_Mouse1001 :
+    case MODE_Mouse1002 :
+    case MODE_Mouse1003 :
+        emit programUsesMouseChanged(true);
+    break;
+
+    case MODE_AppScreen : _screen[0]->clearSelection();
+                          setScreen(0);
+    break;
+  }
+  if (m < MODES_SCREEN || m == MODE_NewLine)
+  {
+    _screen[0]->resetMode(m);
+    _screen[1]->resetMode(m);
+  }
+}
+
+void Vt102Emulation::saveMode(int m)
+{
+  _saveParm.mode[m] = _currParm.mode[m];
+}
+
+void Vt102Emulation::restoreMode(int m)
+{
+  if (_saveParm.mode[m])
+      setMode(m);
+  else
+      resetMode(m);
+}
+
+bool Vt102Emulation::getMode(int m)
+{
+  return _currParm.mode[m];
+}
+
+char Vt102Emulation::getErase() const
+{
+  KeyboardTranslator::Entry entry = _keyTranslator->findEntry(
+                                            Qt::Key_Backspace,
+                                            0,
+                                            0);
+  if ( entry.text().count() > 0 )
+      return entry.text()[0];
+  else
+      return '\b';
+}
+
+/* ------------------------------------------------------------------------- */
+/*                                                                           */
+/*                               Diagnostic                                  */
+/*                                                                           */
+/* ------------------------------------------------------------------------- */
+
+/*! shows the contents of the scan buffer.
+
+    This functions is used for diagnostics. It is called by \e ReportErrorToken
+    to inform about strings that cannot be decoded or handled by the emulation.
+
+    \sa ReportErrorToken
+*/
+
+static void hexdump(int* s, int len)
+{ int i;
+  for (i = 0; i < len; i++)
+  {
+    if (s[i] == '\\')
+      printf("\\\\");
+    else
+    if ((s[i]) > 32 && s[i] < 127)
+      printf("%c",s[i]);
+    else
+      printf("\\%04x(hex)",s[i]);
+  }
+}
+
+void Vt102Emulation::scan_buffer_report() {
+  if (ppos == 0 || (ppos == 1 && (pbuf[0] & 0xff) >= 32)) {
+    return;
+  }
+  printf("token: ");
+  hexdump(pbuf,ppos);
+  printf("\n");
+}
+
+/*!
+*/
+
+void Vt102Emulation::ReportErrorToken()
+{
+#ifndef NDEBUG
+  printf("undecodable "); scan_buffer_report();
+#endif
+}
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/Vt102Emulation.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,187 @@
+/*
+    This file is part of Konsole, an X terminal.
+    
+    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
+    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    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, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+    02110-1301  USA.
+*/
+
+#ifndef VT102EMULATION_H
+#define VT102EMULATION_H
+
+// Standard Library
+#include <stdio.h>
+
+// Qt 
+#include <QtGui/QKeyEvent>
+#include <QtCore/QHash>
+#include <QtCore/QTimer>
+
+// Konsole
+#include "unix/Emulation.h"
+#include "unix/Screen.h"
+
+#define MODE_AppScreen (MODES_SCREEN+0)
+#define MODE_AppCuKeys (MODES_SCREEN+1)
+#define MODE_AppKeyPad (MODES_SCREEN+2)
+#define MODE_Mouse1000 (MODES_SCREEN+3)
+#define MODE_Mouse1001 (MODES_SCREEN+4)
+#define MODE_Mouse1002 (MODES_SCREEN+5)
+#define MODE_Mouse1003 (MODES_SCREEN+6)
+#define MODE_Ansi      (MODES_SCREEN+7)
+#define MODE_total     (MODES_SCREEN+8)
+
+struct DECpar
+{
+  bool mode[MODE_total];
+};
+
+struct CharCodes
+{
+  // coding info
+  char charset[4]; //
+  int  cu_cs;      // actual charset.
+  bool graphic;    // Some VT100 tricks
+  bool pound  ;    // Some VT100 tricks
+  bool sa_graphic; // saved graphic
+  bool sa_pound;   // saved pound
+};
+
+/**
+ * Provides an xterm compatible terminal emulation based on the DEC VT102 terminal.
+ * A full description of this terminal can be found at http://vt100.net/docs/vt102-ug/
+ * 
+ * In addition, various additional xterm escape sequences are supported to provide 
+ * features such as mouse input handling.
+ * See http://rtfm.etla.org/xterm/ctlseq.html for a description of xterm's escape
+ * sequences. 
+ *
+ */
+class Vt102Emulation : public Emulation
+{ 
+Q_OBJECT
+
+public:
+
+  /** Constructs a new emulation */
+  Vt102Emulation();
+  ~Vt102Emulation();
+  
+  // reimplemented
+  virtual void clearEntireScreen();
+  virtual void reset();
+  
+  // reimplemented
+  virtual char getErase() const;
+  
+public slots: 
+
+  // reimplemented 
+  virtual void sendString(const char*,int length = -1);
+  virtual void sendText(const QString& text);
+  virtual void sendKeyEvent(QKeyEvent*);
+  virtual void sendMouseEvent( int buttons, int column, int line , int eventType );
+  
+protected:
+  // reimplemented
+  virtual void setMode    (int mode);
+  virtual void resetMode  (int mode);
+
+  // reimplemented 
+  virtual void receiveChar(int cc);
+  
+
+private slots:
+		
+  //causes changeTitle() to be emitted for each (int,QString) pair in pendingTitleUpdates
+  //used to buffer multiple title updates
+  void updateTitle();
+
+
+private:
+  unsigned short applyCharset(unsigned short c);
+  void setCharset(int n, int cs);
+  void useCharset(int n);
+  void setAndUseCharset(int n, int cs);
+  void saveCursor();
+  void restoreCursor();
+  void resetCharset(int scrno);
+
+  void setMargins(int top, int bottom);
+  //set margins for all screens back to their defaults
+  void setDefaultMargins();
+
+  // returns true if 'mode' is set or false otherwise
+  bool getMode    (int mode);
+  // saves the current boolean value of 'mode'
+  void saveMode   (int mode);
+  // restores the boolean value of 'mode' 
+  void restoreMode(int mode);
+  // resets all modes
+  void resetModes();
+
+  void resetToken();
+#define MAXPBUF 80
+  void pushToToken(int cc);
+  int pbuf[MAXPBUF]; //FIXME: overflow?
+  int ppos;
+#define MAXARGS 15
+  void addDigit(int dig);
+  void addArgument();
+  int argv[MAXARGS];
+  int argc;
+  void initTokenizer();
+  int tbl[256];
+
+  void scan_buffer_report(); //FIXME: rename
+  void ReportErrorToken();   //FIXME: rename
+
+  void tau(int code, int p, int q);
+  void XtermHack();
+
+  void reportTerminalType();
+  void reportSecondaryAttributes();
+  void reportStatus();
+  void reportAnswerBack();
+  void reportCursorPosition();
+  void reportTerminalParms(int p);
+
+  void onScrollLock();
+  void scrollLock(const bool lock);
+
+  // clears the screen and resizes it to the specified
+  // number of columns
+  void clearScreenAndSetColumns(int columnCount);
+
+  CharCodes _charset[2];
+
+  DECpar _currParm;
+  DECpar _saveParm;
+
+  //hash table and timer for buffering calls to the session instance 
+  //to update the name of the session
+  //or window title.
+  //these calls occur when certain escape sequences are seen in the 
+  //output from the terminal
+  QHash<int,QString> _pendingTitleUpdates;
+  QTimer* _titleUpdateTimer;
+  
+};
+
+#endif // VT102EMULATION_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/konsole_wcwidth.cpp	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,216 @@
+/* $XFree86: xc/programs/xterm/wcwidth.character,v 1.3 2001/07/29 22:08:16 tsi Exp $ */
+/*
+ * This is an implementation of wcwidth() and wcswidth() as defined in
+ * "The Single UNIX Specification, Version 2, The Open Group, 1997"
+ * <http://www.UNIX-systems.org/online.html>
+ *
+ * Markus Kuhn -- 2001-01-12 -- public domain
+ */
+
+#include "unix/konsole_wcwidth.h"
+
+struct interval {
+  unsigned short first;
+  unsigned short last;
+};
+
+/* auxiliary function for binary search in interval table */
+static int bisearch(quint16 ucs, const struct interval *table, int max) {
+  int min = 0;
+  int mid;
+
+  if (ucs < table[0].first || ucs > table[max].last)
+    return 0;
+  while (max >= min) {
+    mid = (min + max) / 2;
+    if (ucs > table[mid].last)
+      min = mid + 1;
+    else if (ucs < table[mid].first)
+      max = mid - 1;
+    else
+      return 1;
+  }
+
+  return 0;
+}
+
+
+/* The following functions define the column width of an ISO 10646
+ * character as follows:
+ *
+ *    - The null character (U+0000) has a column width of 0.
+ *
+ *    - Other C0/C1 control characters and DEL will lead to a return
+ *      value of -1.
+ *
+ *    - Non-spacing and enclosing combining characters (general
+ *      category code Mn or Me in the Unicode database) have a
+ *      column width of 0.
+ *
+ *    - Other format characters (general category code Cf in the Unicode
+ *      database) and ZERO WIDTH SPACE (U+200B) have a column width of 0.
+ *
+ *    - Hangul Jamo medial vowels and final consonants (U+1160-U+11FF)
+ *      have a column width of 0.
+ *
+ *    - Spacing characters in the East Asian Wide (W) or East Asian
+ *      FullWidth (F) category as defined in Unicode Technical
+ *      Report #11 have a column width of 2.
+ *
+ *    - All remaining characters (including all printable
+ *      ISO 8859-1 and WGL4 characters, Unicode control characters,
+ *      etc.) have a column width of 1.
+ *
+ * This implementation assumes that quint16 characters are encoded
+ * in ISO 10646.
+ */
+
+int konsole_wcwidth(quint16 ucs)
+{
+  /* sorted list of non-overlapping intervals of non-spacing characters */
+  static const struct interval combining[] = {
+    { 0x0300, 0x034E }, { 0x0360, 0x0362 }, { 0x0483, 0x0486 },
+    { 0x0488, 0x0489 }, { 0x0591, 0x05A1 }, { 0x05A3, 0x05B9 },
+    { 0x05BB, 0x05BD }, { 0x05BF, 0x05BF }, { 0x05C1, 0x05C2 },
+    { 0x05C4, 0x05C4 }, { 0x064B, 0x0655 }, { 0x0670, 0x0670 },
+    { 0x06D6, 0x06E4 }, { 0x06E7, 0x06E8 }, { 0x06EA, 0x06ED },
+    { 0x070F, 0x070F }, { 0x0711, 0x0711 }, { 0x0730, 0x074A },
+    { 0x07A6, 0x07B0 }, { 0x0901, 0x0902 }, { 0x093C, 0x093C },
+    { 0x0941, 0x0948 }, { 0x094D, 0x094D }, { 0x0951, 0x0954 },
+    { 0x0962, 0x0963 }, { 0x0981, 0x0981 }, { 0x09BC, 0x09BC },
+    { 0x09C1, 0x09C4 }, { 0x09CD, 0x09CD }, { 0x09E2, 0x09E3 },
+    { 0x0A02, 0x0A02 }, { 0x0A3C, 0x0A3C }, { 0x0A41, 0x0A42 },
+    { 0x0A47, 0x0A48 }, { 0x0A4B, 0x0A4D }, { 0x0A70, 0x0A71 },
+    { 0x0A81, 0x0A82 }, { 0x0ABC, 0x0ABC }, { 0x0AC1, 0x0AC5 },
+    { 0x0AC7, 0x0AC8 }, { 0x0ACD, 0x0ACD }, { 0x0B01, 0x0B01 },
+    { 0x0B3C, 0x0B3C }, { 0x0B3F, 0x0B3F }, { 0x0B41, 0x0B43 },
+    { 0x0B4D, 0x0B4D }, { 0x0B56, 0x0B56 }, { 0x0B82, 0x0B82 },
+    { 0x0BC0, 0x0BC0 }, { 0x0BCD, 0x0BCD }, { 0x0C3E, 0x0C40 },
+    { 0x0C46, 0x0C48 }, { 0x0C4A, 0x0C4D }, { 0x0C55, 0x0C56 },
+    { 0x0CBF, 0x0CBF }, { 0x0CC6, 0x0CC6 }, { 0x0CCC, 0x0CCD },
+    { 0x0D41, 0x0D43 }, { 0x0D4D, 0x0D4D }, { 0x0DCA, 0x0DCA },
+    { 0x0DD2, 0x0DD4 }, { 0x0DD6, 0x0DD6 }, { 0x0E31, 0x0E31 },
+    { 0x0E34, 0x0E3A }, { 0x0E47, 0x0E4E }, { 0x0EB1, 0x0EB1 },
+    { 0x0EB4, 0x0EB9 }, { 0x0EBB, 0x0EBC }, { 0x0EC8, 0x0ECD },
+    { 0x0F18, 0x0F19 }, { 0x0F35, 0x0F35 }, { 0x0F37, 0x0F37 },
+    { 0x0F39, 0x0F39 }, { 0x0F71, 0x0F7E }, { 0x0F80, 0x0F84 },
+    { 0x0F86, 0x0F87 }, { 0x0F90, 0x0F97 }, { 0x0F99, 0x0FBC },
+    { 0x0FC6, 0x0FC6 }, { 0x102D, 0x1030 }, { 0x1032, 0x1032 },
+    { 0x1036, 0x1037 }, { 0x1039, 0x1039 }, { 0x1058, 0x1059 },
+    { 0x1160, 0x11FF }, { 0x17B7, 0x17BD }, { 0x17C6, 0x17C6 },
+    { 0x17C9, 0x17D3 }, { 0x180B, 0x180E }, { 0x18A9, 0x18A9 },
+    { 0x200B, 0x200F }, { 0x202A, 0x202E }, { 0x206A, 0x206F },
+    { 0x20D0, 0x20E3 }, { 0x302A, 0x302F }, { 0x3099, 0x309A },
+    { 0xFB1E, 0xFB1E }, { 0xFE20, 0xFE23 }, { 0xFEFF, 0xFEFF },
+    { 0xFFF9, 0xFFFB }
+  };
+
+  /* test for 8-bit control characters */
+  if (ucs == 0)
+    return 0;
+  if (ucs < 32 || (ucs >= 0x7f && ucs < 0xa0))
+    return -1;
+
+  /* binary search in table of non-spacing characters */
+  if (bisearch(ucs, combining,
+	       sizeof(combining) / sizeof(struct interval) - 1))
+    return 0;
+
+  /* if we arrive here, ucs is not a combining or C0/C1 control character */
+
+  return 1 +
+    (ucs >= 0x1100 &&
+     (ucs <= 0x115f ||                    /* Hangul Jamo init. consonants */
+      (ucs >= 0x2e80 && ucs <= 0xa4cf && (ucs & ~0x0011) != 0x300a &&
+       ucs != 0x303f) ||                  /* CJK ... Yi */
+      (ucs >= 0xac00 && ucs <= 0xd7a3) || /* Hangul Syllables */
+      (ucs >= 0xf900 && ucs <= 0xfaff) || /* CJK Compatibility Ideographs */
+      (ucs >= 0xfe30 && ucs <= 0xfe6f) || /* CJK Compatibility Forms */
+      (ucs >= 0xff00 && ucs <= 0xff5f) || /* Fullwidth Forms */
+      (ucs >= 0xffe0 && ucs <= 0xffe6) /* do not compare UINT16 with 0x20000 ||
+      (ucs >= 0x20000 && ucs <= 0x2ffff) */));
+}
+
+#if 0
+/*
+ * The following function is the same as konsole_wcwidth(), except that
+ * spacing characters in the East Asian Ambiguous (A) category as
+ * defined in Unicode Technical Report #11 have a column width of 2.
+ * This experimental variant might be useful for users of CJK legacy
+ * encodings who want to migrate to UCS. It is not otherwise
+ * recommended for general use.
+ */
+int konsole_wcwidth_cjk(quint16 ucs)
+{
+  /* sorted list of non-overlapping intervals of East Asian Ambiguous
+   * characters */
+  static const struct interval ambiguous[] = {
+    { 0x00A1, 0x00A1 }, { 0x00A4, 0x00A4 }, { 0x00A7, 0x00A8 },
+    { 0x00AA, 0x00AA }, { 0x00AD, 0x00AD }, { 0x00B0, 0x00B4 },
+    { 0x00B6, 0x00BA }, { 0x00BC, 0x00BF }, { 0x00C6, 0x00C6 },
+    { 0x00D0, 0x00D0 }, { 0x00D7, 0x00D8 }, { 0x00DE, 0x00E1 },
+    { 0x00E6, 0x00E6 }, { 0x00E8, 0x00EA }, { 0x00EC, 0x00ED },
+    { 0x00F0, 0x00F0 }, { 0x00F2, 0x00F3 }, { 0x00F7, 0x00FA },
+    { 0x00FC, 0x00FC }, { 0x00FE, 0x00FE }, { 0x0101, 0x0101 },
+    { 0x0111, 0x0111 }, { 0x0113, 0x0113 }, { 0x011B, 0x011B },
+    { 0x0126, 0x0127 }, { 0x012B, 0x012B }, { 0x0131, 0x0133 },
+    { 0x0138, 0x0138 }, { 0x013F, 0x0142 }, { 0x0144, 0x0144 },
+    { 0x0148, 0x014A }, { 0x014D, 0x014D }, { 0x0152, 0x0153 },
+    { 0x0166, 0x0167 }, { 0x016B, 0x016B }, { 0x01CE, 0x01CE },
+    { 0x01D0, 0x01D0 }, { 0x01D2, 0x01D2 }, { 0x01D4, 0x01D4 },
+    { 0x01D6, 0x01D6 }, { 0x01D8, 0x01D8 }, { 0x01DA, 0x01DA },
+    { 0x01DC, 0x01DC }, { 0x0251, 0x0251 }, { 0x0261, 0x0261 },
+    { 0x02C7, 0x02C7 }, { 0x02C9, 0x02CB }, { 0x02CD, 0x02CD },
+    { 0x02D0, 0x02D0 }, { 0x02D8, 0x02DB }, { 0x02DD, 0x02DD },
+    { 0x0391, 0x03A1 }, { 0x03A3, 0x03A9 }, { 0x03B1, 0x03C1 },
+    { 0x03C3, 0x03C9 }, { 0x0401, 0x0401 }, { 0x0410, 0x044F },
+    { 0x0451, 0x0451 }, { 0x2010, 0x2010 }, { 0x2013, 0x2016 },
+    { 0x2018, 0x2019 }, { 0x201C, 0x201D }, { 0x2020, 0x2021 },
+    { 0x2025, 0x2027 }, { 0x2030, 0x2030 }, { 0x2032, 0x2033 },
+    { 0x2035, 0x2035 }, { 0x203B, 0x203B }, { 0x2074, 0x2074 },
+    { 0x207F, 0x207F }, { 0x2081, 0x2084 }, { 0x20AC, 0x20AC },
+    { 0x2103, 0x2103 }, { 0x2105, 0x2105 }, { 0x2109, 0x2109 },
+    { 0x2113, 0x2113 }, { 0x2121, 0x2122 }, { 0x2126, 0x2126 },
+    { 0x212B, 0x212B }, { 0x2154, 0x2155 }, { 0x215B, 0x215B },
+    { 0x215E, 0x215E }, { 0x2160, 0x216B }, { 0x2170, 0x2179 },
+    { 0x2190, 0x2199 }, { 0x21D2, 0x21D2 }, { 0x21D4, 0x21D4 },
+    { 0x2200, 0x2200 }, { 0x2202, 0x2203 }, { 0x2207, 0x2208 },
+    { 0x220B, 0x220B }, { 0x220F, 0x220F }, { 0x2211, 0x2211 },
+    { 0x2215, 0x2215 }, { 0x221A, 0x221A }, { 0x221D, 0x2220 },
+    { 0x2223, 0x2223 }, { 0x2225, 0x2225 }, { 0x2227, 0x222C },
+    { 0x222E, 0x222E }, { 0x2234, 0x2237 }, { 0x223C, 0x223D },
+    { 0x2248, 0x2248 }, { 0x224C, 0x224C }, { 0x2252, 0x2252 },
+    { 0x2260, 0x2261 }, { 0x2264, 0x2267 }, { 0x226A, 0x226B },
+    { 0x226E, 0x226F }, { 0x2282, 0x2283 }, { 0x2286, 0x2287 },
+    { 0x2295, 0x2295 }, { 0x2299, 0x2299 }, { 0x22A5, 0x22A5 },
+    { 0x22BF, 0x22BF }, { 0x2312, 0x2312 }, { 0x2460, 0x24BF },
+    { 0x24D0, 0x24E9 }, { 0x2500, 0x254B }, { 0x2550, 0x2574 },
+    { 0x2580, 0x258F }, { 0x2592, 0x2595 }, { 0x25A0, 0x25A1 },
+    { 0x25A3, 0x25A9 }, { 0x25B2, 0x25B3 }, { 0x25B6, 0x25B7 },
+    { 0x25BC, 0x25BD }, { 0x25C0, 0x25C1 }, { 0x25C6, 0x25C8 },
+    { 0x25CB, 0x25CB }, { 0x25CE, 0x25D1 }, { 0x25E2, 0x25E5 },
+    { 0x25EF, 0x25EF }, { 0x2605, 0x2606 }, { 0x2609, 0x2609 },
+    { 0x260E, 0x260F }, { 0x261C, 0x261C }, { 0x261E, 0x261E },
+    { 0x2640, 0x2640 }, { 0x2642, 0x2642 }, { 0x2660, 0x2661 },
+    { 0x2663, 0x2665 }, { 0x2667, 0x266A }, { 0x266C, 0x266D },
+    { 0x266F, 0x266F }, { 0x300A, 0x300B }, { 0x301A, 0x301B },
+    { 0xE000, 0xF8FF }, { 0xFFFD, 0xFFFD }
+  };
+
+  /* binary search in table of non-spacing characters */
+  if (bisearch(ucs, ambiguous,
+	       sizeof(ambiguous) / sizeof(struct interval) - 1))
+    return 2;
+
+  return konsole_wcwidth(ucs);
+}
+#endif
+
+// single byte char: +1, multi byte char: +2
+int string_width( const QString &txt )
+{
+  int w = 0;
+  for ( int i = 0; i < txt.length(); ++i )
+     w += konsole_wcwidth( txt[ i ].unicode() );
+ return w;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/konsole_wcwidth.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,24 @@
+/* $XFree86: xc/programs/xterm/wcwidth.h,v 1.2 2001/06/18 19:09:27 dickey Exp $ */
+
+/* Markus Kuhn -- 2001-01-12 -- public domain */
+/* Adaptions for KDE by Waldo Bastian <bastian@kde.org> */
+/*
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>
+*/
+
+
+#ifndef	_KONSOLE_WCWIDTH_H_
+#define	_KONSOLE_WCWIDTH_H_
+
+// Qt
+#include <QtCore/QBool>
+#include <QtCore/QString>
+
+int konsole_wcwidth(quint16 ucs);
+#if 0
+int konsole_wcwidth_cjk(Q_UINT16 ucs);
+#endif
+
+int string_width( const QString &txt );
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/kpty.cpp	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,484 @@
+/*
+
+   This file is part of the KDE libraries
+   Copyright (C) 2002 Waldo Bastian <bastian@kde.org>
+   Copyright (C) 2002-2003,2007 Oswald Buddenhagen <ossi@kde.org>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+   This library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Library General Public
+   License as published by the Free Software Foundation; either
+   version 2 of the License, or (at your option) any later version.
+
+   This library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Library General Public License for more details.
+
+   You should have received a copy of the GNU Library General Public License
+   along with this library; see the file COPYING.LIB.  If not, write to
+   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+   Boston, MA 02110-1301, USA.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include "unix/kpty_p.h"
+
+#ifdef __sgi
+#define __svr4__
+#endif
+
+#ifdef __osf__
+#define _OSF_SOURCE
+#include <float.h>
+#endif
+
+#ifdef _AIX
+#define _ALL_SOURCE
+#endif
+
+// __USE_XOPEN isn't defined by default in ICC
+// (needed for ptsname(), grantpt() and unlockpt())
+#ifdef __INTEL_COMPILER
+#  ifndef __USE_XOPEN
+#    define __USE_XOPEN
+#  endif
+#endif
+
+#include <sys/types.h>
+#include <sys/ioctl.h>
+#include <sys/time.h>
+#include <sys/resource.h>
+#include <sys/stat.h>
+#include <sys/param.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <time.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include <grp.h>
+
+#ifdef Q_OS_MAC
+# include <util.h>
+#else
+# if defined(HAVE_PTY_H)
+#  include <pty.h>
+# endif
+# ifdef HAVE_LIBUTIL_H
+#  include <libutil.h>
+# elif defined(HAVE_UTIL_H)
+#  include <util.h>
+# endif
+#endif
+
+/*
+#ifdef HAVE_UTEMPTER
+extern "C" {
+# include <utempter.h>
+}
+#else
+# include <utmp.h>
+# ifdef HAVE_UTMPX
+#  include <utmpx.h>
+# endif
+# if !defined(_PATH_UTMPX) && defined(_UTMPX_FILE)
+#  define _PATH_UTMPX _UTMPX_FILE
+# endif
+# if !defined(_PATH_WTMPX) && defined(_WTMPX_FILE)
+#  define _PATH_WTMPX _WTMPX_FILE
+# endif
+#endif
+*/
+
+/* for HP-UX (some versions) the extern C is needed, and for other
+   platforms it doesn't hurt */
+extern "C" {
+#include <termios.h>
+#if defined(HAVE_TERMIO_H)
+# include <termio.h> // struct winsize on some systems
+#endif
+}
+
+#if defined (_HPUX_SOURCE)
+# define _TERMIOS_INCLUDED
+# include <bsdtty.h>
+#endif
+
+#ifdef HAVE_SYS_STROPTS_H
+# include <sys/stropts.h>	// Defines I_PUSH
+# define _NEW_TTY_CTRL
+#endif
+
+#if defined (__FreeBSD__) || defined (__NetBSD__) || defined (__OpenBSD__) || defined (__bsdi__) || defined(__APPLE__) || defined (__DragonFly__)
+# define _tcgetattr(fd, ttmode) ioctl(fd, TIOCGETA, (char *)ttmode)
+#else
+# if defined(_HPUX_SOURCE) || defined(__Lynx__) || defined (__CYGWIN__)
+#  define _tcgetattr(fd, ttmode) tcgetattr(fd, ttmode)
+# else
+#  define _tcgetattr(fd, ttmode) ioctl(fd, TCGETS, (char *)ttmode)
+# endif
+#endif
+
+#if defined (__FreeBSD__) || defined (__NetBSD__) || defined (__OpenBSD__) || defined (__bsdi__) || defined(__APPLE__) || defined (__DragonFly__)
+# define _tcsetattr(fd, ttmode) ioctl(fd, TIOCSETA, (char *)ttmode)
+#else
+# if defined(_HPUX_SOURCE) || defined(__CYGWIN__)
+#  define _tcsetattr(fd, ttmode) tcsetattr(fd, TCSANOW, ttmode)
+# else
+#  define _tcsetattr(fd, ttmode) ioctl(fd, TCSETS, (char *)ttmode)
+# endif
+#endif
+
+#include <QtCore>
+
+// not defined on HP-UX for example
+#ifndef CTRL
+# define CTRL(x) ((x) & 037)
+#endif
+
+#define TTY_GROUP "tty"
+
+///////////////////////
+// private functions //
+///////////////////////
+
+//////////////////
+// private data //
+//////////////////
+
+KPtyPrivate::KPtyPrivate(KPty* parent) :
+    masterFd(-1), slaveFd(-1), ownMaster(true), q_ptr(parent)
+{
+}
+
+KPtyPrivate::KPtyPrivate(KPty *parent, int _masterFd, int _slaveFd):
+    masterFd(_masterFd), slaveFd(_slaveFd), ownMaster(true), q_ptr(parent)
+{
+}
+
+
+KPtyPrivate::~KPtyPrivate()
+{
+}
+
+#ifndef HAVE_OPENPTY
+bool KPtyPrivate::chownpty(bool)
+{
+//    return !QProcess::execute(KStandardDirs::findExe("kgrantpty"),
+//        QStringList() << (grant?"--grant":"--revoke") << QString::number(masterFd));
+    return true;
+}
+#endif
+
+/////////////////////////////
+// public member functions //
+/////////////////////////////
+
+KPty::KPty() :
+    d_ptr(new KPtyPrivate(this))
+{
+}
+
+KPty::KPty(int masterFd, int slaveFd) :
+    d_ptr(new KPtyPrivate(this, masterFd, slaveFd))
+{
+}
+
+KPty::KPty(KPtyPrivate *d) :
+    d_ptr(d)
+{
+    d_ptr->q_ptr = this;
+}
+
+KPty::~KPty()
+{
+    close();
+    delete d_ptr;
+}
+
+bool KPty::open()
+{
+  Q_D(KPty);
+
+  if (d->masterFd >= 0) {
+      return true;
+  }
+
+  d->ownMaster = true;
+
+  QByteArray ptyName;
+
+  // Find a master pty that we can open ////////////////////////////////
+
+  // Because not all the pty animals are created equal, they want to
+  // be opened by several different methods.
+
+  // We try, as we know them, one by one.
+
+#ifdef HAVE_OPENPTY
+
+  char ptsn[PATH_MAX];
+  if (::openpty( &d->masterFd, &d->slaveFd, ptsn, 0, 0))
+  {
+    d->masterFd = -1;
+    d->slaveFd = -1;
+    qWarning() << "Can't open a pseudo teletype";
+    return false;
+  }
+  d->ttyName = ptsn;
+
+#else
+
+#ifdef HAVE__GETPTY // irix
+
+  char *ptsn = _getpty(&d->masterFd, O_RDWR|O_NOCTTY, S_IRUSR|S_IWUSR, 0);
+  if (ptsn) {
+    d->ttyName = ptsn;
+    goto grantedpt;
+  }
+
+#elif defined(HAVE_PTSNAME) || defined(TIOCGPTN)
+
+#ifdef HAVE_POSIX_OPENPT
+  d->masterFd = ::posix_openpt(O_RDWR|O_NOCTTY);
+#elif defined(HAVE_GETPT)
+  d->masterFd = ::getpt();
+#elif defined(PTM_DEVICE)
+  d->masterFd = ::open(PTM_DEVICE, O_RDWR|O_NOCTTY);
+#else
+# error No method to open a PTY master detected.
+#endif
+  if (d->masterFd >= 0)
+  {
+#ifdef HAVE_PTSNAME
+    char *ptsn = ptsname(d->masterFd);
+    if (ptsn) {
+        d->ttyName = ptsn;
+#else
+    int ptyno;
+    if (!ioctl(d->masterFd, TIOCGPTN, &ptyno)) {
+        char buf[32];
+        sprintf(buf, "/dev/pts/%d", ptyno);
+        d->ttyName = buf;
+#endif
+#ifdef HAVE_GRANTPT
+        if (!grantpt(d->masterFd))
+           goto grantedpt;
+#else
+        goto gotpty;
+#endif
+    }
+    ::close(d->masterFd);
+    d->masterFd = -1;
+  }
+#endif // HAVE_PTSNAME || TIOCGPTN
+
+  // Linux device names, FIXME: Trouble on other systems?
+  for (const char* s3 = "pqrstuvwxyzabcde"; *s3; s3++)
+  {
+    for (const char* s4 = "0123456789abcdef"; *s4; s4++)
+    {
+      ptyName = QString().sprintf("/dev/pty%c%c", *s3, *s4).toAscii();
+      d->ttyName = QString().sprintf("/dev/tty%c%c", *s3, *s4).toAscii();
+
+      d->masterFd = ::open(ptyName.data(), O_RDWR);
+      if (d->masterFd >= 0)
+      {
+#ifdef Q_OS_SOLARIS
+        /* Need to check the process group of the pty.
+         * If it exists, then the slave pty is in use,
+         * and we need to get another one.
+         */
+        int pgrp_rtn;
+        if (ioctl(d->masterFd, TIOCGPGRP, &pgrp_rtn) == 0 || errno != EIO) {
+          ::close(d->masterFd);
+          d->masterFd = -1;
+          continue;
+        }
+#endif /* Q_OS_SOLARIS */
+        if (!access(d->ttyName.data(),R_OK|W_OK)) // checks availability based on permission bits
+        {
+          if (!geteuid())
+          {
+            struct group* p = getgrnam(TTY_GROUP);
+            if (!p)
+              p = getgrnam("wheel");
+            gid_t gid = p ? p->gr_gid : getgid ();
+
+		 if (!chown(d->ttyName.data(), getuid(), gid)) {
+			chmod(d->ttyName.data(), S_IRUSR|S_IWUSR|S_IWGRP);
+		 }
+	  }
+	  goto gotpty;
+	}
+	::close(d->masterFd);
+	d->masterFd = -1;
+		}
+	 }
+  }
+
+  qWarning() << "Can't open a pseudo teletype";
+  return false;
+
+ gotpty:
+  struct stat st;
+  if (stat(d->ttyName.data(), &st))
+    return false; // this just cannot happen ... *cough*  Yeah right, I just
+                  // had it happen when pty #349 was allocated.  I guess
+                  // there was some sort of leak?  I only had a few open.
+  if (((st.st_uid != getuid()) ||
+       (st.st_mode & (S_IRGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH))) &&
+      !d->chownpty(true))
+  {
+    qWarning()
+      << "chownpty failed for device " << ptyName << "::" << d->ttyName
+      << "\nThis means the communication can be eavesdropped." << endl;
+  }
+
+#if defined(HAVE_GRANTPT) || defined(HAVE__GETPTY)
+ grantedpt:
+#endif
+
+#ifdef HAVE_REVOKE
+  revoke(d->ttyName.data());
+#endif
+
+#ifdef HAVE_UNLOCKPT
+  unlockpt(d->masterFd);
+#elif defined(TIOCSPTLCK)
+  int flag = 0;
+  ioctl(d->masterFd, TIOCSPTLCK, &flag);
+#endif
+
+  d->slaveFd = ::open(d->ttyName.data(), O_RDWR | O_NOCTTY);
+  if (d->slaveFd < 0)
+  {
+    qWarning() << "Can't open slave pseudo teletype";
+    ::close(d->masterFd);
+    d->masterFd = -1;
+    return false;
+  }
+
+#if (defined(__svr4__) || defined(__sgi__))
+  // Solaris
+  ioctl(d->slaveFd, I_PUSH, "ptem");
+  ioctl(d->slaveFd, I_PUSH, "ldterm");
+#endif
+
+#endif /* HAVE_OPENPTY */
+  fcntl(d->masterFd, F_SETFD, FD_CLOEXEC);
+  fcntl(d->slaveFd, F_SETFD, FD_CLOEXEC);
+
+  struct ::termios t;
+  tcGetAttr(&t);
+  t.c_lflag &= ~ECHOCTL;
+  tcSetAttr(&t);
+  return true;
+}
+
+void KPty::closeSlave()
+{
+    Q_D(KPty);
+
+    if (d->slaveFd < 0)
+        return;
+    ::close(d->slaveFd);
+    d->slaveFd = -1;
+}
+
+void KPty::close()
+{
+   Q_D(KPty);
+
+   if (d->masterFd < 0)
+      return;
+   closeSlave();
+   if (d->ownMaster) {
+#ifndef HAVE_OPENPTY
+   // don't bother resetting unix98 pty, it will go away after closing master anyway.
+   if (memcmp(d->ttyName.data(), "/dev/pts/", 9)) {
+      if (!geteuid()) {
+         struct stat st;
+         if (!stat(d->ttyName.data(), &st)) {
+            if (!chown(d->ttyName.data(), 0, st.st_gid == getgid() ? 0 : -1)) {
+              chmod(d->ttyName.data(), S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
+            }
+         }
+      } else {
+         fcntl(d->masterFd, F_SETFD, 0);
+         d->chownpty(false);
+      }
+   }
+   #endif
+   }
+   ::close(d->masterFd);
+   d->masterFd = -1;
+}
+
+// XXX Supposedly, tc[gs]etattr do not work with the master on Solaris.
+// Please verify.
+
+bool KPty::tcGetAttr(struct ::termios *ttmode) const
+{
+    Q_D(const KPty);
+
+    return _tcgetattr(d->masterFd, ttmode) == 0;
+}
+
+bool KPty::tcSetAttr(struct ::termios *ttmode)
+{
+    Q_D(KPty);
+
+    return _tcsetattr(d->masterFd, ttmode) == 0;
+}
+
+bool KPty::setWinSize(int lines, int columns)
+{
+    Q_D(KPty);
+
+    struct winsize winSize;
+    memset(&winSize, 0, sizeof(winSize));
+    winSize.ws_row = (unsigned short)lines;
+    winSize.ws_col = (unsigned short)columns;
+    return ioctl(d->masterFd, TIOCSWINSZ, (char *)&winSize) == 0;
+}
+
+bool KPty::setEcho(bool echo)
+{
+    struct ::termios ttmode;
+    if (!tcGetAttr(&ttmode))
+        return false;
+    if (!echo)
+        ttmode.c_lflag &= ~ECHO;
+    else
+        ttmode.c_lflag |= ECHO;
+    return tcSetAttr(&ttmode);
+}
+
+const char *KPty::ttyName() const
+{
+    Q_D(const KPty);
+
+    return d->ttyName.data();
+}
+
+int KPty::masterFd() const
+{
+    Q_D(const KPty);
+
+    return d->masterFd;
+}
+
+int KPty::slaveFd() const
+{
+    Q_D(const KPty);
+
+    return d->slaveFd;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/kpty.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,166 @@
+/* This file is part of the KDE libraries
+
+    Copyright (C) 2003,2007 Oswald Buddenhagen <ossi@kde.org>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Library General Public
+    License as published by the Free Software Foundation; either
+    version 2 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Library General Public License for more details.
+
+    You should have received a copy of the GNU Library General Public License
+    along with this library; see the file COPYING.LIB.  If not, write to
+    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+    Boston, MA 02110-1301, USA.
+*/
+
+#ifndef kpty_h
+#define kpty_h
+
+#include <QtCore>
+
+struct KPtyPrivate;
+struct termios;
+
+/**
+ * Provides primitives for opening & closing a pseudo TTY pair, assigning the
+ * controlling TTY, utmp registration and setting various terminal attributes.
+ */
+class KPty {
+    Q_DECLARE_PRIVATE(KPty)
+
+public:
+
+  /**
+   * Constructor
+   */
+  KPty();
+  KPty(int masterFd, int slaveFd);
+
+  /**
+   * Destructor:
+   *
+   *  If the pty is still open, it will be closed. Note, however, that
+   *  an utmp registration is @em not undone.
+  */
+  ~KPty();
+
+  /**
+   * Create a pty master/slave pair.
+   *
+   * @return true if a pty pair was successfully opened
+   */
+  bool open();
+
+  /**
+   * Close the pty master/slave pair.
+   */
+  void close();
+
+  /**
+   * Close the pty slave descriptor.
+   *
+   * When creating the pty, KPty also opens the slave and keeps it open.
+   * Consequently the master will never receive an EOF notification.
+   * Usually this is the desired behavior, as a closed pty slave can be
+   * reopened any time - unlike a pipe or socket. However, in some cases
+   * pipe-alike behavior might be desired.
+   *
+   * After this function was called, slaveFd() and setCTty() cannot be
+   * used.
+   */
+  void closeSlave();
+
+  /**
+   * Wrapper around tcgetattr(3).
+   *
+   * This function can be used only while the PTY is open.
+   * You will need an #include &lt;termios.h&gt; to do anything useful
+   * with it.
+   *
+   * @param ttmode a pointer to a termios structure.
+   *  Note: when declaring ttmode, @c struct @c ::termios must be used -
+   *  without the '::' some version of HP-UX thinks, this declares
+   *  the struct in your class, in your method.
+   * @return @c true on success, false otherwise
+   */
+  bool tcGetAttr(struct ::termios *ttmode) const;
+
+  /**
+   * Wrapper around tcsetattr(3) with mode TCSANOW.
+   *
+   * This function can be used only while the PTY is open.
+   *
+   * @param ttmode a pointer to a termios structure.
+   * @return @c true on success, false otherwise. Note that success means
+   *  that @em at @em least @em one attribute could be set.
+   */
+  bool tcSetAttr(struct ::termios *ttmode);
+
+  /**
+   * Change the logical (screen) size of the pty.
+   * The default is 24 lines by 80 columns.
+   *
+   * This function can be used only while the PTY is open.
+   *
+   * @param lines the number of rows
+   * @param columns the number of columns
+   * @return @c true on success, false otherwise
+   */
+  bool setWinSize(int lines, int columns);
+
+  /**
+   * Set whether the pty should echo input.
+   *
+   * Echo is on by default.
+   * If the output of automatically fed (non-interactive) PTY clients
+   * needs to be parsed, disabling echo often makes it much simpler.
+   *
+   * This function can be used only while the PTY is open.
+   *
+   * @param echo true if input should be echoed.
+   * @return @c true on success, false otherwise
+   */
+  bool setEcho(bool echo);
+
+  /**
+   * @return the name of the slave pty device.
+   *
+   * This function should be called only while the pty is open.
+   */
+  const char *ttyName() const;
+
+  /**
+   * @return the file descriptor of the master pty
+   *
+   * This function should be called only while the pty is open.
+   */
+  int masterFd() const;
+
+  /**
+   * @return the file descriptor of the slave pty
+   *
+   * This function should be called only while the pty slave is open.
+   */
+  int slaveFd() const;
+
+protected:
+  /**
+   * @internal
+   */
+  KPty(KPtyPrivate *d);
+
+  /**
+   * @internal
+   */
+  KPtyPrivate * const d_ptr;
+};
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/unix/kpty_p.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,50 @@
+/* This file is part of the KDE libraries
+
+    Copyright (C) 2003,2007 Oswald Buddenhagen <ossi@kde.org>
+
+    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Library General Public
+    License as published by the Free Software Foundation; either
+    version 2 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Library General Public License for more details.
+
+    You should have received a copy of the GNU Library General Public License
+    along with this library; see the file COPYING.LIB.  If not, write to
+    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+    Boston, MA 02110-1301, USA.
+*/
+
+#ifndef kpty_p_h
+#define kpty_p_h
+
+#include "unix/kpty.h"
+
+#include <QtCore/QByteArray>
+
+struct KPtyPrivate {
+    Q_DECLARE_PUBLIC(KPty)
+
+    KPtyPrivate(KPty* parent);
+    KPtyPrivate(KPty* parent, int masterFd, int slaveFd);
+
+    virtual ~KPtyPrivate();
+#ifndef HAVE_OPENPTY
+    bool chownpty(bool grant);
+#endif
+
+    int masterFd;
+    int slaveFd;
+    bool ownMaster:1;
+
+    QByteArray ttyName;
+
+    KPty *q_ptr;
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/win32/QTerminalColors.cpp	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,48 @@
+/*
+
+Copyright (C) 2011 Michael Goffioul.
+
+This file is part of QConsole.
+
+Foobar is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+QConsole 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 Foobar.  If not, see <http://www.gnu.org/licenses/>.
+
+*/
+
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+
+#include "QTerminalColors.h"
+
+//////////////////////////////////////////////////////////////////////////////
+
+QConsoleColors::QConsoleColors (void)
+    : QMap<int, QColor> ()
+{
+  (*this)[0]  = Qt::black;
+  (*this)[1]  = Qt::darkBlue;
+  (*this)[2]  = Qt::darkGreen;
+  (*this)[3]  = Qt::darkCyan;
+  (*this)[4]  = Qt::darkRed;
+  (*this)[5]  = Qt::darkMagenta;
+  (*this)[6]  = Qt::darkYellow;
+  (*this)[7]  = Qt::lightGray;
+  (*this)[8]  = Qt::darkGray;
+  (*this)[9]  = Qt::blue;
+  (*this)[10] = Qt::green;
+  (*this)[11] = Qt::cyan;
+  (*this)[12] = Qt::red;
+  (*this)[13] = Qt::magenta;
+  (*this)[14] = Qt::yellow;
+  (*this)[15] = Qt::white;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/win32/QTerminalColors.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,38 @@
+/*
+
+Copyright (C) 2011 Michael Goffioul.
+
+This file is part of QConsole.
+
+Foobar is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+QConsole 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 Foobar.  If not, see <http://www.gnu.org/licenses/>.
+
+*/
+
+#ifndef __QConsoleColors_h__
+#define __QConsoleColors_h__ 1
+
+#include <QColor>
+#include <QMap>
+
+//////////////////////////////////////////////////////////////////////////////
+
+class QConsoleColors : public QMap<int, QColor>
+{
+public:
+  QConsoleColors (void);
+};
+
+//////////////////////////////////////////////////////////////////////////////
+
+#endif // __QConsoleColors_h__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/win32/QWinTerminalImpl.cpp	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,914 @@
+/*
+
+Copyright (C) 2011 Michael Goffioul.
+
+This file is part of QConsole.
+
+Foobar is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+QConsole 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 Foobar.  If not, see <http://www.gnu.org/licenses/>.
+
+*/
+
+#include <QApplication>
+#include <QColor>
+#include <QFont>
+#include <QHBoxLayout>
+#include <QPaintEvent>
+#include <QPainter>
+#include <QResizeEvent>
+#include <QScrollBar>
+#include <QtDebug>
+#include <QThread>
+#include <QTimer>
+
+#include <fcntl.h>
+#include <io.h>
+#include <stdio.h>
+#include <stdarg.h>
+#define WIN32_LEAN_AND_MEAN
+#define _WIN32_WINNT 0x0500 
+#include <windows.h>
+#include <cstring>
+
+#include "QWinTerminalImpl.h"
+#include "QTerminalColors.h"
+
+// Uncomment to log activity to LOGFILENAME
+// #define DEBUG_QCONSOLE
+#define LOGFILENAME "QConsole.log"
+// Uncomment to create hidden console window
+#define HIDDEN_CONSOLE
+
+#ifdef _MSC_VER
+# pragma warning(disable : 4996)
+#endif
+
+//////////////////////////////////////////////////////////////////////////////
+
+class QConsoleView : public QWidget
+{
+public:
+  QConsoleView (QWinTerminalImpl* parent = 0) : QWidget (parent), q (parent) { }
+  ~QConsoleView (void) { }
+
+protected:
+  void paintEvent (QPaintEvent* event) { q->viewPaintEvent (this, event); }
+  void resizeEvent (QResizeEvent* event) { q->viewResizeEvent (this, event); }
+
+private:
+  QWinTerminalImpl* q;
+};
+
+//////////////////////////////////////////////////////////////////////////////
+
+class QConsoleThread : public QThread
+{
+public:
+  QConsoleThread (QWinTerminalImpl* console) : QThread (console), q (console) { }
+
+protected:
+  void run (void)
+    { q->start (); }
+
+private:
+  QWinTerminalImpl* q;
+};
+
+//////////////////////////////////////////////////////////////////////////////
+
+class QConsolePrivate
+{
+  friend class QWinTerminalImpl;
+
+public:
+  QConsolePrivate (QWinTerminalImpl* parent, const QString& cmd = QString ());
+  ~QConsolePrivate (void);
+
+  void updateConsoleSize (bool sync = false);
+  void syncConsoleParameters (void);
+  void grabConsoleBuffer (CHAR_INFO* buf = 0);
+  void updateScrollBar (void);
+  void setScrollValue (int value);
+  void updateConsoleView (bool grab = true);
+  void monitorConsole (void);
+  void startCommand (void);
+  void sendConsoleText (const QString& s);
+
+  void log (const char* fmt, ...);
+
+  void closeStandardIO (int fd, DWORD stdHandleId, const char* name);
+  void setupStandardIO (DWORD stdHandleId, int fd, const char* name,
+                        const char* devName);
+
+private:
+  QWinTerminalImpl* q;
+
+private:
+  QFont m_font;
+  QColor m_backgroundColor;
+  QString m_command;
+  QConsoleColors m_colors;
+  bool m_inWheelEvent;
+  QString m_title;
+
+  QSize m_charSize;
+  QSize m_bufferSize;
+  QRect m_consoleRect;
+  QPoint m_cursorPos;
+
+  HANDLE m_stdOut;
+  HWND m_consoleWindow;
+  CHAR_INFO* m_buffer;
+  CHAR_INFO* m_tmpBuffer;
+  HANDLE m_process;
+
+  QConsoleView* m_consoleView;
+  QScrollBar* m_scrollBar;
+  QTimer* m_consoleWatcher;
+  QConsoleThread *m_consoleThread;
+};
+
+//////////////////////////////////////////////////////////////////////////////
+
+QConsolePrivate::QConsolePrivate (QWinTerminalImpl* parent, const QString& cmd)
+    : q (parent), m_command (cmd), m_process (NULL), m_inWheelEvent (false)
+{
+  log (NULL);
+
+  // Possibly detach from any existing console
+  log ("Detaching from existing console (if any)...\n");
+  FreeConsole ();
+  log ("Closing standard IO...\n");
+  closeStandardIO (0, STD_INPUT_HANDLE, "STDIN");
+  closeStandardIO (1, STD_OUTPUT_HANDLE, "STDOUT");
+  closeStandardIO (2, STD_ERROR_HANDLE, "STDERR");
+
+#ifdef HIDDEN_CONSOLE
+  HWINSTA hOrigSta, hNewSta;
+
+  // Create new (hidden) console
+  hOrigSta = GetProcessWindowStation ();
+  hNewSta = CreateWindowStation (NULL, 0, GENERIC_ALL, NULL);
+  log ("Current Windows station: %p.\nNew Windows station: %p.\n", hOrigSta,
+       hNewSta);
+  if (! SetProcessWindowStation (hNewSta))
+    log ("Failed to switch to new Windows station.\n");
+#endif
+  if (! AllocConsole ())
+    log ("Failed to create new console.\n");
+#ifdef HIDDEN_CONSOLE
+  if (! SetProcessWindowStation (hOrigSta))
+    log ("Failed to restore original Windows station.\n");
+  if (! CloseWindowStation (hNewSta))
+    log ("Failed to close new Windows station.\n");
+#endif
+
+  log ("New (hidden) console created.\n");
+
+  setupStandardIO (STD_INPUT_HANDLE,  0, "STDIN",  "CONIN$");
+  setupStandardIO (STD_OUTPUT_HANDLE, 1, "STDOUT", "CONOUT$");
+  setupStandardIO (STD_ERROR_HANDLE,  2, "STDERR", "CONOUT$");
+
+  log ("Standard input/output/error set up.\n");
+
+  *stdin = *(fdopen (0, "rb"));
+  *stdout = *(fdopen (1, "wb"));
+  *stderr = *(fdopen (2, "wb"));
+
+  log ("POSIX standard streams created.\n");
+
+  setvbuf (stdin, NULL, _IONBF, 0);
+  setvbuf (stdout, NULL, _IONBF, 0);
+  setvbuf (stderr, NULL, _IONBF, 0);
+
+  log ("POSIX standard stream buffers adjusted.\n");
+
+  HANDLE hStdOut = GetStdHandle (STD_OUTPUT_HANDLE);
+
+  log ("Console allocated: hStdOut: %p\n", hStdOut);
+
+  m_stdOut = hStdOut;
+  m_consoleWindow = GetConsoleWindow ();
+
+  // In case the console window hasn't been created hidden...
+  ShowWindow (m_consoleWindow, SW_HIDE);
+
+  CONSOLE_SCREEN_BUFFER_INFO sbi;
+
+  GetConsoleScreenBufferInfo (hStdOut, &sbi);
+  m_bufferSize = QSize (sbi.dwSize.X, qMax (sbi.dwSize.Y, (SHORT)500));
+  m_consoleRect = QRect (sbi.srWindow.Left, sbi.srWindow.Top,
+                         sbi.srWindow.Right - sbi.srWindow.Left + 1,
+                         sbi.srWindow.Bottom - sbi.srWindow.Top + 1);
+  m_cursorPos = QPoint (sbi.dwCursorPosition.X, sbi.dwCursorPosition.Y);
+
+  log ("Initial console parameters:\n");
+  log ("  buffer size: %d x %d\n", m_bufferSize.width (),
+       m_bufferSize.height ());
+  log ("  window: (%d, %d) -> (%d, %d) [%d x %d]\n",
+       m_consoleRect.left (), m_consoleRect.top (),
+       m_consoleRect.right (), m_consoleRect.bottom (),
+       m_consoleRect.width (), m_consoleRect.height ());
+
+  wchar_t titleBuf[260];
+  GetConsoleTitleW (titleBuf, sizeof (titleBuf));
+  q->setWindowTitle (QString::fromWCharArray (titleBuf));
+
+  m_font.setFamily ("Lucida Console");
+  m_font.setPointSize (9);
+  m_font.setStyleHint (QFont::TypeWriter);
+  m_backgroundColor = Qt::black;
+
+  m_buffer = m_tmpBuffer = 0;
+
+  m_consoleView = new QConsoleView (parent);
+  m_scrollBar = new QScrollBar (Qt::Vertical, parent);
+
+  QHBoxLayout* l = new QHBoxLayout (parent);
+  l->setContentsMargins (0, 0, 0, 0);
+  l->setSpacing (0);
+  l->addWidget (m_consoleView, 1);
+  l->addWidget (m_scrollBar, 0);
+
+  m_consoleView->setPalette (QPalette (m_backgroundColor));
+  m_consoleView->setAutoFillBackground (true);
+  m_consoleView->setFont (m_font);
+  parent->setFocusPolicy (Qt::StrongFocus);
+  parent->winId ();
+
+  updateScrollBar ();
+
+  m_consoleWatcher = new QTimer (parent);
+  m_consoleWatcher->setInterval (10);
+  m_consoleWatcher->setSingleShot (false);
+  
+  QObject::connect (m_scrollBar, SIGNAL (valueChanged (int)),
+                    q, SLOT (scrollValueChanged (int)));
+  QObject::connect (m_consoleWatcher, SIGNAL (timeout (void)),
+                    q, SLOT (monitorConsole (void)));
+
+  m_consoleWatcher->start ();
+
+  if (m_command.isEmpty ())
+    m_consoleThread = 0;
+  else
+    {
+      m_consoleThread = new QConsoleThread (q);
+      QObject::connect (m_consoleThread, SIGNAL (finished (void)),
+                        q, SIGNAL (terminated (void)));
+      m_consoleThread->start ();
+    }
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+QConsolePrivate::~QConsolePrivate (void)
+{
+  if (m_consoleThread && m_consoleThread->isRunning () && m_process)
+    {
+      TerminateProcess (m_process, (UINT)-1);
+      m_consoleThread->wait ();
+    }
+  if (m_buffer)
+    delete [] m_buffer;
+  if (m_tmpBuffer)
+    delete [] m_tmpBuffer;
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QConsolePrivate::setupStandardIO (DWORD stdHandleId, int targetFd,
+                                       const char* name, const char* devName)
+{
+  log ("Opening %s...\n", devName);
+
+  int fd = open (devName, _O_RDWR | _O_BINARY);
+
+  if (fd != -1)
+    {
+      if (fd != targetFd)
+        {
+          log ("Opened %s is not at target file descriptor %d, "
+               "duplicating...\n", name, targetFd);
+          if (dup2 (fd, targetFd) == -1)
+            log ("Failed to duplicate file descriptor: errno=%d.\n", errno);
+          if (close (fd) == -1)
+            log ("Failed to close original file descriptor: errno=%d.\n",
+                 errno);
+        }
+      else
+        log ("%s opened and assigned to file descriptor %d.\n", devName, fd);
+      if (! SetStdHandle (stdHandleId, (HANDLE) _get_osfhandle (targetFd)))
+        log ("Failed to re-assign %s: error=%08x.\n", name, GetLastError ());
+    }
+  else
+    log ("Failed to open %s: errno=%d.\n", devName, errno);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QConsolePrivate::closeStandardIO (int fd, DWORD stdHandleId,
+                                       const char* name)
+{
+  if (close (fd) == -1)
+    log ("Failed to close file descriptor %d: errno=%d.\n", fd, errno);
+  if (! CloseHandle (GetStdHandle (stdHandleId)))
+    log ("Failed to close Win32 %s: error=%08x.\n", name, GetLastError ());
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QConsolePrivate::log (const char* fmt, ...)
+{
+#ifdef DEBUG_QCONSOLE
+  if (fmt)
+    {
+      va_list l;
+      FILE* flog = fopen (LOGFILENAME, "ab");
+
+      va_start (l, fmt);
+      vfprintf (flog, fmt, l);
+      va_end (l);
+      fclose (flog);
+    }
+  else
+    {
+      // Special case to re-initialize the log file
+      FILE* flog = fopen (LOGFILENAME, "w");
+      fclose (flog);
+    }
+#else
+  Q_UNUSED (fmt);
+#endif
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QConsolePrivate::updateConsoleSize (bool sync)
+{
+  QFontMetrics fm (m_font);
+  QSize winSize = m_consoleView->size ();
+
+  m_charSize.rwidth () = fm.maxWidth ();
+  m_charSize.rheight () = fm.lineSpacing ();
+
+  m_consoleRect.setWidth (winSize.width () / fm.maxWidth ());
+  m_consoleRect.setHeight (winSize.height () / fm.lineSpacing ());
+
+  m_bufferSize.rwidth () = m_consoleRect.width ();
+  m_bufferSize.rheight () = qMax (m_bufferSize.height (),
+                                  m_consoleRect.height ());
+
+  m_consoleRect.moveLeft (0);
+  if (m_consoleRect.bottom () >= m_bufferSize.height ())
+    m_consoleRect.moveTop (m_bufferSize.height () - m_consoleRect.height ());
+
+  log ("Console resized:\n");
+  log ("  widget size: %d x %d\n", winSize.width (), winSize.height ());
+  log ("  buffer size: %d x %d\n", m_bufferSize.width (),
+       m_bufferSize.height ());
+  log ("  window: (%d, %d) -> (%d, %d) [%d x %d]\n",
+       m_consoleRect.left (), m_consoleRect.top (),
+       m_consoleRect.right (), m_consoleRect.bottom (),
+       m_consoleRect.width (), m_consoleRect.height ());
+
+  if (sync)
+    syncConsoleParameters ();
+
+  updateScrollBar ();
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QConsolePrivate::syncConsoleParameters (void)
+{
+  CONSOLE_SCREEN_BUFFER_INFO sbi;
+  HANDLE hStdOut = m_stdOut;
+
+  GetConsoleScreenBufferInfo (hStdOut, &sbi);
+
+  COORD bs;
+  SMALL_RECT sr;
+
+  bs.X = sbi.dwSize.X;
+  bs.Y = m_bufferSize.height ();
+  sr.Left   = sbi.srWindow.Left;
+  sr.Right  = sbi.srWindow.Right;
+  sr.Top    = m_consoleRect.top ();
+  sr.Bottom = m_consoleRect.bottom ();
+
+  if (bs.Y > sbi.dwSize.Y)
+    {
+      SetConsoleScreenBufferSize (hStdOut, bs);
+      SetConsoleWindowInfo (hStdOut, TRUE, &sr);
+    }
+  else
+    {
+      SetConsoleWindowInfo (hStdOut, TRUE, &sr);
+      SetConsoleScreenBufferSize (hStdOut, bs);
+    }
+
+  bs.X = m_bufferSize.width ();
+  sr.Left  = m_consoleRect.left ();
+  sr.Right = m_consoleRect.right ();
+
+  if (bs.X > sbi.dwSize.X)
+    {
+      SetConsoleScreenBufferSize (hStdOut, bs);
+      SetConsoleWindowInfo (hStdOut, TRUE, &sr);
+    }
+  else
+    {
+      SetConsoleWindowInfo (hStdOut, TRUE, &sr);
+      SetConsoleScreenBufferSize (hStdOut, bs);
+    }
+
+  log ("Sync'ing console parameters:\n");
+  log ("  buffer size: %d x %d\n", bs.X, bs.Y);
+  log ("  window: (%d, %d) -> (%d, %d)\n",
+       sr.Left, sr.Top, sr.Right, sr.Bottom);
+
+  if (m_buffer)
+    delete [] m_buffer;
+  if (m_tmpBuffer)
+    delete [] m_tmpBuffer;
+
+  int bufSize = m_consoleRect.width () * m_consoleRect.height ();
+
+  m_buffer = new CHAR_INFO[bufSize];
+  m_tmpBuffer = new CHAR_INFO[bufSize];
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QConsolePrivate::grabConsoleBuffer (CHAR_INFO* buf)
+{
+  COORD bs, bc;
+  SMALL_RECT r;
+
+  bs.X = m_consoleRect.width ();
+  bs.Y = m_consoleRect.height ();
+  bc.X = 0;
+  bc.Y = 0;
+
+  r.Left   = m_consoleRect.left ();
+  r.Top    = m_consoleRect.top ();
+  r.Right  = m_consoleRect.right ();
+  r.Bottom = m_consoleRect.bottom ();
+
+  if (! ReadConsoleOutput (m_stdOut, (buf ? buf : m_buffer), bs, bc, &r))
+    qCritical ("cannot read console output");
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QConsolePrivate::updateScrollBar (void)
+{
+  m_scrollBar->setMinimum (0);
+  if (m_bufferSize.height () > m_consoleRect.height ())
+    m_scrollBar->setMaximum (m_bufferSize.height () - m_consoleRect.height ());
+  else
+    m_scrollBar->setMaximum (0);
+  m_scrollBar->setSingleStep (1);
+  m_scrollBar->setPageStep (m_consoleRect.height ());
+  m_scrollBar->setValue (m_consoleRect.top ());
+
+  log ("Scrollbar parameters updated: %d/%d/%d/%d\n",
+       m_scrollBar->minimum (), m_scrollBar->maximum (),
+       m_scrollBar->singleStep (), m_scrollBar->pageStep ());
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QConsolePrivate::setScrollValue (int value)
+{
+  if (value == m_consoleRect.top ())
+    return;
+
+  SMALL_RECT r;
+  HANDLE hStdOut = m_stdOut;
+
+  if (value + m_consoleRect.height () > m_bufferSize.height ())
+    value = m_bufferSize.height () - m_consoleRect.height ();
+
+  r.Left = m_consoleRect.left ();
+  r.Top = value;
+  r.Right = m_consoleRect.right ();
+  r.Bottom = value + m_consoleRect.height () - 1;
+
+  log ("Scrolling window: (%d, %d) -> (%d, %d) [%d x %d]\n",
+       r.Left, r.Top, r.Right, r.Bottom, 
+       r.Right - r.Left + 1, r.Bottom - r.Top + 1);
+
+  if (SetConsoleWindowInfo (hStdOut, TRUE, &r))
+    {
+      m_consoleRect.moveTop (value);
+      updateConsoleView ();
+    }
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QConsolePrivate::updateConsoleView (bool grab)
+{
+  if (grab)
+    grabConsoleBuffer ();
+  m_consoleView->update ();
+  m_consoleWatcher->start ();
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QConsolePrivate::monitorConsole (void)
+{
+  CONSOLE_SCREEN_BUFFER_INFO sbi;
+  HANDLE hStdOut = GetStdHandle (STD_OUTPUT_HANDLE);
+
+  static wchar_t titleBuf[260];
+
+  GetConsoleTitleW (titleBuf, sizeof (titleBuf));
+  QString title = QString::fromWCharArray (titleBuf);
+
+  if (title != m_title)
+    {
+      q->setWindowTitle (title);
+      emit q->titleChanged (title);
+    }
+
+  if (GetConsoleScreenBufferInfo (hStdOut, &sbi))
+    {
+      if (m_bufferSize.width () != sbi.dwSize.X
+          || m_bufferSize.height () != sbi.dwSize.Y)
+        {
+          // Buffer size changed
+          m_bufferSize.rwidth () = sbi.dwSize.X;
+          m_bufferSize.rheight () = sbi.dwSize.Y;
+          updateScrollBar ();
+        }
+
+      if (m_cursorPos.x () != sbi.dwCursorPosition.X
+          || m_cursorPos.y () != sbi.dwCursorPosition.Y)
+        {
+          // Cursor position changed
+          m_consoleView->update
+            ((m_cursorPos.x () - sbi.srWindow.Left) * m_charSize.width (),
+             (m_cursorPos.y () - sbi.srWindow.Top) * m_charSize.height (),
+             m_charSize.width (), m_charSize.height ());
+          m_cursorPos.rx () = sbi.dwCursorPosition.X;
+          m_cursorPos.ry () = sbi.dwCursorPosition.Y;
+          m_consoleView->update
+            ((m_cursorPos.x () - sbi.srWindow.Left) * m_charSize.width (),
+             (m_cursorPos.y () - sbi.srWindow.Top) * m_charSize.height (),
+             m_charSize.width (), m_charSize.height ());
+        }
+
+      if (m_consoleRect.left () != sbi.srWindow.Left
+          || m_consoleRect.right () != sbi.srWindow.Right
+          || m_consoleRect.top () != sbi.srWindow.Top
+          || m_consoleRect.bottom () != sbi.srWindow.Bottom)
+        {
+          // Console window changed
+          m_consoleRect = QRect (sbi.srWindow.Left, sbi.srWindow.Top,
+                                 sbi.srWindow.Right - sbi.srWindow.Left + 1,
+                                 sbi.srWindow.Bottom - sbi.srWindow.Top + 1);
+          updateScrollBar ();
+          updateConsoleView ();
+          return;
+        }
+
+      if (m_tmpBuffer && m_buffer)
+        {
+          grabConsoleBuffer (m_tmpBuffer);
+          if (memcmp (m_tmpBuffer, m_buffer,
+                      sizeof (CHAR_INFO) * m_consoleRect.width () *
+                      m_consoleRect.height ()))
+            {
+              // FIXME: compute the area to update based on the
+              // difference between the 2 buffers.
+              qSwap (m_buffer, m_tmpBuffer);
+              updateConsoleView (false);
+            }
+        }
+    }
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QConsolePrivate::startCommand (void)
+{
+  QString cmd = m_command;
+
+  if (cmd.isEmpty ())
+    cmd = qgetenv ("COMSPEC").constData ();
+
+  if (! cmd.isEmpty ())
+    {
+      STARTUPINFO si;
+      PROCESS_INFORMATION pi;
+
+      ZeroMemory (&si, sizeof (si));
+      si.cb = sizeof (si);
+      ZeroMemory (&pi, sizeof (pi));
+
+      if (CreateProcessW (NULL,
+                          (LPWSTR)cmd.unicode (),
+                          NULL,
+                          NULL,
+                          TRUE,
+                          0,
+                          NULL,
+                          NULL,
+                          &si,
+                          &pi))
+        {
+          CloseHandle (pi.hThread);
+          m_process = pi.hProcess;
+          WaitForSingleObject (m_process, INFINITE);
+          CloseHandle (m_process);
+          m_process = NULL;
+        }
+    }
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QConsolePrivate::sendConsoleText (const QString& s)
+{
+  // Send the string in chunks of 512 characters. Each character is
+  // translated into an equivalent keypress event.
+
+#define TEXT_CHUNK_SIZE 512
+
+  int len = s.length ();
+  INPUT_RECORD events[TEXT_CHUNK_SIZE];
+  DWORD nEvents = 0, written;
+  HANDLE hStdIn = GetStdHandle (STD_INPUT_HANDLE);
+
+  ZeroMemory (events, sizeof (events));
+
+  for (int i = 0; i < len; i++)
+    {
+      QChar c = s.at (i);
+
+      if (c == L'\r' || c == L'\n')
+        {
+          if (c == L'\r' && i < (len - 1) && s.at (i+1) == L'\n')
+            i++;
+          if (nEvents)
+            {
+              WriteConsoleInput (hStdIn, events, nEvents, &written);
+              nEvents = 0;
+              ZeroMemory (events, sizeof (events));
+            }
+          PostMessage (m_consoleWindow, WM_KEYDOWN, VK_RETURN, 0x001C0001);
+          PostMessage (m_consoleWindow, WM_KEYDOWN, VK_RETURN, 0xC01C0001);
+        }
+      else
+        {
+          events[nEvents].EventType                        = KEY_EVENT;
+          events[nEvents].Event.KeyEvent.bKeyDown          = TRUE;
+          events[nEvents].Event.KeyEvent.wRepeatCount      = 1;
+          events[nEvents].Event.KeyEvent.wVirtualKeyCode   =
+            LOBYTE (VkKeyScan (c.unicode ()));
+          events[nEvents].Event.KeyEvent.wVirtualScanCode  = 0;
+          events[nEvents].Event.KeyEvent.uChar.UnicodeChar = c.unicode ();
+          events[nEvents].Event.KeyEvent.dwControlKeyState = 0;
+          nEvents++;
+        }
+
+      if (nEvents == TEXT_CHUNK_SIZE
+          || (nEvents > 0 && i == (len - 1)))
+        {
+          WriteConsoleInput (hStdIn, events, nEvents, &written);
+          nEvents = 0;
+          ZeroMemory (events, sizeof (events));
+        }
+    }
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+QWinTerminalImpl::QWinTerminalImpl (QWidget* parent)
+    : QTerminalInterface (parent), d (new QConsolePrivate (this))
+{
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+QWinTerminalImpl::QWinTerminalImpl (const QString& cmd, QWidget* parent)
+    : QTerminalInterface (parent), d (new QConsolePrivate (this, cmd))
+{
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+QWinTerminalImpl::~QWinTerminalImpl (void)
+{
+  delete d;
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QWinTerminalImpl::viewResizeEvent (QConsoleView*, QResizeEvent*)
+{
+  d->updateConsoleSize (true);
+  d->grabConsoleBuffer ();
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QWinTerminalImpl::viewPaintEvent (QConsoleView* w, QPaintEvent* event)
+{
+  QPainter p (w);
+  int cw = d->m_charSize.width (), ch = d->m_charSize.height ();
+  int ascent, stride, cx1, cy1, cx2, cy2, x, y;
+  WORD attr = 0;
+  QString s;
+  bool hasChar = false;
+
+  QRect updateRect = event->rect ();
+
+  cx1 = updateRect.left () / cw;
+  cy1 = updateRect.top () / ch;
+  cx2 = qMin (d->m_consoleRect.width () - 1, updateRect.right () / cw);
+  cy2 = qMin (d->m_consoleRect.height () - 1, updateRect.bottom () / ch);
+
+  if (cx1 > d->m_consoleRect.width () - 1
+      || cy1 > d->m_consoleRect.height () - 1)
+    return;
+
+  p.setFont (d->m_font);
+  p.setPen (Qt::black);
+
+  ascent = p.fontMetrics ().ascent ();
+  stride = d->m_consoleRect.width ();
+
+  s.reserve (cx2 - cx1 + 1);
+  y = ascent + cy1 * ch;;
+
+  for (int j = cy1; j <= cy2; j++, y += ch)
+    {
+      // Reset string buffer and starting X coordinate
+      s.clear ();
+      hasChar = false;
+      x = cx1 * cw;
+
+      for (int i = cx1; i <= cx2; i++)
+        {
+          CHAR_INFO* ci = &(d->m_buffer[stride*j+i]);
+
+          if ((ci->Attributes & 0x00ff) != attr)
+            {
+              // Character attributes changed
+              if (! s.isEmpty ())
+                {
+                  // String buffer not empty -> draw it
+                  if (hasChar || (attr & 0x00f0))
+                    {
+                      if (attr & 0x00f0)
+                        p.fillRect (x, y-ascent, s.length () * cw, ch,
+                                    p.brush ());
+                      p.drawText (x, y, s);
+                    }
+                  x += (s.length () * cw);
+                  s.clear ();
+                  hasChar = false;
+                }
+              // Update current pen and store current attributes
+              // FIXME: what about background?
+              attr = (ci->Attributes & 0x00ff);
+              p.setPen (d->m_colors[attr & 0x000f]);
+              p.setBrush (d->m_colors[(attr >> 4) & 0x000f]);
+            }
+
+          // Append current character to the string buffer
+          s.append (ci->Char.UnicodeChar);
+          if (ci->Char.UnicodeChar != L' ')
+            hasChar = true;
+        }
+
+      if (! s.isEmpty () && (hasChar || (attr & 0x00f0)))
+        {
+          // Line end reached, but string buffer not empty -> draw it
+          // No need to update s or x, they will be reset on the next
+          // for-loop iteration
+          if (attr & 0x00f0)
+            p.fillRect (x, y-ascent, s.length () * cw, ch, p.brush ());
+          p.drawText (x, y, s);
+        }
+    }
+
+  // Draw cursor
+  p.setCompositionMode (QPainter::RasterOp_SourceXorDestination);
+  p.fillRect ((d->m_cursorPos.x () - d->m_consoleRect.x ()) * cw,
+              (d->m_cursorPos.y () - d->m_consoleRect.y ()) * ch,
+              cw, ch, d->m_colors[7]);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QWinTerminalImpl::wheelEvent (QWheelEvent* event)
+{
+  if (! d->m_inWheelEvent)
+    {
+      // Forward to the scrollbar (avoid recursion)
+      d->m_inWheelEvent = true;
+      QApplication::sendEvent (d->m_scrollBar, event);
+      d->m_inWheelEvent = false;
+    }
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+bool QWinTerminalImpl::winEvent (MSG* msg, long* result)
+{
+  switch (msg->message)
+    {
+    case WM_KEYDOWN:
+    case WM_KEYUP:
+    //case WM_CHAR:
+      // Forward Win32 message to the console window
+      PostMessage (d->m_consoleWindow,
+                   msg->message,
+                   msg->wParam,
+                   msg->lParam);
+      result = 0;
+      return true;
+    default:
+      return false;
+    }
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QWinTerminalImpl::scrollValueChanged (int value)
+{
+  d->setScrollValue (value);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QWinTerminalImpl::monitorConsole (void)
+{
+  d->monitorConsole ();
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QWinTerminalImpl::focusInEvent (QFocusEvent* event)
+{
+  QWidget::focusInEvent (event);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QWinTerminalImpl::start (void)
+{
+  d->startCommand ();
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QWinTerminalImpl::sendText (const QString& s)
+{
+  d->sendConsoleText (s);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QWinTerminalImpl::setTerminalFont (const QFont& f)
+{
+  d->m_font = f;
+  d->m_consoleView->setFont (f);
+  d->updateConsoleSize (true);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QWinTerminalImpl::setSize (int columns, int lines)
+{
+  Q_UNUSED (columns);
+  Q_UNUSED (lines);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QWinTerminalImpl::copyClipboard (void)
+{
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void QWinTerminalImpl::pasteClipboard (void)
+{
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/libqterminal/win32/QWinTerminalImpl.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,81 @@
+/*
+
+Copyright (C) 2011 Michael Goffioul.
+
+This file is part of QConsole.
+
+Foobar is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+QConsole 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 Foobar.  If not, see <http://www.gnu.org/licenses/>.
+
+*/
+
+#ifndef __QConsole_h__
+#define __QConsole_h__ 1
+
+#include <QWidget>
+#include "QTerminalInterface.h"
+class QFocusEvent;
+class QKeyEvent;
+class QPaintEvent;
+class QResizeEvent;
+class QWheelEvent;
+
+class QConsolePrivate;
+class QConsoleThread;
+class QConsoleView;
+
+//////////////////////////////////////////////////////////////////////////////
+
+class QWinTerminalImpl : public QTerminalInterface
+{
+  Q_OBJECT
+  friend class QConsolePrivate;
+  friend class QConsoleThread;
+  friend class QConsoleView;
+
+public:
+  QWinTerminalImpl (QWidget* parent = 0);
+  QWinTerminalImpl (const QString& cmd, QWidget* parent = 0);
+  ~QWinTerminalImpl (void);
+
+  void setTerminalFont (const QFont& font);
+  void setSize (int columns, int lines);
+  void sendText (const QString& s);
+
+public slots:
+  void copyClipboard (void);
+  void pasteClipboard (void);
+
+signals:
+  void terminated (void);
+  void titleChanged (const QString&);
+
+protected:
+  void viewPaintEvent (QConsoleView*, QPaintEvent*);
+  void viewResizeEvent (QConsoleView*, QResizeEvent*);
+  void wheelEvent (QWheelEvent*);
+  void focusInEvent (QFocusEvent*);
+  bool winEvent (MSG*, long*);
+  virtual void start (void);
+
+private slots:
+  void scrollValueChanged (int value);
+  void monitorConsole (void);
+
+private:
+  QConsolePrivate* d;
+};
+
+//////////////////////////////////////////////////////////////////////////////
+
+#endif // __QConsole_h__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/msvc.pri	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,11 @@
+CONFIG += release
+
+QMAKE_CXXFLAGS += -MP
+LIBDIR_SUFFIX = release
+
+msvc-debug {
+	QMAKE_CXXFLAGS_RELEASE += -Zi
+	QMAKE_CXXFLAGS_RELEASE -= -O2
+	QMAKE_LFLAGS_RELEASE += -debug
+	QMAKE_CLEAN += $(DESTDIR)$(QMAKE_TARGET).pdb
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/qterminal.pro	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,2 @@
+TEMPLATE 	= subdirs
+SUBDIRS 	= libqterminal qterminal
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/qterminal/README	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,1 @@
+here is sample program which uses QTermWidet for displaying a terminal
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/qterminal/main.cpp	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,40 @@
+/*  Copyright (C) 2008 e_k (e_k@users.sourceforge.net)
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Library General Public
+    License as published by the Free Software Foundation; either
+    version 2 of the License, or (at your option) any later version.
+		
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Library General Public License for more details.
+				
+    You should have received a copy of the GNU Library General Public License
+    along with this library; see the file COPYING.LIB.  If not, write to
+    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+    Boston, MA 02110-1301, USA.
+*/
+						
+
+#include <QtCore>
+#include <QtGui>
+#include <QApplication>
+
+#include "QTerminal.h"
+
+int main(int argc, char *argv[])
+{
+    QApplication app(argc, argv);
+    QMainWindow *mainWindow = new QMainWindow();
+
+    QTerminal *terminal = new QTerminal();
+
+    mainWindow->setCentralWidget(terminal);
+    mainWindow->resize(600, 400);
+
+    mainWindow->show();    
+    return app.exec();
+} 
+
+  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libgui/qterminal/qterminal/qterminal.pro	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,15 @@
+TEMPLATE	= app
+
+QT += core gui
+
+SOURCES 	= main.cpp
+INCLUDEPATH 	= ../libqterminal
+
+win32 {
+  win32-msvc*: include(../msvc.pri)
+  LIBS += -L../libqterminal/$$LIBDIR_SUFFIX \
+    -lqterminal -luser32 -lkernel32
+} else {
+  DEFINES += HAVE_PTY_H HAVE_OPENPTY
+  LIBS += -L../libqterminal -lqterminal -lutil
+}
--- a/libgui/src/history-dockwidget.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libgui/src/history-dockwidget.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -200,7 +200,7 @@
           std::string entry = command_history::get_entry (i);
 
           _history_model->setData (_history_model->index (i),
-                                   QString::fromStdString (entry));
+                      QString::fromLocal8Bit (entry.data (), entry.size ()));
         }
 
       // FIXME -- does this behavior make sense?  Calling
Binary file libgui/src/icons/graphic_logo_DocumentationDockWidget.png has changed
Binary file libgui/src/icons/graphic_logo_FileEditor.png has changed
Binary file libgui/src/icons/graphic_logo_FilesDockWidget.png has changed
Binary file libgui/src/icons/graphic_logo_HistoryDockWidget.png has changed
Binary file libgui/src/icons/graphic_logo_TerminalDockWidget.png has changed
Binary file libgui/src/icons/graphic_logo_WorkspaceView.png has changed
Binary file libgui/src/icons/letter_logo_DocumentationDockWidget.png has changed
Binary file libgui/src/icons/letter_logo_FileEditor.png has changed
Binary file libgui/src/icons/letter_logo_FilesDockWidget.png has changed
Binary file libgui/src/icons/letter_logo_HistoryDockWidget.png has changed
Binary file libgui/src/icons/letter_logo_TerminalDockWidget.png has changed
Binary file libgui/src/icons/letter_logo_WorkspaceView.png has changed
--- a/libgui/src/main-window.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libgui/src/main-window.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -61,6 +61,36 @@
 
 main_window::~main_window ()
 {
+  // Clean up all dynamically created objects to ensure they are
+  // deleted before this main_window is.  Otherwise, some will be
+  // attached to a non-existent parent.
+
+  if (_octave_qt_event_listener)
+    delete _octave_qt_event_listener;
+
+  if (_file_editor)
+    delete _file_editor;
+
+  if (_terminal_dock_widget)
+    delete _terminal_dock_widget;
+
+  if (_terminal)
+    delete _terminal;
+
+  if (_status_bar)
+    delete _status_bar;
+
+  if (_documentation_dock_widget)
+    delete _documentation_dock_widget;
+
+  if (_files_dock_widget)
+    delete _files_dock_widget;
+
+  if (_history_dock_widget)
+    delete _history_dock_widget;
+
+  if (_workspace_view)
+    delete _workspace_view;
 }
 
 void
@@ -185,6 +215,23 @@
     _terminal->setCursorType(QTerminalInterface::UnderlineCursor,
                              cursorBlinking);
 
+  // the widget's icons (when floating)
+  int icon_set = settings->value ("DockWidgets/widget_icon_set",0).toInt ();
+  QString icon_prefix = QString (WIDGET_ICON_SET_PREFIX[icon_set]);
+  QString icon;
+  foreach (QObject *obj, children ())
+    {
+      QString name = obj->objectName ();
+      if (obj->inherits("QDockWidget") && ! name.isEmpty ())
+        { // if children is a dockwidget with a name
+          QDockWidget *widget = qobject_cast<QDockWidget *> (obj);
+          icon = icon_prefix;  // prefix or octave-logo
+          if (icon_set)        // > 0 : each widget has individual icon
+            icon = icon + name + QString(".png");
+          widget->setWindowIcon (QIcon (icon));
+        }
+    }
+
   resource_manager::update_network_settings ();
 }
 
@@ -216,19 +263,25 @@
 void
 main_window::change_current_working_directory ()
 {
-  QString selectedDirectory =
+  QString directory =
     QFileDialog::getExistingDirectory(this, tr ("Set working direcotry"));
 
-  if (!selectedDirectory.isEmpty ())
-    octave_link::post_event (this, &main_window::change_directory_callback,
-                             selectedDirectory.toStdString ());
+  if (!directory.isEmpty ())
+    {
+      std::string dir = directory.toLocal8Bit ().data ();
+      octave_link::post_event (this, &main_window::change_directory_callback,dir);
+    }
 }
 
 void
 main_window::set_current_working_directory (const QString& directory)
 {
-  octave_link::post_event (this, &main_window::change_directory_callback,
-                           directory.toStdString ());
+  QFileInfo fileInfo (directory);  // check whether this is an existing dir
+  if (fileInfo.exists () && fileInfo.isDir ())   // is dir and exists
+    {
+      std::string dir = directory.toLocal8Bit ().data ();
+      octave_link::post_event (this, &main_window::change_directory_callback,dir);
+    }
 }
 
 void
@@ -237,6 +290,19 @@
   set_current_working_directory ("..");
 }
 
+// Slot that is called if return is pressed in the line edit of the combobox
+// -> a new or a directory that is already in the drop down list was entered
+void
+main_window::current_working_directory_entered ()
+{
+  QString dir = _current_directory_line_edit->text ();  // get new directory
+  int index = _current_directory_combo_box->findText (dir);  // already in list?
+  if ( index < 0 )  // directory not yet in list -> set directory
+    set_current_working_directory (dir);
+  // if directory already in list, combobox triggers signal activated ()
+  // to change directory
+}
+
 void
 main_window::focus_command_window ()
 {
@@ -478,26 +544,31 @@
   _documentation_dock_widget->setStatusTip (tr ("See the documentation for help."));
   _status_bar               = new QStatusBar (this);
 
+  _current_directory_line_edit = new QLineEdit (this);
   _current_directory_combo_box = new QComboBox (this);
-  _current_directory_combo_box->setFixedWidth (300);
+  _current_directory_combo_box->setFixedWidth (current_directory_width);
   _current_directory_combo_box->setEditable (true);
+  // setLineEdit takes ownership -> no need to delete line_edit in ~main_window
+  _current_directory_combo_box->setLineEdit (_current_directory_line_edit);
   _current_directory_combo_box->setInsertPolicy (QComboBox::InsertAtTop);
-  _current_directory_combo_box->setMaxVisibleItems (16);
-  _current_directory_combo_box->setMaxCount (16);
+  _current_directory_combo_box->setMaxVisibleItems (current_directory_max_visible);
+  _current_directory_combo_box->setMaxCount (current_directory_max_count);
 
-  _current_directory_tool_button = new QToolButton (this);
-  _current_directory_tool_button->setIcon (QIcon(":/actions/icons/search.png"));
+  QToolButton *current_directory_tool_button = new QToolButton (this);
+  current_directory_tool_button->setIcon (QIcon(":/actions/icons/search.png"));
 
-  _current_directory_up_tool_button = new QToolButton (this);
-  _current_directory_up_tool_button->setIcon (QIcon(":/actions/icons/up.png"));
+  QToolButton *current_directory_up_tool_button = new QToolButton (this);
+  current_directory_up_tool_button->setIcon (QIcon(":/actions/icons/up.png"));
 
   // Octave Terminal subwindow.
   _terminal = new QTerminal (this);
   _terminal->setObjectName ("OctaveTerminal");
   _terminal->setFocusPolicy (Qt::StrongFocus);
   _terminal_dock_widget = new terminal_dock_widget (_terminal, this);
-  _terminal_dock_widget->setWindowIcon (QIcon(":/actions/icons/terminal.png"));
 
+  // Create and set the central widget.  QMainWindow takes ownership of
+  // the widget (pointer) so there is no need to delete the object upon
+  // destroying this main_window.
   QWidget *dummyWidget = new QWidget ();
   dummyWidget->setObjectName ("CentralDummyWidget");
   dummyWidget->resize (10, 10);
@@ -744,6 +815,7 @@
 
   // Toolbars
   QToolBar *main_tool_bar = addToolBar ("Main");
+  main_tool_bar->setObjectName ("MainToolBar");
   main_tool_bar->addAction (new_script_action);
   main_tool_bar->addAction (open_action);
   main_tool_bar->addSeparator ();
@@ -753,10 +825,12 @@
   main_tool_bar->addAction (undo_action);
   main_tool_bar->addAction (redo_action);
   main_tool_bar->addSeparator ();
+  // addWidget takes ownership of the objects so there is no
+  // need to delete these upon destroying this main_window.
   main_tool_bar->addWidget (new QLabel (tr ("Current Directory:")));
   main_tool_bar->addWidget (_current_directory_combo_box);
-  main_tool_bar->addWidget (_current_directory_tool_button);
-  main_tool_bar->addWidget (_current_directory_up_tool_button);
+  main_tool_bar->addWidget (current_directory_tool_button);
+  main_tool_bar->addWidget (current_directory_up_tool_button);
 
   connect (qApp,                        SIGNAL (aboutToQuit ()),
            this,                        SLOT   (prepare_for_quit ()));
@@ -836,9 +910,9 @@
            this,                        SLOT   (handle_load_workspace_request ()));
   connect (clear_workspace_action,      SIGNAL (triggered ()),
            this,                        SLOT   (handle_clear_workspace_request ()));
-  connect (_current_directory_tool_button, SIGNAL (clicked ()),
+  connect (current_directory_tool_button, SIGNAL (clicked ()),
            this,                        SLOT   (change_current_working_directory ()));
-  connect (_current_directory_up_tool_button, SIGNAL (clicked ()),
+  connect (current_directory_up_tool_button, SIGNAL (clicked ()),
            this,                        SLOT   (current_working_directory_up()));
   connect (copy_action,                 SIGNAL (triggered()),
            _terminal,                   SLOT   (copyClipboard ()));
@@ -846,6 +920,8 @@
            _terminal,                   SLOT   (pasteClipboard ()));
   connect (_current_directory_combo_box, SIGNAL (activated (QString)),
            this,                        SLOT (set_current_working_directory (QString)));
+  connect (_current_directory_line_edit, SIGNAL (returnPressed ()),
+           this,                        SLOT (current_working_directory_entered ()));
   connect (_debug_continue,             SIGNAL (triggered ()),
            this,                        SLOT (debug_continue ()));
   connect (_debug_step_into,            SIGNAL (triggered ()),
--- a/libgui/src/main-window.h	Thu Nov 01 15:01:20 2012 -0400
+++ b/libgui/src/main-window.h	Sun Dec 23 13:00:02 2012 -0500
@@ -98,6 +98,7 @@
   void change_current_working_directory ();
   void set_current_working_directory (const QString& directory);
   void current_working_directory_up ();
+  void current_working_directory_entered ();
 
   void focus_command_window ();
   void focus_command_history ();
@@ -166,8 +167,10 @@
   // Toolbars.
   QStatusBar *              _status_bar;
   QComboBox *               _current_directory_combo_box;
-  QToolButton *             _current_directory_tool_button;
-  QToolButton *             _current_directory_up_tool_button;
+  static const int        current_directory_width       = 300;
+  static const int        current_directory_max_visible = 16;
+  static const int        current_directory_max_count   = 16;
+  QLineEdit *               _current_directory_line_edit;
 
   octave_qt_event_listener *_octave_qt_event_listener;
 
--- a/libgui/src/module.mk	Thu Nov 01 15:01:20 2012 -0400
+++ b/libgui/src/module.mk	Sun Dec 23 13:00:02 2012 -0500
@@ -27,9 +27,21 @@
   src/icons/filesaveas.png \
   src/icons/filesave.png \
   src/icons/find.png \
+  src/icons/graphic_logo_DocumentationDockWidget.png \
+  src/icons/graphic_logo_FileEditor.png \
+  src/icons/graphic_logo_FilesDockWidget.png \
+  src/icons/graphic_logo_HistoryDockWidget.png \
+  src/icons/graphic_logo_TerminalDockWidget.png \
+  src/icons/graphic_logo_WorkspaceView.png \
   src/icons/help_index.png \
   src/icons/icons_license \
   src/icons/jabber_protocol.png \
+  src/icons/letter_logo_DocumentationDockWidget.png \
+  src/icons/letter_logo_FileEditor.png \
+  src/icons/letter_logo_FilesDockWidget.png \
+  src/icons/letter_logo_HistoryDockWidget.png \
+  src/icons/letter_logo_TerminalDockWidget.png \
+  src/icons/letter_logo_WorkspaceView.png \
   src/icons/logo.png \
   src/icons/question.png \
   src/icons/redled.png \
@@ -126,10 +138,7 @@
 src_libgui_src_la_CPPFLAGS = \
   $(AM_CPPFLAGS) \
   @OCTGUI_DLL_DEFS@ \
-  -I$(QT_INCDIR) \
-  -I$(QT_INCDIR)/QtCore \
-  -I$(QT_INCDIR)/QtGui \
-  -I$(QT_INCDIR)/QtNetwork \
+  @QT_CPPFLAGS@ \
   -I$(srcdir)/qterminal/libqterminal \
   -Isrc -I$(srcdir)/src \
   -I$(srcdir)/src/m-editor \
--- a/libgui/src/octave-gui.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libgui/src/octave-gui.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -31,6 +31,7 @@
 #include <iostream>
 
 #include "lo-utils.h"
+#include "oct-env.h"
 #include "syswait.h"
 
 #include "welcome-wizard.h"
@@ -82,8 +83,6 @@
 {
   dissociate_terminal ();
 
-  setenv ("GNUTERM", "qt", 1);
-
   QApplication application (argc, argv);
 
   while (true)
--- a/libgui/src/octave-qt-event-listener.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libgui/src/octave-qt-event-listener.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -36,7 +36,7 @@
 octave_qt_event_listener::current_directory_has_changed (const std::string& directory)
 {
   emit current_directory_has_changed_signal
-    (QString::fromStdString (directory));
+    (QString::fromLocal8Bit (directory.data (), directory.size ()));
 }
 
 void
--- a/libgui/src/resource-manager.h	Thu Nov 01 15:01:20 2012 -0400
+++ b/libgui/src/resource-manager.h	Sun Dec 23 13:00:02 2012 -0500
@@ -28,6 +28,19 @@
 #include <QMap>
 #include <QSettings>
 
+// constants for the widget's icons
+enum widget_icon_set
+  {
+    NO_ICON_SET = 0,
+    GRAPHIC_ICON_SET,
+    LETTER_ICON_SET
+  };
+static const char* WIDGET_ICON_SET_PREFIX[] =
+    {":/actions/icons/logo.png",
+     ":/actions/icons/graphic_logo_",
+     ":/actions/icons/letter_logo_"};
+
+
 class resource_manager
 {
 protected:
--- a/libgui/src/resource.qrc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libgui/src/resource.qrc	Sun Dec 23 13:00:02 2012 -0500
@@ -36,5 +36,17 @@
         <file>icons/db_step_in.png</file>
         <file>icons/db_step_out.png</file>
         <file>icons/db_stop.png</file>
+        <file>icons/letter_logo_FilesDockWidget.png</file>
+        <file>icons/letter_logo_FileEditor.png</file>
+        <file>icons/letter_logo_TerminalDockWidget.png</file>
+        <file>icons/letter_logo_HistoryDockWidget.png</file>
+        <file>icons/letter_logo_WorkspaceView.png</file>
+        <file>icons/letter_logo_DocumentationDockWidget.png</file>
+        <file>icons/graphic_logo_FilesDockWidget.png</file>
+        <file>icons/graphic_logo_FileEditor.png</file>
+        <file>icons/graphic_logo_TerminalDockWidget.png</file>
+        <file>icons/graphic_logo_HistoryDockWidget.png</file>
+        <file>icons/graphic_logo_WorkspaceView.png</file>
+        <file>icons/graphic_logo_DocumentationDockWidget.png</file>
     </qresource>
 </RCC>
--- a/libgui/src/settings-dialog.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libgui/src/settings-dialog.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -38,6 +38,11 @@
 
   // FIXME -- what should happen if settings is 0?
 
+  int widget_icon_set = settings->value ("DockWidgets/widget_icon_set",0).toInt ();
+  ui->general_icon_octave-> setChecked (NO_ICON_SET == widget_icon_set);
+  ui->general_icon_graphic-> setChecked (GRAPHIC_ICON_SET == widget_icon_set);
+  ui->general_icon_letter-> setChecked (LETTER_ICON_SET == widget_icon_set);
+
   ui->useCustomFileEditor->setChecked (settings->value ("useCustomFileEditor").toBool ());
   ui->customFileEditor->setText (settings->value ("customFileEditor").toString ());
   ui->editor_showLineNumbers->setChecked (settings->value ("editor/showLineNumbers",true).toBool () );
@@ -100,6 +105,12 @@
 
   // FIXME -- what should happen if settings is 0?
 
+  int widget_icon_set = NO_ICON_SET;
+  if (ui->general_icon_letter->isChecked ())
+    widget_icon_set = LETTER_ICON_SET;
+  else if (ui->general_icon_graphic->isChecked ())
+    widget_icon_set = GRAPHIC_ICON_SET;
+  settings->setValue ("DockWidgets/widget_icon_set",widget_icon_set);
   settings->setValue ("useCustomFileEditor", ui->useCustomFileEditor->isChecked ());
   settings->setValue ("customFileEditor", ui->customFileEditor->text ());
   settings->setValue ("editor/showLineNumbers", ui->editor_showLineNumbers->isChecked ());
--- a/libgui/src/settings-dialog.ui	Thu Nov 01 15:01:20 2012 -0400
+++ b/libgui/src/settings-dialog.ui	Sun Dec 23 13:00:02 2012 -0500
@@ -34,6 +34,84 @@
      <property name="currentIndex">
       <number>0</number>
      </property>
+     <widget class="QWidget" name="tab_4">
+      <property name="enabled">
+       <bool>true</bool>
+      </property>
+      <attribute name="title">
+       <string>General</string>
+      </attribute>
+      <widget class="QGroupBox" name="groupBox">
+       <property name="geometry">
+        <rect>
+         <x>10</x>
+         <y>10</y>
+         <width>551</width>
+         <height>81</height>
+        </rect>
+       </property>
+       <property name="sizePolicy">
+        <sizepolicy hsizetype="Expanding" vsizetype="Minimum">
+         <horstretch>0</horstretch>
+         <verstretch>0</verstretch>
+        </sizepolicy>
+       </property>
+       <property name="title">
+        <string>Icon set for dock widget</string>
+       </property>
+       <property name="alignment">
+        <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop</set>
+       </property>
+       <property name="flat">
+        <bool>false</bool>
+       </property>
+       <property name="checkable">
+        <bool>false</bool>
+       </property>
+       <widget class="QRadioButton" name="general_icon_octave">
+        <property name="geometry">
+         <rect>
+          <x>0</x>
+          <y>20</y>
+          <width>151</width>
+          <height>21</height>
+         </rect>
+        </property>
+        <property name="text">
+         <string>Octave logo only</string>
+        </property>
+        <property name="checked">
+         <bool>true</bool>
+        </property>
+       </widget>
+       <widget class="QRadioButton" name="general_icon_letter">
+        <property name="geometry">
+         <rect>
+          <x>0</x>
+          <y>40</y>
+          <width>151</width>
+          <height>21</height>
+         </rect>
+        </property>
+        <property name="text">
+         <string>Letter icons</string>
+        </property>
+       </widget>
+       <widget class="QRadioButton" name="general_icon_graphic">
+        <property name="geometry">
+         <rect>
+          <x>0</x>
+          <y>60</y>
+          <width>151</width>
+          <height>21</height>
+         </rect>
+        </property>
+        <property name="text">
+         <string>Graphic  icons</string>
+        </property>
+       </widget>
+      </widget>
+     </widget>
      <widget class="QWidget" name="tab">
       <attribute name="title">
        <string>Editor</string>
--- a/libgui/src/terminal-dockwidget.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libgui/src/terminal-dockwidget.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -39,6 +39,20 @@
   connect (this, SIGNAL (topLevelChanged(bool)), this, SLOT(top_level_changed(bool)));
 }
 
+void
+terminal_dock_widget::closeEvent (QCloseEvent *e)
+{
+  emit active_changed (false);
+  QDockWidget::closeEvent (e);
+}
+
+void
+terminal_dock_widget::handle_visibility_changed (bool visible)
+{
+  if (visible)
+    emit active_changed (true);
+}
+
 // slot for signal that is emitted when floating property changes
 void
 terminal_dock_widget::top_level_changed (bool floating)
--- a/libgui/src/terminal-dockwidget.h	Thu Nov 01 15:01:20 2012 -0400
+++ b/libgui/src/terminal-dockwidget.h	Sun Dec 23 13:00:02 2012 -0500
@@ -36,13 +36,13 @@
   void active_changed (bool active);
 
 public slots:
-  void handle_visibility_changed (bool visible)
-  {
-    if (visible)
-      emit active_changed (true);
-  }
+  void handle_visibility_changed (bool visible);
   /** Slot when floating property changes */
   void top_level_changed (bool floating);
+
+protected:
+  void closeEvent (QCloseEvent *event);
 };
 
+
 #endif // TERMINALDOCKWIDGET_H
--- a/libinterp/Makefile.am	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/Makefile.am	Sun Dec 23 13:00:02 2012 -0500
@@ -216,9 +216,17 @@
 DLL_CXXDEFS = @OCTINTERP_DLL_DEFS@
 
 ## Rule to build a DEF file from a .cc file
+##
+## FIXME -- This rule should be fixed to avoid using special
+## flags like JAVA_CPPFLAGS for every file.  How could it be written
+## so that it uses octave_value_liboctave_value_la_CPPFLAGS when
+## generating the octave-value/*.df files?
+## 
+## FIXME -- Shouldn't the build stop if CPP fails here?
 %.df: %.cc
 	$(CXXCPP) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \
-	  $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) \
+	  $(AM_CPPFLAGS) $(JAVA_CPPFLAGS) $(CPPFLAGS) \
+	  $(AM_CXXFLAGS) $(CXXFLAGS) \
 	  -DMAKE_BUILTINS $< | $(srcdir)/mkdefs $(srcdir) $< > $@-t
 	mv $@-t $@
 
@@ -283,10 +291,10 @@
 if AMCOND_BUILD_DOCS
 install-data-hook: install-oct install-built-in-docstrings
 else
-install-data-hook: install-oct
+install-data-hook: install-oct uninstall-built-in-docstrings
 endif
 
-uninstall-local: uninstall-oct
+uninstall-local: uninstall-oct uninstall-built-in-docstrings
 
 if AMCOND_ENABLE_DYNAMIC_LINKING
 install-oct:
@@ -322,8 +330,11 @@
 install-built-in-docstrings:
 	$(MKDIR_P) $(DESTDIR)$(octetcdir)
 	$(INSTALL_DATA) DOCSTRINGS $(DESTDIR)$(octetcdir)/built-in-docstrings
+
+uninstall-built-in-docstrings:
+	rm -f $(DESTDIR)$(octetcdir)/built-in-docstrings
 endif
-.PHONY: install-built-in-docstrings
+.PHONY: install-built-in-docstrings uninstall-built-in-docstrings
 
 CLEANFILES = \
   $(DLDFCN_PKG_ADD_FILE) \
--- a/libinterp/corefcn/mappers.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/corefcn/mappers.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -547,7 +547,7 @@
 @end example\n\
 \n\
 @end ifnottex\n\
-@seealso{erfc, erfcx, erfinv, erfcinv}\n\
+@seealso{erfc, erfcx, erfi, dawson, erfinv, erfcinv}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -584,6 +584,13 @@
 %! assert (erfc (x), 1-v, 1.e-6);
 %! assert (erfinv (v), x, 1.e-6);
 
+%!test
+%! x = [1+2i,-1+2i,1e-6+2e-6i,0+2i];
+%! v = [-0.53664356577857-5.04914370344703i, 0.536643565778565-5.04914370344703i, 0.112837916709965e-5+0.225675833419178e-5i, 18.5648024145755526i];
+%! assert (erf (x), v, -1.e-10);
+%! assert (erf (-x), -v, -1.e-10);
+%! assert (erfc (x), 1-v, -1.e-10);
+
 %!error erf ()
 %!error erf (1, 2)
 */
@@ -596,7 +603,7 @@
 @example\n\
 erf (@var{y}) == @var{x}\n\
 @end example\n\
-@seealso{erf, erfc, erfcx, erfcinv}\n\
+@seealso{erf, erfc, erfcx, erfi, dawson, erfcinv}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -634,7 +641,7 @@
 @example\n\
 erfc (@var{y}) == @var{x}\n\
 @end example\n\
-@seealso{erfc, erf, erfcx, erfinv}\n\
+@seealso{erfc, erf, erfcx, erfi, dawson, erfinv}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -674,7 +681,7 @@
 @ifnottex\n\
 @w{@code{1 - erf (@var{z})}}.\n\
 @end ifnottex\n\
-@seealso{erfcinv, erfcx, erf, erfinv}\n\
+@seealso{erfcinv, erfcx, erfi, dawson, erf, erfinv}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -707,11 +714,11 @@
 @ifnottex\n\
 \n\
 @example\n\
-exp (z^2) * erfc (x)\n\
+exp (z^2) * erfc (z)\n\
 @end example\n\
 \n\
 @end ifnottex\n\
-@seealso{erfc, erf, erfinv, erfcinv}\n\
+@seealso{erfc, erf, erfi, dawson, erfinv, erfcinv}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -724,12 +731,98 @@
 }
 
 /*
-## FIXME: Need a test for erfcx
+
+%!test
+%! x = [1+2i,-1+2i,1e-6+2e-6i,0+2i];
+%! assert (erfcx (x), exp (x.^2) .* erfc(x), -1.e-10);
+
+%!test
+%! x = [100, 100+20i];
+%! v = [0.0056416137829894329, 0.0054246791754558-0.00108483153786434i];
+%! assert (erfcx (x), v, -1.e-10);
 
 %!error erfcx ()
 %!error erfcx (1, 2)
 */
 
+DEFUN (erfi, args, ,
+    "-*- texinfo -*-\n\
+@deftypefn {Mapping Function} {} erfi (@var{z})\n\
+Compute the imaginary error function,\n\
+@tex\n\
+$$\n\
+ -i {\\rm erf} (iz) \n\
+$$\n\
+@end tex\n\
+@ifnottex\n\
+\n\
+@example\n\
+-i * erf (i*z)\n\
+@end example\n\
+\n\
+@end ifnottex\n\
+@seealso{erfc, erf, erfcx, dawson, erfinv, erfcinv}\n\
+@end deftypefn")
+{
+  octave_value retval;
+  if (args.length () == 1)
+    retval = args(0).erfi ();
+  else
+    print_usage ();
+
+  return retval;
+}
+
+/*
+
+%!test
+%! x = [-0.1, 0.1, 1, 1+2i,-1+2i,1e-6+2e-6i,0+2i];
+%! assert (erfi (x), -i * erf(i*x), -1.e-10);
+
+%!error erfi ()
+%!error erfi (1, 2)
+*/
+
+DEFUN (dawson, args, ,
+    "-*- texinfo -*-\n\
+@deftypefn {Mapping Function} {} dawson (@var{z})\n\
+Compute the Dawson (scaled imaginary error) function,\n\
+@tex\n\
+$$\n\
+ {\\sqrt{\\pi} \\over 2} e^{-z^2} {\\rm erfi} (z) \\equiv -i {\\sqrt{\\pi} \\over 2} e^{-z^2} {\\rm erf} (iz)\n\
+$$\n\
+@end tex\n\
+@ifnottex\n\
+\n\
+@example\n\
+(sqrt (pi) / 2) * exp (-z^2) * erfi (z)\n\
+@end example\n\
+\n\
+@end ifnottex\n\
+@seealso{erfc, erf, erfcx, erfi, erfinv, erfcinv}\n\
+@end deftypefn")
+{
+  octave_value retval;
+  if (args.length () == 1)
+    retval = args(0).dawson ();
+  else
+    print_usage ();
+
+  return retval;
+}
+
+/*
+
+%!test
+%! x = [0.1, 1, 1+2i,-1+2i,1e-4+2e-4i,0+2i];
+%! v = [0.099335992397852861, 0.53807950691, -13.38892731648-11.828715104i, 13.38892731648-11.828715104i, 0.0001000000073333+0.000200000001333i, 48.160012114291i];
+%! assert (dawson (x), v, -1.e-10);
+%! assert (dawson (-x), -v, -1.e-10);
+
+%!error dawson ()
+%!error dawson (1, 2)
+*/
+
 DEFUN (exp, args, ,
     "-*- texinfo -*-\n\
 @deftypefn {Mapping Function} {} exp (@var{x})\n\
--- a/libinterp/corefcn/tril.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/corefcn/tril.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -356,9 +356,9 @@
 The default value of @var{k} is zero, so that @code{triu} and\n\
 @code{tril} normally include the main diagonal as part of the result.\n\
 \n\
-If the value of @var{k} is negative, additional elements above (for\n\
-@code{tril}) or below (for @code{triu}) the main diagonal are also\n\
-selected.\n\
+If the value of @var{k} is nonzero integer, the selection of elements\
+starts at an offset of @var{k} diagonals above or below the main\
+diagonal; above for positive @var{k} and below for negative @var{k}.\
 \n\
 The absolute value of @var{k} must not be greater than the number of\n\
 sub-diagonals or super-diagonals.\n\
--- a/libinterp/dldfcn/fftw.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/dldfcn/fftw.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -267,3 +267,32 @@
 
   return retval;
 }
+
+/*
+
+%!testif HAVE_FFTW
+%! def_method = fftw ("planner");
+%! unwind_protect
+%!   method = "estimate";
+%!   fftw ("planner", method);
+%!   assert (fftw ("planner"), method);
+%!   method = "measure";
+%!   fftw ("planner", method);
+%!   assert (fftw ("planner"), method);
+%!   method = "patient";
+%!   fftw ("planner", method);
+%!   assert (fftw ("planner"), method);
+%!   method = "exhaustive";
+%!   fftw ("planner", method);
+%!   assert (fftw ("planner"), method);
+%!   method = "hybrid";
+%!   fftw ("planner", method);
+%!   assert (fftw ("planner"), method);
+%! unwind_protect_cleanup
+%!   fftw ("planner", def_method);
+%! end_unwind_protect
+
+%!error <Invalid call to fftw> fftw ();
+%!error <Invalid call to fftw> fftw ("planner", "estimate", "measure");
+
+ */
--- a/libinterp/dldfcn/module-files	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/dldfcn/module-files	Sun Dec 23 13:00:02 2012 -0500
@@ -9,7 +9,7 @@
 __voronoi__.cc|$(QHULL_CPPFLAGS)|$(QHULL_LDFLAGS)|$(QHULL_LIBS)
 amd.cc|$(SPARSE_XCPPFLAGS)|$(SPARSE_XLDFLAGS)|$(SPARSE_XLIBS)
 ccolamd.cc|$(SPARSE_XCPPFLAGS)|$(SPARSE_XLDFLAGS)|$(SPARSE_XLIBS)
-chol.cc
+chol.cc|$(SPARSE_XCPPFLAGS)|$(SPARSE_XLDFLAGS)|$(SPARSE_XLIBS)
 colamd.cc|$(SPARSE_XCPPFLAGS)|$(SPARSE_XLDFLAGS)|$(SPARSE_XLIBS)
 convhulln.cc|$(QHULL_CPPFLAGS)|$(QHULL_LDFLAGS)|$(QHULL_LIBS)
 dmperm.cc|$(SPARSE_XCPPFLAGS)|$(SPARSE_XLDFLAGS)|$(SPARSE_XLIBS)
--- a/libinterp/interp-core/action-container.h	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/interp-core/action-container.h	Sun Dec 23 13:00:02 2012 -0500
@@ -31,7 +31,6 @@
 // FIXME -- is there a better name for this class?
 
 class
-OCTINTERP_API
 action_container
 {
 public:
--- a/libinterp/interp-core/event-queue.h	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/interp-core/event-queue.h	Sun Dec 23 13:00:02 2012 -0500
@@ -29,7 +29,6 @@
 #include "action-container.h"
 
 class
-OCTINTERP_API
 event_queue : public action_container
 {
 public:
--- a/libinterp/interp-core/jit-ir.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/interp-core/jit-ir.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -80,6 +80,16 @@
   insert_before (loc->location (), ablock);
 }
 
+void
+jit_block_list::label (void)
+{
+  if (mlist.size ())
+    {
+      jit_block *block = mlist.back ();
+      block->label ();
+    }
+}
+
 std::ostream&
 jit_block_list::print (std::ostream& os, const std::string& header) const
 {
@@ -469,6 +479,21 @@
 }
 
 void
+jit_block::label (size_t avisit_count, size_t& number)
+{
+  if (visited (avisit_count))
+    return;
+
+  for (jit_use *use = first_use (); use; use = use->next ())
+    {
+      jit_block *pred = use->user_parent ();
+      pred->label (avisit_count, number);
+    }
+
+  mid = number++;
+}
+
+void
 jit_block::pop_all (void)
 {
   for (iterator iter = begin (); iter != end (); ++iter)
@@ -478,6 +503,28 @@
     }
 }
 
+std::ostream&
+jit_block::print (std::ostream& os, size_t indent) const
+{
+  print_indent (os, indent);
+  short_print (os) << ":        %pred = ";
+  for (jit_use *use = first_use (); use; use = use->next ())
+    {
+      jit_block *pred = use->user_parent ();
+      os << *pred;
+      if (use->next ())
+        os << ", ";
+    }
+  os << std::endl;
+
+  for (const_iterator iter = begin (); iter != end (); ++iter)
+    {
+      jit_instruction *instr = *iter;
+      instr->print (os, indent + 1) << std::endl;
+    }
+  return os;
+}
+
 jit_block *
 jit_block::maybe_split (jit_factory& factory, jit_block_list& blocks,
                         jit_block *asuccessor)
@@ -651,6 +698,23 @@
 
 // -------------------- jit_call --------------------
 bool
+jit_call::needs_release (void) const
+{
+  if (type () && jit_typeinfo::get_release (type ()).valid ())
+    {
+      for (jit_use *use = first_use (); use; use = use->next ())
+        {
+          jit_assign *assign = dynamic_cast<jit_assign *> (use->user ());
+          if (assign && assign->artificial ())
+            return false;
+        }
+
+      return true;
+    }
+  return false;
+}
+
+bool
 jit_call::infer (void)
 {
   // FIXME: explain algorithm
@@ -679,6 +743,33 @@
   return false;
 }
 
+// -------------------- jit_error_check --------------------
+std::string
+jit_error_check::variable_to_string (variable v)
+{
+  switch (v)
+    {
+    case var_error_state:
+      return "error_state";
+    case var_interrupt:
+      return "interrupt";
+    default:
+      panic_impossible ();
+    }
+}
+
+std::ostream&
+jit_error_check::print (std::ostream& os, size_t indent) const
+{
+  print_indent (os, indent) << "error_check " << variable_to_string (mvariable)
+                            << ", ";
+
+  if (has_check_for ())
+    os << "<for> " << *check_for () << ", ";
+  print_successor (os << "<normal> ", 1) << ", ";
+  return print_successor (os << "<error> ", 0);
+}
+
 // -------------------- jit_magic_end --------------------
 jit_magic_end::context::context (jit_factory& factory, jit_value *avalue,
                                  size_t aindex, size_t acount)
--- a/libinterp/interp-core/jit-ir.h	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/interp-core/jit-ir.h	Sun Dec 23 13:00:02 2012 -0500
@@ -169,6 +169,8 @@
 
   void insert_before (jit_block *loc, jit_block *ablock);
 
+  void label (void);
+
   std::ostream& print (std::ostream& os, const std::string& header) const;
 
   std::ostream& print_dom (std::ostream& os) const;
@@ -654,19 +656,7 @@
     label (mvisit_count, number);
   }
 
-  void label (size_t avisit_count, size_t& number)
-  {
-    if (visited (avisit_count))
-      return;
-
-    for (jit_use *use = first_use (); use; use = use->next ())
-      {
-        jit_block *pred = use->user_parent ();
-        pred->label (avisit_count, number);
-      }
-
-    mid = number++;
-  }
+  void label (size_t avisit_count, size_t& number);
 
   // See for idom computation algorithm
   // Cooper, Keith D.; Harvey, Timothy J; and Kennedy, Ken (2001).
@@ -704,26 +694,7 @@
   // call pop_varaible on all instructions
   void pop_all (void);
 
-  virtual std::ostream& print (std::ostream& os, size_t indent = 0) const
-  {
-    print_indent (os, indent);
-    short_print (os) << ":        %pred = ";
-    for (jit_use *use = first_use (); use; use = use->next ())
-      {
-        jit_block *pred = use->user_parent ();
-        os << *pred;
-        if (use->next ())
-          os << ", ";
-      }
-    os << std::endl;
-
-    for (const_iterator iter = begin (); iter != end (); ++iter)
-      {
-        jit_instruction *instr = *iter;
-        instr->print (os, indent + 1) << std::endl;
-      }
-    return os;
-  }
+  virtual std::ostream& print (std::ostream& os, size_t indent = 0) const;
 
   jit_block *maybe_split (jit_factory& factory, jit_block_list& blocks,
                           jit_block *asuccessor);
@@ -742,6 +713,8 @@
     os << mname;
     if (mid != NO_ID)
       os << mid;
+    else
+      os << "!";
     return os;
   }
 
@@ -1203,10 +1176,7 @@
     return moperation.overload (argument_types ());
   }
 
-  virtual bool needs_release (void) const
-  {
-    return type () && jit_typeinfo::get_release (type ()).valid ();
-  }
+  virtual bool needs_release (void) const;
 
   virtual std::ostream& print (std::ostream& os, size_t indent = 0) const
   {
@@ -1233,33 +1203,53 @@
 };
 
 // FIXME: This is just ugly...
-// checks error_state, if error_state is false then goto the normal branche,
+// checks error_state, if error_state is false then goto the normal branch,
 // otherwise goto the error branch
 class
 jit_error_check : public jit_terminator
 {
 public:
-  jit_error_check (jit_call *acheck_for, jit_block *normal, jit_block *error)
-    : jit_terminator (2, error, normal, acheck_for) {}
+  // Which variable is the error check for?
+  enum variable
+    {
+      var_error_state,
+      var_interrupt
+    };
+
+  static std::string variable_to_string (variable v);
+
+  jit_error_check (variable var, jit_call *acheck_for, jit_block *normal,
+                   jit_block *error)
+    : jit_terminator (2, error, normal, acheck_for), mvariable (var) {}
+
+  jit_error_check (variable var, jit_block *normal, jit_block *error)
+    : jit_terminator (2, error, normal), mvariable (var) {}
+
+  variable check_variable (void) const { return mvariable; }
+
+  bool has_check_for (void) const
+  {
+    return argument_count () == 3;
+  }
 
   jit_call *check_for (void) const
   {
+    assert (has_check_for ());
     return static_cast<jit_call *> (argument (2));
   }
 
-  virtual std::ostream& print (std::ostream& os, size_t indent = 0) const
-  {
-    print_indent (os, indent) << "error_check " << *check_for () << ", ";
-    print_successor (os, 1) << ", ";
-    return print_successor (os, 0);
-  }
+  virtual std::ostream& print (std::ostream& os, size_t indent = 0) const;
 
   JIT_VALUE_ACCEPT;
 protected:
   virtual bool check_alive (size_t idx) const
   {
+    if (! has_check_for ())
+      return true;
     return idx == 1 ? true : check_for ()->can_error ();
   }
+private:
+  variable mvariable;
 };
 
 // for now only handles the 1D case
--- a/libinterp/interp-core/jit-typeinfo.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/interp-core/jit-typeinfo.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -633,8 +633,6 @@
     throw jit_fail_exception ("Call not implemented");
 
   assert (in_args.size () == args.size ());
-  llvm::Function *stacksave
-    = llvm::Intrinsic::getDeclaration (module, llvm::Intrinsic::stacksave);
   llvm::SmallVector<llvm::Value *, 10> llvm_args;
   llvm_args.reserve (in_args.size () + sret ());
 
@@ -1112,6 +1110,15 @@
   engine->addGlobalMapping (lerror_state,
                             reinterpret_cast<void *> (&error_state));
 
+  // sig_atomic_type is going to be some sort of integer
+  sig_atomic_type = llvm::Type::getIntNTy (context, sizeof(sig_atomic_t) * 8);
+  loctave_interrupt_state
+    = new llvm::GlobalVariable (*module, sig_atomic_type, false,
+                                llvm::GlobalValue::ExternalLinkage, 0,
+                                "octave_interrupt_state");
+  engine->addGlobalMapping (loctave_interrupt_state,
+                            reinterpret_cast<void *> (&octave_interrupt_state));
+
   // generic call function
   {
     jit_type *int_t = intN (sizeof (octave_builtin::fcn) * 8);
@@ -1322,12 +1329,29 @@
     llvm::Value *one = builder.getInt32 (1);
     llvm::Value *two = builder.getInt32 (2);
     llvm::Value *three = builder.getInt32 (3);
+    llvm::Value *fzero = llvm::ConstantFP::get (scalar_t, 0);
+
+    // we are really dealing with a complex number OR a scalar. That is, if the
+    // complex component is 0, we really have a scalar. This matters in
+    // 0+0i * NaN
+    llvm::BasicBlock *complex_mul = fn.new_block ("complex_mul");
+    llvm::BasicBlock *real_mul = fn.new_block ("real_mul");
+    llvm::BasicBlock *ret_block = fn.new_block ("ret");
+    llvm::Value *temp = builder.CreateFCmpUEQ (complex_imag (lhs), fzero);
+    llvm::Value *temp2 = builder.CreateFCmpUEQ (complex_imag (rhs), fzero);
+    temp = builder.CreateAnd (temp, temp2);
+    builder.CreateCondBr (temp, real_mul, complex_mul);
+
+    builder.SetInsertPoint(real_mul);
+    temp = builder.CreateFMul (complex_real (lhs), complex_real (rhs));
+    llvm::Value *real_branch_ret = complex_new (temp, fzero);
+    builder.CreateBr (ret_block);
 
     llvm::Type *vec4 = llvm::VectorType::get (scalar_t, 4);
     llvm::Value *mlhs = llvm::UndefValue::get (vec4);
     llvm::Value *mrhs = mlhs;
-
-    llvm::Value *temp = complex_real (lhs);
+    builder.SetInsertPoint (complex_mul);
+    temp = complex_real (lhs);
     mlhs = builder.CreateInsertElement (mlhs, temp, zero);
     mlhs = builder.CreateInsertElement (mlhs, temp, two);
     temp = complex_imag (lhs);
@@ -1349,7 +1373,15 @@
     tlhs = builder.CreateExtractElement (mres, two);
     trhs = builder.CreateExtractElement (mres, three);
     llvm::Value *ret_imag = builder.CreateFAdd (tlhs, trhs);
-    fn.do_return (builder, complex_new (ret_real, ret_imag));
+    llvm::Value *complex_branch_ret = complex_new (ret_real, ret_imag);
+    builder.CreateBr (ret_block);
+
+    builder.SetInsertPoint (ret_block);
+    llvm::PHINode *merge = llvm::PHINode::Create(complex_t, 2);
+    builder.Insert (merge);
+    merge->addIncoming (real_branch_ret, real_mul);
+    merge->addIncoming (complex_branch_ret, complex_mul);
+    fn.do_return (builder, merge);
   }
 
   binary_ops[octave_value::op_mul].add_overload (fn);
@@ -1381,10 +1413,25 @@
   body = fn.new_block ();
   builder.SetInsertPoint (body);
   {
+    llvm::BasicBlock *complex_mul = fn.new_block ("complex_mul");
+    llvm::BasicBlock *scalar_mul = fn.new_block ("scalar_mul");
+
+    llvm::Value *fzero = llvm::ConstantFP::get (scalar_t, 0);
     llvm::Value *lhs = fn.argument (builder, 0);
-    llvm::Value *tlhs = complex_new (lhs, lhs);
     llvm::Value *rhs = fn.argument (builder, 1);
-    fn.do_return (builder, builder.CreateFMul (tlhs, rhs));
+
+    llvm::Value *cmp = builder.CreateFCmpUEQ (complex_imag (rhs), fzero);
+    builder.CreateCondBr (cmp, scalar_mul, complex_mul);
+
+    builder.SetInsertPoint (scalar_mul);
+    llvm::Value *temp = complex_real (rhs);
+    temp = builder.CreateFMul (lhs, temp);
+    fn.do_return (builder, complex_new (temp, fzero), false);
+
+
+    builder.SetInsertPoint (complex_mul);
+    temp = complex_new (lhs, lhs);
+    fn.do_return (builder, builder.CreateFMul (temp, rhs));
   }
   binary_ops[octave_value::op_mul].add_overload (fn);
   binary_ops[octave_value::op_el_mul].add_overload (fn);
@@ -1761,7 +1808,7 @@
   casts[scalar->type_id ()].stash_name ("(scalar)");
   casts[complex->type_id ()].stash_name ("(complex)");
   casts[matrix->type_id ()].stash_name ("(matrix)");
-  casts[any->type_id ()].stash_name ("(range)");
+  casts[range->type_id ()].stash_name ("(range)");
 
   // cast any <- matrix
   fn = create_function (jit_convention::external, "octave_jit_cast_any_matrix",
@@ -2040,6 +2087,14 @@
   return abuilder.CreateLoad (lerror_state);
 }
 
+llvm::Value *
+jit_typeinfo::do_insert_interrupt_check (llvm::IRBuilderD& abuilder)
+{
+  llvm::LoadInst *val = abuilder.CreateLoad (loctave_interrupt_state);
+  val->setVolatile (true);
+  return abuilder.CreateICmpSGT (val, abuilder.getInt32 (0));
+}
+
 void
 jit_typeinfo::add_builtin (const std::string& name)
 {
@@ -2273,7 +2328,14 @@
     }
 
   if (ov.is_complex_scalar ())
-    return get_complex ();
+    {
+      Complex cv = ov.complex_value ();
+
+      // We don't really represent complex values, instead we represent
+      // complex_or_scalar. If the imag value is zero, we assume a scalar.
+      if (cv.imag () == 0)
+        return get_complex ();
+    }
 
   return get_any ();
 }
--- a/libinterp/interp-core/jit-typeinfo.h	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/interp-core/jit-typeinfo.h	Sun Dec 23 13:00:02 2012 -0500
@@ -566,6 +566,11 @@
     return instance->do_insert_error_check (bld);
   }
 
+  static llvm::Value *insert_interrupt_check (llvm::IRBuilderD& bld)
+  {
+    return instance->do_insert_interrupt_check (bld);
+  }
+
   static const jit_operation& end (void)
   {
     return instance->end_fn;
@@ -692,6 +697,8 @@
 
   llvm::Value *do_insert_error_check (llvm::IRBuilderD& bld);
 
+  llvm::Value *do_insert_interrupt_check (llvm::IRBuilderD& bld);
+
   void add_builtin (const std::string& name);
 
   void register_intrinsic (const std::string& name, size_t id,
@@ -747,6 +754,9 @@
   int next_id;
 
   llvm::GlobalVariable *lerror_state;
+  llvm::GlobalVariable *loctave_interrupt_state;
+
+  llvm::Type *sig_atomic_type;
 
   std::vector<jit_type*> id_to_type;
   jit_type *any;
--- a/libinterp/interp-core/oct-procbuf.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/interp-core/oct-procbuf.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -42,6 +42,10 @@
 #include "gripes.h"
 #include "utils.h"
 
+#ifndef SHELL_PATH
+#define SHELL_PATH "/bin/sh"
+#endif
+
 // This class is based on the procbuf class from libg++, written by
 // Per Bothner, Copyright (C) 1993 Free Software Foundation.
 
@@ -125,7 +129,7 @@
           octave_procbuf_list = octave_procbuf_list->next;
         }
 
-      execl ("/bin/sh", "sh", "-c", command, static_cast<void *> (0));
+      execl (SHELL_PATH, "sh", "-c", command, static_cast<void *> (0));
 
       exit (127);
     }
--- a/libinterp/interp-core/pt-jit.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/interp-core/pt-jit.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -27,16 +27,18 @@
 #include <config.h>
 #endif
 
+#include "debug.h"
 #include "defun.h"
 #include "ov.h"
 #include "pt-all.h"
 #include "pt-jit.h"
+#include "sighandlers.h"
 #include "symtab.h"
 #include "variables.h"
 
-bool Venable_jit_debugging = false;
-
-bool Venable_jit_compiler = true;
+static bool Venable_jit_debugging = false;
+
+static bool Venable_jit_compiler = true;
 
 #ifdef HAVE_LLVM
 
@@ -60,6 +62,12 @@
 
 static llvm::LLVMContext& context = llvm::getGlobalContext ();
 
+// -------------------- jit_break_exception --------------------
+
+// jit_break is thrown whenever a branch we are converting has only breaks or
+// continues. This is because all code that follows a break or continue is dead.
+class jit_break_exception : public std::exception {};
+
 // -------------------- jit_convert --------------------
 jit_convert::jit_convert (tree &tee, jit_type *for_bounds)
   : converting_function (false)
@@ -69,10 +77,14 @@
   if (for_bounds)
     create_variable (next_for_bounds (false), for_bounds);
 
-  visit (tee);
+  try
+    {
+      visit (tee);
+    }
+  catch (const jit_break_exception&)
+    {}
 
   // breaks must have been handled by the top level loop
-  assert (! breaking);
   assert (breaks.empty ());
   assert (continues.empty ());
 
@@ -119,32 +131,48 @@
     }
 
   jit_value *return_value = 0;
+  bool all_breaking = false;
   if (fcn.is_special_expr ())
     {
       tree_expression *expr = fcn.special_expr ();
       if (expr)
         {
           jit_variable *retvar = get_variable ("#return");
-          jit_value *retval = visit (expr);
+          jit_value *retval;
+          try
+            {
+              retval = visit (expr);
+            }
+          catch (const jit_break_exception&)
+            {}
+
+          if (breaks.size () || continues.size ())
+            throw jit_fail_exception ("break/continue not supported in "
+                                      "anonymous functions");
+
           block->append (factory.create<jit_assign> (retvar, retval));
           return_value = retvar;
         }
     }
   else
-    visit_statement_list (*fcn.body ());
-
-  // the user may use break or continue to exit the function. Because the
-  // function does not start as a loop, we can have one continue, one break, or
-  // a regular fallthrough to exit the function
-  if (continues.size ())
     {
-      assert (! continues.size ());
+      try
+        {
+          visit_statement_list (*fcn.body ());
+        }
+      catch (const jit_break_exception&)
+        {
+          all_breaking = true;
+        }
+
+      // the user may use break or continue to exit the function
       finish_breaks (final_block, continues);
+      finish_breaks (final_block, breaks);
     }
-  else if (breaks.size ())
-    finish_breaks (final_block, breaks);
-  else
+
+  if (! all_breaking)
     block->append (factory.create<jit_branch> (final_block));
+
   blocks.push_back (final_block);
   block = final_block;
 
@@ -250,7 +278,7 @@
 jit_convert::visit_break_command (tree_break_command&)
 {
   breaks.push_back (block);
-  breaking = true;
+  throw jit_break_exception ();
 }
 
 void
@@ -275,7 +303,7 @@
 jit_convert::visit_continue_command (tree_continue_command&)
 {
   continues.push_back (block);
-  breaking = true;
+  throw jit_break_exception ();
 }
 
 void
@@ -310,11 +338,9 @@
   // and used only inside the for loop (e.g. the index variable)
 
   // If we are a nested for loop we need to store the previous breaks
-  assert (! breaking);
   unwind_protect prot;
   prot.protect_var (breaks);
   prot.protect_var (continues);
-  prot.protect_var (breaking);
   breaks.clear ();
   continues.clear ();
 
@@ -353,23 +379,34 @@
 
   // do loop
   tree_statement_list *pt_body = cmd.body ();
-  pt_body->accept (*this);
-
-  if (breaking && continues.empty ())
+  bool all_breaking = false;
+  try
+    {
+      pt_body->accept (*this);
+    }
+  catch (const jit_break_exception&)
     {
-      // WTF are you doing user? Every branch was a continue, why did you have
-      // a loop??? Users are silly people...
-      finish_breaks (tail, breaks);
-      blocks.push_back (tail);
-      block = tail;
-      return;
+      if (continues.empty ())
+        {
+          // WTF are you doing user? Every branch was a break, why did you have
+          // a loop??? Users are silly people...
+          finish_breaks (tail, breaks);
+          blocks.push_back (tail);
+          block = tail;
+          return;
+        }
+
+      all_breaking = true;
     }
 
   // check our condition, continues jump to this block
   jit_block *check_block = factory.create<jit_block> ("for_check");
   blocks.push_back (check_block);
 
-  if (! breaking)
+  jit_block *interrupt_check = factory.create<jit_block> ("for_interrupt");
+  blocks.push_back (interrupt_check);
+
+  if (! all_breaking)
     block->append (factory.create<jit_branch> (check_block));
   finish_breaks (check_block, continues);
 
@@ -379,9 +416,16 @@
   jit_call *iter_inc = factory.create<jit_call> (add_fn, iterator, one);
   block->append (iter_inc);
   block->append (factory.create<jit_assign> (iterator, iter_inc));
-  check = block->append (factory.create<jit_call> (jit_typeinfo::for_check, control,
-                                           iterator));
-  block->append (factory.create<jit_cond_branch> (check, body, tail));
+  check = block->append (factory.create<jit_call> (jit_typeinfo::for_check,
+                                                   control, iterator));
+  block->append (factory.create<jit_cond_branch> (check, interrupt_check,
+                                                  tail));
+
+  block = interrupt_check;
+  jit_error_check *ec
+    = factory.create<jit_error_check> (jit_error_check::var_interrupt,
+                                       body, final_block);
+  block->append (ec);
 
   // breaks will go to our tail
   blocks.push_back (tail);
@@ -486,6 +530,13 @@
   if (! last_else)
     entry_blocks[entry_blocks.size () - 1] = tail;
 
+
+  // each branch in the if statement will have different breaks/continues
+  block_list current_breaks = breaks;
+  block_list current_continues = continues;
+  breaks.clear ();
+  continues.clear ();
+
   size_t num_incomming = 0; // number of incomming blocks to our tail
   iter = lst.begin ();
   for (size_t i = 0; iter != lst.end (); ++iter, ++i)
@@ -515,17 +566,23 @@
 
       tree_statement_list *stmt_lst = tic->commands ();
       assert (stmt_lst); // jwe: Can this be null?
-      stmt_lst->accept (*this);
-
-      if (breaking)
-        breaking = false;
-      else
+
+      try
         {
+          stmt_lst->accept (*this);
           ++num_incomming;
           block->append (factory.create<jit_branch> (tail));
         }
+      catch(const jit_break_exception&)
+        {}
+
+      current_breaks.splice (current_breaks.end (), breaks);
+      current_continues.splice (current_continues.end (), continues);
     }
 
+  breaks.splice (breaks.end (), current_breaks);
+  continues.splice (continues.end (), current_continues);
+
   if (num_incomming || ! last_else)
     {
       blocks.push_back (tail);
@@ -533,7 +590,7 @@
     }
   else
     // every branch broke, so we don't have a tail
-    breaking = true;
+    throw jit_break_exception ();
 }
 
 void
@@ -570,17 +627,19 @@
 jit_convert::visit_constant (tree_constant& tc)
 {
   octave_value v = tc.rvalue1 ();
-  if (v.is_real_scalar () && v.is_double_type () && ! v.is_complex_type ())
+  jit_type *ty = jit_typeinfo::type_of (v);
+
+  if (ty == jit_typeinfo::get_scalar ())
     {
       double dv = v.double_value ();
       result = factory.create<jit_const_scalar> (dv);
     }
-  else if (v.is_range ())
+  else if (ty == jit_typeinfo::get_range ())
     {
       Range rv = v.range_value ();
       result = factory.create<jit_const_range> (rv);
     }
-  else if (v.is_complex_scalar ())
+  else if (ty == jit_typeinfo::get_complex ())
     {
       Complex cv = v.complex_value ();
       result = factory.create<jit_const_complex> (cv);
@@ -711,9 +770,6 @@
       // jwe: Can this ever be null?
       assert (elt);
       elt->accept (*this);
-
-      if (breaking)
-        break;
     }
 }
 
@@ -750,11 +806,9 @@
 void
 jit_convert::visit_while_command (tree_while_command& wc)
 {
-  assert (! breaking);
   unwind_protect prot;
   prot.protect_var (breaks);
   prot.protect_var (continues);
-  prot.protect_var (breaking);
   breaks.clear ();
   continues.clear ();
 
@@ -776,14 +830,36 @@
   block = body;
 
   tree_statement_list *loop_body = wc.body ();
+  bool all_breaking = false;
   if (loop_body)
-    loop_body->accept (*this);
+    {
+      try
+        {
+          loop_body->accept (*this);
+        }
+      catch (const jit_break_exception&)
+        {
+          all_breaking = true;
+        }
+    }
 
   finish_breaks (tail, breaks);
-  finish_breaks (cond_check, continues);
-
-  if (! breaking)
-    block->append (factory.create<jit_branch> (cond_check));
+
+  if (! all_breaking || continues.size ())
+    {
+      jit_block *interrupt_check
+        = factory.create<jit_block> ("interrupt_check");
+      blocks.push_back (interrupt_check);
+      finish_breaks (interrupt_check, continues);
+      if (! all_breaking)
+        block->append (factory.create<jit_branch> (interrupt_check));
+
+      block = interrupt_check;
+      jit_error_check *ec
+        = factory.create<jit_error_check> (jit_error_check::var_interrupt,
+                                           cond_check, final_block);
+      block->append (ec);
+    }
 
   blocks.push_back (tail);
   block = tail;
@@ -802,7 +878,6 @@
   iterator_count = 0;
   for_bounds_count = 0;
   short_count = 0;
-  breaking = false;
   jit_instruction::reset_ids ();
 
   entry_block = factory.create<jit_block> ("body");
@@ -818,8 +893,9 @@
   block->append (ret);
 
   jit_block *normal = factory.create<jit_block> (block->name ());
-  jit_error_check *check = factory.create<jit_error_check> (ret, normal,
-                                                            final_block);
+  jit_error_check *check
+    = factory.create<jit_error_check> (jit_error_check::var_error_state, ret,
+                                       normal, final_block);
   block->append (check);
   blocks.push_back (normal);
   block = normal;
@@ -1312,7 +1388,20 @@
 void
 jit_convert_llvm::visit (jit_error_check& check)
 {
-  llvm::Value *cond = jit_typeinfo::insert_error_check (builder);
+  llvm::Value *cond;
+
+  switch (check.check_variable ())
+    {
+    case jit_error_check::var_error_state:
+      cond = jit_typeinfo::insert_error_check (builder);
+      break;
+    case jit_error_check::var_interrupt:
+      cond = jit_typeinfo::insert_interrupt_check (builder);
+      break;
+    default:
+      panic_impossible ();
+    }
+
   llvm::Value *br = builder.CreateCondBr (cond, check.successor_llvm (0),
                                           check.successor_llvm (1));
   check.stash_llvm (br);
@@ -1388,7 +1477,7 @@
     }
 
   remove_dead ();
-  final_block ().label ();
+  blocks.label ();
   place_releases ();
   simplify_phi ();
 }
@@ -1422,7 +1511,7 @@
 void
 jit_infer::construct_ssa (void)
 {
-  final_block ().label ();
+  blocks.label ();
   final_block ().compute_idom (entry_block ());
   entry_block ().compute_df ();
   entry_block ().create_dom_tree ();
@@ -1793,7 +1882,7 @@
   const size_t MIN_TRIP_COUNT = 1000;
 
   size_t tc = trip_count (bounds);
-  if (! tc || ! initialize ())
+  if (! tc || ! initialize () || ! enabled ())
     return false;
 
   jit_info::vmap extra_vars;
@@ -1816,7 +1905,7 @@
 bool
 tree_jit::do_execute (tree_while_command& cmd)
 {
-  if (! initialize ())
+  if (! initialize () || ! enabled ())
     return false;
 
   jit_info *info = cmd.get_info ();
@@ -1834,7 +1923,7 @@
 tree_jit::do_execute (octave_user_function& fcn, const octave_value_list& args,
                       octave_value_list& retval)
 {
-  if (! initialize ())
+  if (! initialize () || ! enabled ())
     return false;
 
   jit_function_info *info = fcn.get_info ();
@@ -1848,6 +1937,16 @@
     return info->execute (args, retval);
 }
 
+bool
+tree_jit::enabled (void)
+{
+  // Ideally, we should only disable JIT if there is a breakpoint in the code we
+  // are about to run. However, we can't figure this out in O(1) time, so we
+  // conservatively check for the existence of any breakpoints.
+  return Venable_jit_compiler && ! bp_table::have_breakpoints ()
+    && ! Vdebug_on_interrupt && ! Vdebug_on_error;
+}
+
 size_t
 tree_jit::trip_count (const octave_value& bounds) const
 {
@@ -1903,8 +2002,7 @@
       if (Venable_jit_debugging)
         {
           jit_block_list& blocks = infer.get_blocks ();
-          jit_block *entry_block = blocks.front ();
-          entry_block->label ();
+          blocks.label ();
           std::cout << "-------------------- Compiling function ";
           std::cout << "--------------------\n";
 
@@ -2018,6 +2116,8 @@
   if (ret)
     retval(0) = octave_value (ret);
 
+  octave_quit ();
+
   return true;
 }
 
@@ -2086,6 +2186,8 @@
         symbol_table::varref (arguments[i].first) = real_arguments[i];
     }
 
+  octave_quit ();
+
   return true;
 }
 
@@ -2123,8 +2225,7 @@
       if (Venable_jit_debugging)
         {
           jit_block_list& blocks = infer.get_blocks ();
-          jit_block *entry_block = blocks.front ();
-          entry_block->label ();
+          blocks.label ();
           std::cout << "-------------------- Compiling tree --------------------\n";
           std::cout << tee.str_print_code () << std::endl;
           blocks.print (std::cout, "octave jit ir");
@@ -2227,6 +2328,33 @@
 Test some simple cases that compile.
 
 %!test
+%! for i=1:1e6
+%!   if i < 5
+%!     break
+%!   else
+%!     break
+%!   endif
+%! endfor
+%! assert (i, 1);
+
+%!test
+%! while 1
+%!   if 1
+%!     break
+%!  else
+%!    break
+%!  endif
+%! endwhile
+
+%!test
+%! for i=1:1e6
+%!   if i == 100
+%!     break
+%!   endif
+%! endfor
+%! assert (i, 100);
+
+%!test
 %! inc = 1e-5;
 %! result = 0;
 %! for ii = 0:inc:1
@@ -2244,6 +2372,35 @@
 %! assert (abs (result - 1/9) < 1e-5);
 
 %!test
+%! temp = 1+1i;
+%! nan = NaN;
+%! while 1
+%!   temp = temp - 1i;
+%!   temp = temp * nan;
+%!   break;
+%! endwhile
+%! assert (imag (temp), 0);
+
+%!test
+%! temp = 1+1i;
+%! nan = NaN+1i;
+%! while 1
+%!   nan = nan - 1i;
+%!   temp = temp - 1i;
+%!   temp = temp * nan;
+%!   break;
+%! endwhile
+%! assert (imag (temp), 0);
+
+%!test
+%! temp = 1+1i;
+%! while 1
+%!   temp = temp * 5;
+%!   break;
+%! endwhile
+%! assert (temp, 5+5i);
+
+%!test
 %! nr = 1001;
 %! mat = zeros (1, nr);
 %! for i = 1:nr
--- a/libinterp/interp-core/pt-jit.h	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/interp-core/pt-jit.h	Sun Dec 23 13:00:02 2012 -0500
@@ -231,8 +231,6 @@
 
   jit_value *visit (tree& tee);
 
-  bool breaking; // true if we are breaking OR continuing
-
   typedef std::list<jit_block *> block_list;
   block_list breaks;
   block_list continues;
@@ -379,6 +377,8 @@
   bool do_execute (octave_user_function& fcn, const octave_value_list& args,
                    octave_value_list& retval);
 
+  bool enabled (void);
+
   size_t trip_count (const octave_value& bounds) const;
 
   llvm::Module *module;
@@ -439,11 +439,4 @@
 };
 
 #endif
-
-// If TRUE, enable JIT compiler debugging/tracing.
-extern bool Venable_jit_debugging;
-
-// If TRUE, enable JIT compiler.
-extern bool Venable_jit_compiler;
-
 #endif
--- a/libinterp/interpfcn/data.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/interpfcn/data.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -2792,7 +2792,13 @@
             MAKE_INT_BRANCH (uint32);
             MAKE_INT_BRANCH (uint64);
 #undef MAKE_INT_BRANCH
-
+            // GAGME: Accursed Matlab compatibility...
+            case btyp_char:
+              if (isextra)
+                retval = arg.array_value (true).xsum (dim);
+              else
+                retval = arg.array_value (true).sum (dim);
+              break;
             case btyp_bool:
               if (arg.is_sparse_type ())
                 {
@@ -2874,6 +2880,9 @@
 %!assert (sum (zeros (2, 2, 0, 3, "single"), 4), zeros (2, 2, 0, "single"))
 %!assert (sum (zeros (2, 2, 0, 3, "single"), 7), zeros (2, 2, 0, 3, "single"))
 
+;-)
+%!assert (sum ("Octave") + "8", sumsq (primes (17)))
+
 %!error sum ()
 */
 
--- a/libinterp/interpfcn/debug.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/interpfcn/debug.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -794,21 +794,24 @@
 
 DEFUN (dbtype, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Built-in Function} {} dbtype ()\n\
-@deftypefnx {Built-in Function} {} dbtype (\"startl:endl\")\n\
-@deftypefnx {Built-in Function} {} dbtype (\"startl:end\")\n\
-@deftypefnx {Built-in Function} {} dbtype (\"@var{func}\")\n\
-@deftypefnx {Built-in Function} {} dbtype (\"@var{func}\", \"startl\")\n\
-@deftypefnx {Built-in Function} {} dbtype (\"@var{func}\", \"startl:endl\")\n\
-@deftypefnx {Built-in Function} {} dbtype (\"@var{func}\", \"startl:end\")\n\
-When in debugging mode and called with no arguments, list the script file\n\
-being debugged with line numbers.  An optional range specification,\n\
-specified as a string, can be used to list only a portion of the file.\n\
-The special keyword \"end\" is a valid line number specification.\n\
+@deftypefn  {Command} {} dbtype\n\
+@deftypefnx {Command} {} dbtype @var{lineno}\n\
+@deftypefnx {Command} {} dbtype @var{startl:endl}\n\
+@deftypefnx {Command} {} dbtype @var{startl:end}\n\
+@deftypefnx {Command} {} dbtype @var{func}\n\
+@deftypefnx {Command} {} dbtype @var{func} @var{lineno}\n\
+@deftypefnx {Command} {} dbtype @var{func} @var{startl:endl}\n\
+@deftypefnx {Command} {} dbtype @var{func} @var{startl:end}\n\
+Display a script file with line numbers.\n\
 \n\
-When called with the name of a function, list that script file\n\
-with line numbers.\n\
-@seealso{dbstatus, dbstop}\n\
+When called with no arguments in debugging mode, display the script file\n\
+currently being debugged.  An optional range specification can be used to\n\
+list only a portion of the file.  The special keyword \"end\" is a valid\n\
+line number specification for the last line of the file.\n\
+\n\
+When called with the name of a function, list that script file with line\n\
+numbers.\n\
+@seealso{dbwhere, dbstatus, dbstop}\n\
 @end deftypefn")
 {
   octave_value retval;
--- a/libinterp/interpfcn/error.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/interpfcn/error.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -1943,6 +1943,7 @@
 When called from inside a function with the \"local\" option, the variable is\n\
 changed locally for the function and any subroutines it calls.  The original\n\
 variable value is restored when exiting the function.\n\
+@seealso{debug_on_warning, debug_on_interrupt}\n\
 @end deftypefn")
 {
   return SET_INTERNAL_VARIABLE (debug_on_error);
@@ -1959,6 +1960,7 @@
 When called from inside a function with the \"local\" option, the variable is\n\
 changed locally for the function and any subroutines it calls.  The original\n\
 variable value is restored when exiting the function.\n\
+@seealso{debug_on_error, debug_on_interrupt}\n\
 @end deftypefn")
 {
   return SET_INTERNAL_VARIABLE (debug_on_warning);
--- a/libinterp/interpfcn/graphics.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/interpfcn/graphics.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -137,6 +137,10 @@
 {
   Matrix cmap (64, 3, 0.0);
 
+  // Produce X in the same manner as linspace so that 
+  // jet_colormap and jet.m produce *exactly* the same result.
+  double delta = 1.0 / 63.0;
+
   for (octave_idx_type i = 0; i < 64; i++)
     {
       // This is the jet colormap.  It would be nice to be able
@@ -146,7 +150,7 @@
       // called, so calling an interpreted function is not
       // possible.
 
-      double x = i / 63.0;
+      double x = i*delta;
 
       if (x >= 3.0/8.0 && x < 5.0/8.0)
         cmap(i,0) = 4.0 * x - 3.0/2.0;
@@ -2041,13 +2045,12 @@
 void
 graphics_object::set (const octave_map& m)
 {
-  for (octave_map::const_iterator p = m.begin ();
-       p != m.end (); p++)
-    {
-      caseless_str name  = m.key (p);
-
-      octave_value val = octave_value (m.contents (p).elem (m.numel () - 1));
-
+  for (octave_idx_type p = 0; p < m.nfields (); p++)
+    {
+      caseless_str name  = m.keys ()[p];
+
+      octave_value val = octave_value (m.contents (name).elem (m.numel () - 1));
+      
       set_value_or_default (name, val);
 
       if (error_state)
@@ -2066,6 +2069,32 @@
 %! h = plot (1:10, 10:-1:1, 1:10, 1:10);
 %! set (h, struct ("linewidth", {5, 10}));
 %! assert (get (h, "linewidth"), {10; 10});
+## test ordering
+%!test
+%! markchanged = @(h, foobar, name) set (h, "userdata", [get(h,"userdata"); {name}]);
+%! figure (1, "visible", "off")
+%! clf ()
+%! h = line ();
+%! set (h, "userdata", {})
+%! addlistener (h, "color", {markchanged, "color"})
+%! addlistener (h, "linewidth", {markchanged, "linewidth"})
+%! # "linewidth" first
+%! props.linewidth = 2;
+%! props.color = "r";
+%! set (h, props);
+%! assert (get (h, "userdata"), fieldnames (props))
+%! clear props
+%! clf ()
+%! h = line ();
+%! set (h, "userdata", {})
+%! addlistener (h, "color", {markchanged, "color"})
+%! addlistener (h, "linewidth", {markchanged, "linewidth"})
+%! # "color" first
+%! props.color = "r";
+%! props.linewidth = 2;
+%! set (h, props);
+%! assert (get (h, "userdata"), fieldnames (props))
+%! close (1)
 */
 
 // Set a property to a value or to its (factory) default value.
--- a/libinterp/interpfcn/graphics.in.h	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/interpfcn/graphics.in.h	Sun Dec 23 13:00:02 2012 -0500
@@ -1394,7 +1394,7 @@
 
   array_property (const std::string& nm, const graphics_handle& h,
                   const octave_value& m)
-    : base_property (nm, h), data (m),
+    : base_property (nm, h), data (m.is_sparse_type () ? m.full_value () : m),
       xmin (), xmax (), xminp (), xmaxp (),
       type_constraints (), size_constraints ()
     {
@@ -1454,12 +1454,14 @@
 protected:
   bool do_set (const octave_value& v)
     {
-      if (validate (v))
+      octave_value tmp = v.is_sparse_type () ? v.full_value () : v;
+
+      if (validate (tmp))
         {
           // FIXME -- should we check for actual data change?
-          if (! is_equal (v))
+          if (! is_equal (tmp))
             {
-              data = v;
+              data = tmp;
 
               get_data_limits ();
 
--- a/libinterp/interpfcn/help.h	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/interpfcn/help.h	Sun Dec 23 13:00:02 2012 -0500
@@ -36,21 +36,21 @@
 
 // Name of the doc cache file specified on the command line.
 // (--doc-cache-file file)
-extern std::string Vdoc_cache_file;
+extern OCTINTERP_API std::string Vdoc_cache_file;
 
 // Name of the file containing local Texinfo macros that are prepended
 // to doc strings before processing.
 // (--texi-macros-file)
-extern std::string Vtexi_macros_file;
+extern OCTINTERP_API std::string Vtexi_macros_file;
 
 // Name of the info file specified on command line.
 // (--info-file file)
-extern std::string Vinfo_file;
+extern OCTINTERP_API std::string Vinfo_file;
 
 // Name of the info reader we'd like to use.
 // (--info-program program)
-extern std::string Vinfo_program;
+extern OCTINTERP_API std::string Vinfo_program;
 
-extern std::string do_which (const std::string& name);
+extern OCTINTERP_API std::string do_which (const std::string& name);
 
 #endif
--- a/libinterp/interpfcn/oct-hist.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/interpfcn/oct-hist.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -128,25 +128,52 @@
 // means read file, arg of -q means don't number lines.  Arg of N
 // means only display that many items.
 
-static void
-do_history (int argc, const string_vector& argv)
+static string_vector
+do_history (const octave_value_list& args, int nargout)
 {
-  int numbered_output = 1;
+  bool numbered_output = nargout == 0;
 
   unwind_protect frame;
 
+  string_vector hlist;
+
   frame.add_fcn (command_history::set_file, command_history::file ());
 
-  int i;
-  for (i = 1; i < argc; i++)
+  int nargin = args.length ();
+
+  // Number of history lines to show
+  int limit = -1;
+
+  for (octave_idx_type i = 0; i < nargin; i++)
     {
-      std::string option = argv[i];
+      octave_value arg = args(i);
+
+      std::string option;
+
+      if (arg.is_string ())
+        option = arg.string_value ();
+      else if (arg.is_numeric_type ())
+        {
+          limit = arg.int_value ();
+          continue;
+        }
+      else
+        {
+          gripe_wrong_type_arg ("history", arg);
+          return hlist;
+        }
 
       if (option == "-r" || option == "-w" || option == "-a"
           || option == "-n")
         {
-          if (i < argc - 1)
-            command_history::set_file (argv[i+1]);
+          if (i < nargin - 1 && args(i+1).is_string ())
+            command_history::set_file (args(++i).string_value ());
+          else
+            {
+              error ("history: expecting file name for %s option",
+                     option.c_str ());
+              return hlist;
+            }
 
           if (option == "-a")
             // Append 'new' lines to file.
@@ -167,43 +194,49 @@
           else
             panic_impossible ();
 
-          return;
+          return hlist;
         }
-      else if (argv[i] == "-q")
-        numbered_output = 0;
-      else if (argv[i] == "--")
+      else if (option == "-q")
+        numbered_output = false;
+      else if (option == "--")
         {
           i++;
           break;
         }
       else
-        break;
+        {
+          // The last argument found in the command list that looks like
+          // an integer will be used
+          int tmp;
+
+          if (sscanf (option.c_str (), "%d", &tmp) == 1)
+            limit = tmp;
+          else
+            {
+              if (option.length () > 0 && option[0] == '-')
+                error ("history: unrecognized option '%s'", option.c_str ());
+              else
+                error ("history: bad non-numeric arg '%s'", option.c_str ());
+
+              return  hlist;
+            }
+        }
     }
 
-  int limit = -1;
+  if (limit < 0)
+    limit = -limit;
 
-  if (i < argc)
-    {
-      if (sscanf (argv[i].c_str (), "%d", &limit) != 1)
-        {
-          if (argv[i][0] == '-')
-            error ("history: unrecognized option '%s'", argv[i].c_str ());
-          else
-            error ("history: bad non-numeric arg '%s'", argv[i].c_str ());
-
-          return;
-        }
-
-      if (limit < 0)
-        limit = -limit;
-    }
-
-  string_vector hlist = command_history::list (limit, numbered_output);
+  hlist = command_history::list (limit, numbered_output);
 
   int len = hlist.length ();
 
-  for (i = 0; i < len; i++)
-    octave_stdout << hlist[i] << "\n";
+  if (nargout == 0)
+    {
+      for (octave_idx_type i = 0; i < len; i++)
+        octave_stdout << hlist[i] << "\n";
+    }
+
+  return hlist;
 }
 
 // Read the edited history lines from STREAM and return them
@@ -314,9 +347,28 @@
     }
 }
 
+static bool
+get_int_arg (const octave_value& arg, int& val)
+{
+  bool ok = true;
+
+  if (arg.is_string ())
+    {
+      std::string tmp = arg.string_value ();
+
+      ok = sscanf (tmp.c_str (), "%d", &val) == 1;
+    }
+  else if (arg.is_numeric_type ())
+    val = arg.int_value ();
+  else
+    ok = false;
+
+  return ok;
+}
+
 static std::string
-mk_tmp_hist_file (int argc, const string_vector& argv,
-                  int insert_curr, const char *warn_for)
+mk_tmp_hist_file (const octave_value_list& args,
+                  bool insert_curr, const char *warn_for)
 {
   std::string retval;
 
@@ -339,31 +391,34 @@
 
   int hist_end = hist_count;
   int hist_beg = hist_count;
-  int reverse = 0;
+
+  bool reverse = false;
 
   // Process options.
 
-  int usage_error = 0;
-  if (argc == 3)
+  int nargin = args.length ();
+
+  bool usage_error = false;
+  if (nargin == 2)
     {
-      if (sscanf (argv[1].c_str (), "%d", &hist_beg) != 1
-          || sscanf (argv[2].c_str (), "%d", &hist_end) != 1)
-        usage_error = 1;
-      else
+      if (get_int_arg (args(0), hist_beg)
+          && get_int_arg (args(1), hist_end))
         {
           hist_beg--;
           hist_end--;
         }
+      else
+        usage_error = true;
     }
-  else if (argc == 2)
+  else if (nargin == 1)
     {
-      if (sscanf (argv[1].c_str (), "%d", &hist_beg) != 1)
-        usage_error = 1;
-      else
+      if (get_int_arg (args(0), hist_beg))
         {
           hist_beg--;
           hist_end = hist_beg;
         }
+      else
+        usage_error = true;
     }
 
   if (hist_beg < 0 || hist_end < 0 || hist_beg > hist_count
@@ -384,7 +439,7 @@
       int t = hist_end;
       hist_end = hist_beg;
       hist_beg = t;
-      reverse = 1;
+      reverse = true;
     }
 
   std::string name = octave_tempnam ("", "oct-");
@@ -421,9 +476,9 @@
 }
 
 static void
-do_edit_history (int argc, const string_vector& argv)
+do_edit_history (const octave_value_list& args)
 {
-  std::string name = mk_tmp_hist_file (argc, argv, 0, "edit_history");
+  std::string name = mk_tmp_hist_file (args, false, "edit_history");
 
   if (name.empty ())
     return;
@@ -489,9 +544,9 @@
 }
 
 static void
-do_run_history (int argc, const string_vector& argv)
+do_run_history (const octave_value_list& args)
 {
-  std::string name = mk_tmp_hist_file (argc, argv, 1, "run_history");
+  std::string name = mk_tmp_hist_file (args, true, "run_history");
 
   if (name.empty ())
     return;
@@ -570,21 +625,15 @@
 {
   octave_value_list retval;
 
-  int argc = args.length () + 1;
-
-  string_vector argv = args.make_argv ("edit_history");
-
-  if (error_state)
-    return retval;
-
-  do_edit_history (argc, argv);
+  do_edit_history (args);
 
   return retval;
 }
 
-DEFUN (history, args, ,
+DEFUN (history, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn {Command} {} history options\n\
+@deftypefn {Command} history options\n\
+@deftypefnx {Built-in Function} {@var{h} = } history (@var{opt1}, @var{opt2}, @dots{})\n\
 If invoked with no arguments, @code{history} displays a list of commands\n\
 that you have executed.  Valid options are:\n\
 \n\
@@ -609,18 +658,17 @@
 For example, to display the five most recent commands that you have\n\
 typed without displaying line numbers, use the command\n\
 @kbd{history -q 5}.\n\
+\n\
+If invoked with a single output argument, the history will be saved to that\n\
+argument as a cell string and will not be output to screen.\n\
 @end deftypefn")
 {
-  octave_value_list retval;
-
-  int argc = args.length () + 1;
+  octave_value retval;
 
-  string_vector argv = args.make_argv ("history");
+  string_vector hlist = do_history (args, nargout);
 
-  if (error_state)
-    return retval;
-
-  do_history (argc, argv);
+  if (nargout > 0)
+    retval = Cell (hlist);
 
   return retval;
 }
@@ -635,14 +683,7 @@
 {
   octave_value_list retval;
 
-  int argc = args.length () + 1;
-
-  string_vector argv = args.make_argv ("run_history");
-
-  if (error_state)
-    return retval;
-
-  do_run_history (argc, argv);
+  do_run_history (args);
 
   return retval;
 }
--- a/libinterp/interpfcn/sighandlers.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/interpfcn/sighandlers.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -61,7 +61,7 @@
 bool can_interrupt = false;
 
 // TRUE means we should try to enter the debugger on SIGINT.
-static bool Vdebug_on_interrupt = false;
+bool Vdebug_on_interrupt = false;
 
 // Allow users to avoid writing octave-workspace for SIGHUP (sent by
 // closing gnome-terminal, for example).  Note that this variable has
@@ -978,6 +978,7 @@
 When called from inside a function with the \"local\" option, the variable is\n\
 changed locally for the function and any subroutines it calls.  The original\n\
 variable value is restored when exiting the function.\n\
+@seealso{debug_on_error, debug_on_warning}\n\
 @end deftypefn")
 {
   return SET_INTERNAL_VARIABLE (debug_on_interrupt);
--- a/libinterp/interpfcn/sighandlers.h	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/interpfcn/sighandlers.h	Sun Dec 23 13:00:02 2012 -0500
@@ -174,4 +174,7 @@
   static void cleanup_instance (void) { delete instance; instance = 0; }
 };
 
+// TRUE means we should try to enter the debugger on SIGINT.
+extern OCTINTERP_API bool Vdebug_on_interrupt;
+
 #endif
--- a/libinterp/interpfcn/toplev.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/interpfcn/toplev.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -77,6 +77,10 @@
 #include "variables.h"
 #include "version.h"
 
+#ifndef SHELL_PATH
+#define SHELL_PATH "/bin/sh"
+#endif
+
 void (*octave_exit) (int) = ::exit;
 
 // TRUE means the quit() call is allowed.
@@ -950,7 +954,7 @@
                   // FIXME -- should probably replace this
                   // call with something portable.
 
-                  execl ("/bin/sh", "sh", "-c", cmd_str.c_str (),
+                  execl (SHELL_PATH, "sh", "-c", cmd_str.c_str (),
                          static_cast<void *> (0));
 
                   panic_impossible ();
@@ -1346,8 +1350,9 @@
       { false, "QRUPDATE_CPPFLAGS", OCTAVE_CONF_QRUPDATE_CPPFLAGS },
       { false, "QRUPDATE_LDFLAGS", OCTAVE_CONF_QRUPDATE_LDFLAGS },
       { false, "QRUPDATE_LIBS", OCTAVE_CONF_QRUPDATE_LIBS },
-      { false, "QT_INCDIR", OCTAVE_CONF_QT_INCDIR },
-      { false, "QT_LIBDIR", OCTAVE_CONF_QT_LIBDIR },
+      { false, "QT_CPPFLAGS", OCTAVE_CONF_QT_CPPFLAGS },
+      { false, "QT_LDFLAGS", OCTAVE_CONF_QT_LDFLAGS },
+      { false, "QT_LIBS", OCTAVE_CONF_QT_LIBS },
       { false, "RANLIB", OCTAVE_CONF_RANLIB },
       { false, "RDYNAMIC_FLAG", OCTAVE_CONF_RDYNAMIC_FLAG },
       { false, "READLINE_LIBS", OCTAVE_CONF_READLINE_LIBS },
--- a/libinterp/interpfcn/variables.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/interpfcn/variables.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -282,7 +282,7 @@
 
           frame.run ();
 
-          if (tmp.is_defined () && tmp.is_map ())
+          if (tmp.is_defined () && (tmp.is_map () || tmp.is_java ()))
             names = tmp.map_keys ();
         }
     }
--- a/libinterp/link-deps.mk	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/link-deps.mk	Sun Dec 23 13:00:02 2012 -0500
@@ -7,7 +7,6 @@
 endif
 
 LIBOCTINTERP_LINK_DEPS += \
-  $(GRAPHICS_LIBS) \
   $(FT2_LIBS) \
   $(HDF5_LIBS) \
   $(Z_LIBS) \
@@ -17,10 +16,10 @@
   $(X11_LIBS) \
   $(CARBON_LIBS) \
   $(LLVM_LIBS) \
+  $(JAVA_LIBS) \
   $(LAPACK_LIBS)
 
 LIBOCTINTERP_LINK_OPTS = \
-  $(GRAPHICS_LDFLAGS) \
   $(FT2_LDFLAGS) \
   $(HDF5_LDFLAGS) \
   $(Z_LDFLAGS) \
--- a/libinterp/oct-conf.in.h	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/oct-conf.in.h	Sun Dec 23 13:00:02 2012 -0500
@@ -482,12 +482,16 @@
 #define OCTAVE_CONF_QRUPDATE_LIBS %OCTAVE_CONF_QRUPDATE_LIBS%
 #endif
 
-#ifndef OCTAVE_CONF_QT_INCDIR
-#define OCTAVE_CONF_QT_INCDIR %OCTAVE_CONF_QT_INCDIR%
+#ifndef OCTAVE_CONF_QT_CPPFLAGS
+#define OCTAVE_CONF_QT_CPPFLAGS %OCTAVE_CONF_QT_CPPFLAGS%
 #endif
 
-#ifndef OCTAVE_CONF_QT_LIBDIR
-#define OCTAVE_CONF_QT_LIBDIR %OCTAVE_CONF_QT_LIBDIR%
+#ifndef OCTAVE_CONF_QT_LDFLAGS
+#define OCTAVE_CONF_QT_LDFLAGS %OCTAVE_CONF_QT_LDFLAGS%
+#endif
+
+#ifndef OCTAVE_CONF_QT_LIBS
+#define OCTAVE_CONF_QT_LIBS %OCTAVE_CONF_QT_LIBS%
 #endif
 
 #ifndef OCTAVE_CONF_RANLIB
--- a/libinterp/octave-value/module.mk	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/octave-value/module.mk	Sun Dec 23 13:00:02 2012 -0500
@@ -52,6 +52,7 @@
   octave-value/ov-flt-cx-mat.h \
   octave-value/ov-flt-re-diag.h \
   octave-value/ov-flt-re-mat.h \
+  octave-value/ov-java.h \
   octave-value/ov-lazy-idx.h \
   octave-value/ov-mex-fcn.h \
   octave-value/ov-null-mat.h \
@@ -110,6 +111,7 @@
   octave-value/ov-flt-cx-mat.cc \
   octave-value/ov-flt-re-diag.cc \
   octave-value/ov-flt-re-mat.cc \
+  octave-value/ov-java.cc \
   octave-value/ov-lazy-idx.cc \
   octave-value/ov-mex-fcn.cc \
   octave-value/ov-null-mat.cc \
@@ -130,4 +132,14 @@
 noinst_LTLIBRARIES += octave-value/liboctave-value.la
 
 octave_value_liboctave_value_la_SOURCES = $(OCTAVE_VALUE_SRC)
-octave_value_liboctave_value_la_CPPFLAGS = $(liboctinterp_la_CPPFLAGS)
+
+## FIXME -- maybe it would be better to limit the JAVA flags to
+## the compile commands for ov-java.cc?  Does JAVA_LIBS need to be
+## added to LIBOCTINTERP_LINK_DEPS (see libinterp/link-deps.mk)?
+## Should we have a separate set of JAVA_LDFLAGS?
+
+octave_value_liboctave_value_la_CPPFLAGS = \
+  $(liboctinterp_la_CPPFLAGS) \
+  $(JAVA_CPPFLAGS)
+
+octave_value_liboctave_value_la_LIBADD = $(JAVA_LIBS)
--- a/libinterp/octave-value/ov-base.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/octave-value/ov-base.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -1194,6 +1194,8 @@
       "erfcinv",
       "erfc",
       "erfcx",
+      "erfi",
+      "dawson",
       "exp",
       "expm1",
       "finite",
--- a/libinterp/octave-value/ov-base.h	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/octave-value/ov-base.h	Sun Dec 23 13:00:02 2012 -0500
@@ -365,6 +365,8 @@
 
   virtual bool is_object (void) const { return false; }
 
+  virtual bool is_java (void) const { return false; }
+
   virtual bool is_cs_list (void) const { return false; }
 
   virtual bool is_magic_colon (void) const { return false; }
@@ -689,6 +691,8 @@
       umap_erfcinv,
       umap_erfc,
       umap_erfcx,
+      umap_erfi,
+      umap_dawson,
       umap_exp,
       umap_expm1,
       umap_finite,
--- a/libinterp/octave-value/ov-class.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/octave-value/ov-class.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -45,6 +45,9 @@
 #include "mxarray.h"
 #include "oct-lvalue.h"
 #include "ov-class.h"
+#ifdef HAVE_JAVA
+#include "ov-java.h"
+#endif
 #include "ov-fcn.h"
 #include "ov-usr-fcn.h"
 #include "pager.h"
@@ -1921,13 +1924,14 @@
 
 DEFUN (class, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Built-in Function} {} class (@var{expr})\n\
-@deftypefnx {Built-in Function} {} class (@var{s}, @var{id})\n\
-@deftypefnx {Built-in Function} {} class (@var{s}, @var{id}, @var{p}, @dots{})\n\
-Return the class of the expression @var{expr} or create a class with\n\
+@deftypefn  {Function File} {@var{classname} =} class (@var{obj})\n\
+@deftypefnx {Function File} {} class (@var{s}, @var{id})\n\
+@deftypefnx {Function File} {} class (@var{s}, @var{id}, @var{p}, @dots{})\n\
+Return the class of the object @var{obj} or create a class with\n\
 fields from structure @var{s} and name (string) @var{id}.  Additional\n\
 arguments name a list of parent classes from which the new class is\n\
 derived.\n\
+@seealso{typeinfo, isa}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -1937,9 +1941,11 @@
   if (nargin == 0)
     print_usage ();
   else if (nargin == 1)
+    // Called for class of object
     retval = args(0).class_name ();
   else
     {
+      // Called as class constructor
       octave_function *fcn = octave_call_stack::caller ();
 
       std::string id = args(1).string_value ();
@@ -1996,6 +2002,18 @@
   return retval;
 }
 
+/*
+%!assert (class (1.1), "double");
+%!assert (class (single (1.1)), "single");
+%!assert (class (uint8 (1)), "uint8");
+%!testif HAVE_JAVA
+%! jobj = javaObject ("java.lang.StringBuffer");
+%! assert (class (jobj), "java.lang.StringBuffer");
+
+%% Test Input Validation
+%!error class ()
+*/
+
 DEFUN (__isa_parent__, args, ,
   "-*- texinfo -*-\n\
 @deftypefn {Built-in Function} {} __isa_parent__ (@var{class}, @var{name})\n\
@@ -2103,47 +2121,33 @@
   return retval;
 }
 
-DEFUN (methods, args, nargout,
+DEFUN (__methods__, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Built-in Function} {} methods (@var{x})\n\
-@deftypefnx {Built-in Function} {} methods (\"classname\")\n\
-Return a cell array containing the names of the methods for the\n\
-object @var{x} or the named class.\n\
+@deftypefn  {Built-in Function} {} __methods__ (@var{x})\n\
+@deftypefnx {Built-in Function} {} __methods__ (\"classname\")\n\
+Internal function.\n\
+\n\
+Implements @code{methods} for Octave class objects and classnames.\n\
+@seealso{methods}\n\
 @end deftypefn")
 {
   octave_value retval;
 
-  if (args.length () == 1)
-    {
-      octave_value arg = args(0);
-
-      std::string class_name;
+  // Input validation has already been done in methods.m.
+  octave_value arg = args(0);
 
-      if (arg.is_object ())
-        class_name = arg.class_name ();
-      else if (arg.is_string ())
-        class_name = arg.string_value ();
-      else
-        error ("methods: expecting object or class name as argument");
+  std::string class_name;
 
-      if (! error_state)
-        {
-          string_vector sv = load_path::methods (class_name);
-
-          if (nargout == 0)
-            {
-              octave_stdout << "Methods for class " << class_name << ":\n\n";
+  if (arg.is_object ())
+    class_name = arg.class_name ();
+  else if (arg.is_string ())
+    class_name = arg.string_value ();
 
-              sv.list_in_columns (octave_stdout);
-
-              octave_stdout << std::endl;
-            }
-          else
-            retval = Cell (sv);
-        }
+  if (! error_state)
+    {
+      string_vector sv = load_path::methods (class_name);
+      retval = Cell (sv);
     }
-  else
-    print_usage ();
 
   return retval;
 }
--- a/libinterp/octave-value/ov-complex.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/octave-value/ov-complex.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -431,6 +431,11 @@
       SCALAR_MAPPER (asinh, ::asinh);
       SCALAR_MAPPER (atan, ::atan);
       SCALAR_MAPPER (atanh, ::atanh);
+      SCALAR_MAPPER (erf, ::erf);
+      SCALAR_MAPPER (erfc, ::erfc);
+      SCALAR_MAPPER (erfcx, ::erfcx);
+      SCALAR_MAPPER (erfi, ::erfi);
+      SCALAR_MAPPER (dawson, ::dawson);
       SCALAR_MAPPER (ceil, ::ceil);
       SCALAR_MAPPER (conj, std::conj);
       SCALAR_MAPPER (cos, std::cos);
--- a/libinterp/octave-value/ov-cx-mat.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/octave-value/ov-cx-mat.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -777,6 +777,11 @@
       ARRAY_MAPPER (asinh, Complex, ::asinh);
       ARRAY_MAPPER (atan, Complex, ::atan);
       ARRAY_MAPPER (atanh, Complex, ::atanh);
+      ARRAY_MAPPER (erf, Complex, ::erf);
+      ARRAY_MAPPER (erfc, Complex, ::erfc);
+      ARRAY_MAPPER (erfcx, Complex, ::erfcx);
+      ARRAY_MAPPER (erfi, Complex, ::erfi);
+      ARRAY_MAPPER (dawson, Complex, ::dawson);
       ARRAY_MAPPER (ceil, Complex, ::ceil);
       ARRAY_MAPPER (cos, Complex, std::cos);
       ARRAY_MAPPER (cosh, Complex, std::cosh);
--- a/libinterp/octave-value/ov-cx-sparse.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/octave-value/ov-cx-sparse.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -903,6 +903,11 @@
       ARRAY_MAPPER (asinh, Complex, ::asinh);
       ARRAY_MAPPER (atan, Complex, ::atan);
       ARRAY_MAPPER (atanh, Complex, ::atanh);
+      ARRAY_MAPPER (erf, Complex, ::erf);
+      ARRAY_MAPPER (erfc, Complex, ::erfc);
+      ARRAY_MAPPER (erfcx, Complex, ::erfcx);
+      ARRAY_MAPPER (erfi, Complex, ::erfi);
+      ARRAY_MAPPER (dawson, Complex, ::dawson);
       ARRAY_MAPPER (ceil, Complex, ::ceil);
       ARRAY_MAPPER (conj, Complex, std::conj<double>);
       ARRAY_MAPPER (cos, Complex, std::cos);
--- a/libinterp/octave-value/ov-float.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/octave-value/ov-float.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -295,6 +295,8 @@
       SCALAR_MAPPER (erfcinv, ::erfcinv);
       SCALAR_MAPPER (erfc, ::erfcf);
       SCALAR_MAPPER (erfcx, ::erfcx);
+      SCALAR_MAPPER (erfi, ::erfi);
+      SCALAR_MAPPER (dawson, ::dawson);
       SCALAR_MAPPER (gamma, xgamma);
       SCALAR_MAPPER (lgamma, rc_lgamma);
       SCALAR_MAPPER (cbrt, ::cbrtf);
--- a/libinterp/octave-value/ov-flt-complex.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/octave-value/ov-flt-complex.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -416,6 +416,11 @@
       SCALAR_MAPPER (asinh, ::asinh);
       SCALAR_MAPPER (atan, ::atan);
       SCALAR_MAPPER (atanh, ::atanh);
+      SCALAR_MAPPER (erf, ::erf);
+      SCALAR_MAPPER (erfc, ::erfc);
+      SCALAR_MAPPER (erfcx, ::erfcx);
+      SCALAR_MAPPER (erfi, ::erfi);
+      SCALAR_MAPPER (dawson, ::dawson);
       SCALAR_MAPPER (ceil, ::ceil);
       SCALAR_MAPPER (conj, std::conj);
       SCALAR_MAPPER (cos, std::cos);
--- a/libinterp/octave-value/ov-flt-cx-mat.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/octave-value/ov-flt-cx-mat.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -744,6 +744,11 @@
       ARRAY_MAPPER (asinh, FloatComplex, ::asinh);
       ARRAY_MAPPER (atan, FloatComplex, ::atan);
       ARRAY_MAPPER (atanh, FloatComplex, ::atanh);
+      ARRAY_MAPPER (erf, FloatComplex, ::erf);
+      ARRAY_MAPPER (erfc, FloatComplex, ::erfc);
+      ARRAY_MAPPER (erfcx, FloatComplex, ::erfcx);
+      ARRAY_MAPPER (erfi, FloatComplex, ::erfi);
+      ARRAY_MAPPER (dawson, FloatComplex, ::dawson);
       ARRAY_MAPPER (ceil, FloatComplex, ::ceil);
       ARRAY_MAPPER (cos, FloatComplex, std::cos);
       ARRAY_MAPPER (cosh, FloatComplex, std::cosh);
--- a/libinterp/octave-value/ov-flt-re-mat.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/octave-value/ov-flt-re-mat.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -783,6 +783,8 @@
       ARRAY_MAPPER (erfcinv, float, ::erfcinv);
       ARRAY_MAPPER (erfc, float, ::erfcf);
       ARRAY_MAPPER (erfcx, float, ::erfcx);
+      ARRAY_MAPPER (erfi, float, ::erfi);
+      ARRAY_MAPPER (dawson, float, ::dawson);
       ARRAY_MAPPER (gamma, float, xgamma);
       RC_ARRAY_MAPPER (lgamma, FloatComplex, rc_lgamma);
       ARRAY_MAPPER (cbrt, float, ::cbrtf);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libinterp/octave-value/ov-java.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,2311 @@
+/*
+
+Copyright (C) 2007 Michael Goffioul
+
+This file is part of Octave.
+
+Octave is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by the
+Free Software Foundation; either version 3 of the License, or (at your
+option) any later version.
+
+Octave 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/>.
+
+*/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include "defun.h"
+#include "error.h"
+
+#if defined HAVE_JAVA
+
+#if defined (HAVE_WINDOWS_H)
+#include <windows.h>
+#endif
+
+#include <algorithm>
+#include <map>
+#include <iostream>
+#include <fstream>
+
+#include <clocale>
+
+#include "Cell.h"
+#include "cmd-edit.h"
+#include "defaults.h"
+#include "file-ops.h"
+#include "file-stat.h"
+#include "load-path.h"
+#include "oct-env.h"
+#include "oct-shlib.h"
+#include "ov-java.h"
+#include "parse.h"
+#include "variables.h"
+
+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);
+  JNIEXPORT void JNICALL
+  Java_org_octave_OctaveReference_doFinalize (JNIEnv *, jclass, jint);
+
+  JNIEXPORT void JNICALL
+  Java_org_octave_Octave_doInvoke (JNIEnv *, jclass, jint, jobjectArray);
+
+  JNIEXPORT void JNICALL
+  Java_org_octave_Octave_doEvalString (JNIEnv *, jclass, jstring);
+
+  JNIEXPORT jboolean JNICALL
+  Java_org_octave_Octave_needThreadedInvokation (JNIEnv *, jclass);
+}
+
+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_matrix_autoconversion = false;
+bool Vjava_unsigned_autoconversion = true;
+bool Vdebug_java = false;
+
+class JVMArgs
+{
+public:
+
+  JVMArgs (void)
+  {
+    vm_args.version = JNI_VERSION_1_2;
+    vm_args.nOptions = 0;
+    vm_args.options = 0;
+    vm_args.ignoreUnrecognized = false;
+  }
+
+  ~JVMArgs (void)
+  {
+    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 && Vdebug_java)
+              std::cerr << "invalid JVM option, skipping: " << line << std::endl;
+          }
+      }
+  }
+
+private:
+
+  void clean (void)
+  {
+    if (vm_args.options != 0)
+      {
+        for (int i = 0; i < vm_args.nOptions; i++)
+          delete [] vm_args.options[i].optionString;
+        delete [] vm_args.options;
+
+        vm_args.options = 0;
+        vm_args.nOptions = 0;
+      }
+  }
+
+  void update (void)
+  {
+    clean ();
+
+    if (java_opts.size () > 0)
+      {
+        int index = 0;
+
+        vm_args.nOptions = java_opts.size ();
+        vm_args.options = new JavaVMOption [vm_args.nOptions];
+        for (std::list<std::string>::const_iterator it = java_opts.begin (); it != java_opts.end (); ++it)
+          {
+            if (Vdebug_java)
+              std::cout << *it << std::endl;
+            vm_args.options[index++].optionString = strsave ((*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
+initial_java_dir (void)
+{
+  static std::string java_dir;
+
+  if (java_dir.empty ())
+    {
+      java_dir = octave_env::getenv ("OCTAVE_JAVA_DIR");
+
+      if (java_dir.empty ())
+        java_dir = Vfcn_file_dir + file_ops::dir_sep_str () + "java";
+    }
+
+  return java_dir;
+}
+
+// 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.
+
+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 () > 0)
+            {
+              if (line[0] == '#' || line[0] == '%')
+                ; // skip comments
+              else
+                {
+                  // prepend separator character
+                  classpath.append (dir_path::path_sep_str ());
+
+                  // append content of line without whitespace
+                  int last = line.find_last_not_of (" \t\f\v\r\n");
+
+                  classpath.append (file_ops::tilde_expand (line.substr (0, last+1)));
+                }
+            }
+        }
+    }
+
+  return (classpath);
+}
+
+static std::string
+initial_class_path (void)
+{
+  std::string java_dir = initial_java_dir ();
+
+  std::string retval = java_dir;
+
+  // find octave.jar file
+  if (! retval.empty ())
+    {
+      std::string sep = file_ops::dir_sep_str ();
+
+      std::string jar_file = java_dir + sep + "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 an optional file specifying classpaths in 3 places.
+          // 1) Current directory
+          // 2) User's home directory
+          // 3) Octave installation directory where octave.jar resides
+
+          // The filename is "javaclasspath.txt", but historically
+          // has been "classpath.txt" so both are supported.
+          std::string cp_list[] = {"javaclasspath.txt", "classpath.txt"};
+
+          for (int i=0; i<2; i++)
+            {
+              std::string filename = cp_list[i];
+              std::string cp_file = filename;
+              file_stat   cp_exists;
+
+              // Try to find classpath file in the current directory.
+
+              cp_exists = file_stat (cp_file);
+              if (cp_exists)
+                {
+                  // File found.  Add its contents to the static classpath.
+                  std::string classpath = read_classpath_txt (cp_file);
+                  retval.append (classpath);
+                }
+
+              // Try to find classpath file in the user's home directory.
+
+              cp_file = "~" + sep + filename;
+              cp_file = file_ops::tilde_expand (cp_file);
+              cp_exists = file_stat (cp_file);
+              if (cp_exists)
+                {
+                  // File found.  Add its contents to the static classpath.
+                  std::string classpath = read_classpath_txt (cp_file);
+                  retval.append (classpath);
+                }
+
+              // Try to find classpath file in the Octave install directory.
+
+              cp_file = java_dir + sep + filename;
+              cp_exists = file_stat (cp_file);
+              if (cp_exists)
+                {
+                  // File found.  Add its contents to the static classpath.
+                  std::string classpath = read_classpath_txt (cp_file);
+                  retval.append (classpath);
+                }
+            }
+        }
+      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 (void)
+{
+  // Most of the time JVM already exists and has been initialized.
+  if (jvm)
+    return;
+
+  JNIEnv *current_env;
+  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"));
+
+          old_cwd = octave_env::get_current_directory ();
+
+          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  // Not Win32 system
+
+  // JAVA_LDPATH determined by configure and set in config.h
+#if defined (__APPLE__)
+  std::string jvm_lib_path = JAVA_LDPATH + std::string ("/libjvm.dylib");
+#else
+  std::string jvm_lib_path = JAVA_LDPATH + std::string ("/libjvm.so");
+#endif
+
+#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 = reinterpret_cast<JNI_CreateJavaVM_t> (lib.search ("JNI_CreateJavaVM"));
+  JNI_GetCreatedJavaVMs_t get_vm = reinterpret_cast<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 (reinterpret_cast<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 = const_cast<char *> ("octave");
+          vm_args.group = NULL;
+          if (jvm->AttachCurrentThread (reinterpret_cast<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 ("-Xrs");
+      vm_args.add ("-Djava.system.class.loader=org.octave.OctClassLoader");
+      vm_args.read_java_opts (initial_java_dir () + 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;
+}
+
+bool
+octave_java::is_java_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 octave_value
+check_exception (JNIEnv* jni_env)
+{
+  octave_value retval;
+
+  jthrowable_ref ex (jni_env, jni_env->ExceptionOccurred ());
+
+  if (ex)
+    {
+      if (Vdebug_java)
+        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, const 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, "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, "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 ();
+
+  while (retval.is_undefined ())
+    {
+      // Convert a scalar of any numeric class (byte, short, integer, long,
+      // float, double) to a double value.  Matlab does the same thing.
+      cls = jni_env->FindClass ("java/lang/Number");
+      if (jni_env->IsInstanceOf (jobj, cls))
+        {
+          jmethodID m = jni_env->GetMethodID (cls, "doubleValue", "()D");
+          retval = jni_env->CallDoubleMethod (jobj, m);
+          break;
+        }
+
+      cls = jni_env->FindClass ("java/lang/Boolean");
+      if (jni_env->IsInstanceOf (jobj, cls))
+        {
+          jmethodID m = jni_env->GetMethodID (cls, "booleanValue", "()Z");
+          retval = (jni_env->CallBooleanMethod (jobj, m) ? true : false);
+          break;
+        }
+
+      cls = jni_env->FindClass ("java/lang/String");
+      if (jni_env->IsInstanceOf (jobj, cls))
+        {
+          retval = jstring_to_string (jni_env, jobj);
+          break;
+        }
+
+      cls = jni_env->FindClass ("java/lang/Character");
+      if (jni_env->IsInstanceOf (jobj, cls))
+        {
+          jmethodID m = jni_env->GetMethodID (cls, "charValue", "()C");
+          retval = jni_env->CallCharMethod (jobj, m);
+          retval = retval.convert_to_str (false, true); 
+          break;
+        }
+
+      if (Vjava_matrix_autoconversion)
+        {
+          cls = find_octave_class (jni_env, "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;
+                  break;
+                }
+              else if (s == "byte")
+                {
+                  if (Vjava_unsigned_autoconversion)
+                    {
+                      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 (), reinterpret_cast<jbyte *> (m.fortran_vec ()));
+                      retval = m;
+                      break;
+                    }
+                  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 (), reinterpret_cast<jbyte *> (m.fortran_vec ()));
+                      retval = m;
+                      break;
+                    }
+                }
+              else if (s == "integer")
+                {
+                  if (Vjava_unsigned_autoconversion)
+                    {
+                      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 (), reinterpret_cast<jint *> (m.fortran_vec ()));
+                      retval = m;
+                      break;
+                    }
+                  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 (), reinterpret_cast<jint *> (m.fortran_vec ()));
+                      retval = m;
+                      break;
+                    }
+                }
+            }
+        }
+
+      cls = find_octave_class (jni_env, "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;
+
+          break;
+        }
+
+      // No suitable class found.  Return a generic octave_java object
+      retval = octave_value (new octave_java (jobj, jcls));
+      break;
+    }
+
+  return retval;
+}
+
+octave_value
+box_more (JNIEnv* jni_env, jobject jobj, jclass jcls)
+{
+  octave_value retval = box (jni_env, jobj, jcls);
+
+  if (retval.is_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.is_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_real_scalar ())
+    {
+      if (val.is_double_type ())
+        {
+          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
+        {
+          float fval = val.float_scalar_value ();
+          jclass_ref fcls (jni_env, jni_env->FindClass ("java/lang/Float"));
+          jfieldID fid = jni_env->GetStaticFieldID (fcls, "TYPE", "Ljava/lang/Class;");
+          jmethodID mid = jni_env->GetMethodID (fcls, "<init>", "(F)V");
+          jcls = reinterpret_cast<jclass> (jni_env->GetStaticObjectField (fcls, fid));
+          jobj = jni_env->NewObject (fcls, mid, fval);
+        }
+    }
+  else if (val.is_integer_type () && val.is_scalar_type ())
+    {
+      int32_t ival = val.int32_scalar_value ();
+      jclass_ref icls (jni_env, jni_env->FindClass ("java/lang/Integer"));
+      jfieldID fid = jni_env->GetStaticFieldID (icls, "TYPE", "Ljava/lang/Class;");
+      jmethodID mid = jni_env->GetMethodID (icls, "<init>", "(I)V");
+      jcls = reinterpret_cast<jclass> (jni_env->GetStaticObjectField (icls, fid));
+      jobj = jni_env->NewObject (icls, mid, ival);
+    }
+  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_empty ())
+    {
+      jobj = 0;
+      jcls = 0;
+      //jcls = jni_env->FindClass ("java/lang/Object");
+    }
+  else if (!Vjava_matrix_autoconversion
+           && ((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_matrix_autoconversion
+           && (val.is_matrix_type () || val.is_range ()) && val.is_real_type ())
+    {
+      jclass_ref mcls (jni_env, find_octave_class (jni_env, "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 (), reinterpret_cast <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 (), reinterpret_cast<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 (), reinterpret_cast<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, "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, "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 ();
+
+          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 (__java_init__, , ,
+  "-*- texinfo -*-\n\
+@deftypefn {Built-in Function} {} java_init ()\n\
+Internal function used @strong{only} when debugging Java interface.\n\
+Function will directly call initialize_java() to create an instance of a JVM.\n\
+@end deftypefn")
+{
+  octave_value retval;
+
+  retval = 0;
+  initialize_java ();
+  if (! error_state)
+    retval = 1;
+
+  return retval;
+}
+
+DEFUN (__java_exit__, , ,
+  "-*- texinfo -*-\n\
+@deftypefn {Built-in Function} {} java_exit ()\n\
+Internal function used @strong{only} when debugging Java interface.\n\
+Function will directly call terminate_jvm() to destroy the current JVM\n\
+instance.\n\
+@end deftypefn")
+{
+  octave_value retval;
+
+  terminate_jvm ();
+
+  return retval;
+}
+
+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 *, 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);
+
+int octave_java::t_id (-1);
+
+const std::string octave_java::t_name ("octave_java");
+
+void
+octave_java::register_type (void)
+{
+  t_id = octave_value_typeinfo::register_type
+    (octave_java::t_name, "<unknown>", octave_value (new 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 (reinterpret_cast<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(1) = octave_value (this);
+          ovl(0) = (idx.front ())(0);
+          std::list<octave_value_list>::const_iterator it = idx.begin ();
+          ovl.append (*++it);
+          retval = feval (std::string ("javaMethod"), 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_javaMethod (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, "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_javaMethod (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, "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_javaObject (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, "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 = octave_value (new octave_java (resObj, 0));
+          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, "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, "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, "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, "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;
+}
+
+#endif  // endif on HAVE_JAVA
+
+// DEFUN blocks below must be outside of HAVE_JAVA block so that
+// documentation strings are always available, even when functions are not.
+
+DEFUN (javaObject, args, ,
+  "-*- texinfo -*-\n\
+@deftypefn  {Built-in Function} {@var{jobj} =} javaObject (@var{classname})\n\
+@deftypefnx {Built-in Function} {@var{jobj} =} javaObject (@var{classname}, @var{arg1}, @dots{})\n\
+Create a Java object of class @var{classsname}, by calling the class\n\
+constructor with the arguments @var{arg1}, @dots{}\n\
+\n\
+The first example below creates an uninitialized object,\n\
+while the second example supplies an initial argument to the constructor.\n\
+\n\
+@example\n\
+@group\n\
+x = javaObject (\"java.lang.StringBuffer\")\n\
+x = javaObject (\"java.lang.StringBuffer\", \"Initial string\")\n\
+@end group\n\
+@end example\n\
+\n\
+@seealso{javaMethod, javaArray}\n\
+@end deftypefn")
+{
+#ifdef HAVE_JAVA
+  octave_value retval;
+
+  initialize_java ();
+
+  if (! error_state)
+    {
+      JNIEnv *current_env = octave_java::thread_jni_env ();
+
+      if (args.length () > 0)
+        {
+          std::string classname = 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_javaObject (current_env, classname, tmp);
+            }
+          else
+            error ("javaObject: CLASSNAME must be a string");
+        }
+      else
+        print_usage ();
+    }
+
+  return retval;
+#else
+  error ("javaObject: Octave was not compiled with Java interface");
+  return octave_value ();
+#endif
+}
+
+/*
+%!testif HAVE_JAVA
+%% The tests below merely check if javaObject works at all. Whether it works
+%% properly, i.e. creates the right values, is a matter of Java itself
+%% Create a Short and check if it really is a short, i.e. whether it overflows
+%! assert (javaObject ("java.lang.Short", 40000).doubleValue < 0);
+*/
+
+DEFUN (javaMethod, args, ,
+  "-*- texinfo -*-\n\
+@deftypefn  {Built-in Function} {@var{ret} =} javaMethod (@var{methodname}, @var{obj})\n\
+@deftypefnx {Built-in Function} {@var{ret} =} javaMethod (@var{methodname}, @var{obj}, @var{arg1}, @dots{})\n\
+Invoke the method @var{methodname} on the Java object @var{obj} with the\n\
+arguments @var{arg1}, @dots{}  For static methods, @var{obj} can be a string\n\
+representing the fully qualified name of the corresponding class.  The\n\
+function returns the result of the method invocation.\n\
+\n\
+When @var{obj} is a regular Java object, structure-like indexing can be\n\
+used as a shortcut syntax.  For instance, the two following statements are\n\
+equivalent\n\
+\n\
+@example\n\
+@group\n\
+  ret = javaMethod (\"method1\", x, 1.0, \"a string\")\n\
+  ret = x.method1 (1.0, \"a string\")\n\
+@end group\n\
+@end example\n\
+\n\
+@seealso{methods, javaObject}\n\
+@end deftypefn")
+{
+#ifdef HAVE_JAVA
+  octave_value retval;
+
+  initialize_java ();
+
+  if (! error_state)
+    {
+      JNIEnv *current_env = octave_java::thread_jni_env ();
+
+      if (args.length () > 1)
+        {
+          std::string methodname = args(0).string_value ();
+          if (! error_state)
+            {
+              octave_value_list tmp;
+              for (int i=2; i<args.length (); i++)
+                tmp(i-2) = args(i);
+
+              if (args(1).is_java ())
+                {
+                  octave_java *jobj = TO_JAVA (args(1));
+                  retval = jobj->do_javaMethod (current_env, methodname, tmp);
+                }
+              else if (args(1).is_string ())
+                {
+                  std::string cls = args(1).string_value ();
+                  retval = octave_java::do_javaMethod (current_env, cls, methodname, tmp);
+                }
+              else
+                error ("javaMethod: OBJ must be a Java object or a string");
+            }
+          else
+            error ("javaMethod: METHODNAME must be a string");
+        }
+      else
+        print_usage ();
+    }
+
+  return retval;
+#else
+  error ("javaMethod: Octave was not compiled with Java interface");
+  return octave_value ();
+#endif
+}
+
+/*
+%!testif HAVE_JAVA
+%% Check for valid first two Java version numbers
+%! jver = strsplit (javaMethod ('getProperty', 'java.lang.System', 'java.version'), '.');
+%! assert (isfinite (str2double (jver{1})) && isfinite (str2double (jver{2})));
+*/
+
+DEFUN (__java_get__, args, ,
+    "-*- texinfo -*-\n\
+@deftypefn {Built-in 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, structure-like indexing can be\n\
+used as a shortcut syntax.  For instance, the two following statements are\n\
+equivalent\n\
+\n\
+@example\n\
+@group\n\
+  __java_get__ (x, \"field1\")\n\
+  x.field1\n\
+@end group\n\
+@end example\n\
+\n\
+@seealso{__java_set__, javaMethod, javaObject}\n\
+@end deftypefn")
+{
+#ifdef HAVE_JAVA
+  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).is_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__: OBJ must be a Java object or a string");
+            }
+          else
+            error ("__java_get__: NAME must be a string");
+        }
+      else
+        print_usage ();
+    }
+
+  return retval;
+#else
+  error ("__java_get__: Octave was not compiled with Java interface");
+  return octave_value ();
+#endif
+}
+
+DEFUN (__java_set__, args, ,
+    "-*- texinfo -*-\n\
+@deftypefn {Built-in 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\n\
+@var{val}.  For static fields, @var{obj} can be a string representing the\n\
+fully qualified named of the corresponding Java class.\n\
+\n\
+When @var{obj} is a regular Java object, structure-like indexing can be\n\
+used as a shortcut syntax.  For instance, the two following statements are\n\
+equivalent\n\
+\n\
+@example\n\
+@group\n\
+  __java_set__ (x, \"field1\", val)\n\
+  x.field1 = val\n\
+@end group\n\
+@end example\n\
+\n\
+@seealso{__java_get__, javaMethod, javaObject}\n\
+@end deftypefn")
+{
+#ifdef HAVE_JAVA
+  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).is_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__: OBJ must be a Java object or a string");
+            }
+          else
+            error ("__java_set__: NAME must be a string");
+        }
+      else
+        print_usage ();
+    }
+
+  return retval;
+#else
+  error ("__java_set__: Octave was not compiled with Java interface");
+  return octave_value ();
+#endif
+}
+
+DEFUN (java2mat, args, ,
+  "-*- texinfo -*-\n\
+@deftypefn {Built-in Function} {} java2mat (@var{javaobj})\n\
+Undocumented internal function.\n\
+@end deftypefn")
+{
+#ifdef HAVE_JAVA
+  octave_value_list retval;
+
+  initialize_java ();
+
+  if (! error_state)
+    {
+      JNIEnv *current_env = octave_java::thread_jni_env ();
+
+      if (args.length () == 1)
+        {
+          if (args(0).is_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;
+#else
+  error ("java2mat: Octave was not compiled with Java interface");
+  return octave_value ();
+#endif
+}
+
+DEFUN (java_matrix_autoconversion, args, nargout,
+  "-*- texinfo -*-\n\
+@deftypefn  {Built-in Function} {@var{val} =} java_matrix_autoconversion ()\n\
+@deftypefnx {Built-in Function} {@var{old_val} =} java_matrix_autoconversion (@var{new_val})\n\
+@deftypefnx {Built-in Function} {} java_matrix_autoconversion (@var{new_val}, \"local\")\n\
+Query or set the internal variable that controls whether Java arrays are\n\
+automatically converted to Octave matrices.  The default value is false.\n\
+\n\
+When called from inside a function with the \"local\" option, the variable is\n\
+changed locally for the function and any subroutines it calls.  The original\n\
+variable value is restored when exiting the function.\n\
+@seealso{java_unsigned_autoconversion, debug_java}\n\
+@end deftypefn")
+{
+#ifdef HAVE_JAVA
+  return SET_INTERNAL_VARIABLE (java_matrix_autoconversion);
+#else
+  error ("java_matrix_autoconversion: Octave was not compiled with Java interface");
+  return octave_value ();
+#endif
+}
+
+DEFUN (java_unsigned_autoconversion, args, nargout,
+  "-*- texinfo -*-\n\
+@deftypefn  {Built-in Function} {@var{val} =} java_unsigned_autoconversion ()\n\
+@deftypefnx {Built-in Function} {@var{old_val} =} java_unsigned_autoconversion (@var{new_val})\n\
+@deftypefnx {Built-in Function} {} java_unsigned_autoconversion (@var{new_val}, \"local\")\n\
+Query or set the internal variable that controls how integer classes are\n\
+converted when @code{java_matrix_autoconversion} is enabled.  When enabled,\n\
+Java arrays of class Byte or Integer are converted to matrices of class\n\
+uint8 or uint32 respectively.  The default value is true.\n\
+\n\
+When called from inside a function with the \"local\" option, the variable is\n\
+changed locally for the function and any subroutines it calls.  The original\n\
+variable value is restored when exiting the function.\n\
+@seealso{java_matrix_autoconversion, debug_java}\n\
+@end deftypefn")
+{
+#ifdef HAVE_JAVA
+  return SET_INTERNAL_VARIABLE (java_unsigned_autoconversion);
+#else
+  error ("java_unsigned_autoconversion: Octave was not compiled with Java interface");
+  return octave_value ();
+#endif
+}
+
+DEFUN (debug_java, args, nargout,
+  "-*- texinfo -*-\n\
+@deftypefn  {Built-in Function} {@var{val} =} debug_java ()\n\
+@deftypefnx {Built-in Function} {@var{old_val} =} debug_java (@var{new_val})\n\
+@deftypefnx {Built-in Function} {} debug_java (@var{new_val}, \"local\")\n\
+Query or set the internal variable that determines whether extra debugging\n\
+information regarding the initialization of the JVM and any Java exceptions\n\
+is printed.\n\
+\n\
+When called from inside a function with the \"local\" option, the variable is\n\
+changed locally for the function and any subroutines it calls.  The original\n\
+variable value is restored when exiting the function.\n\
+@seealso{java_matrix_autoconversion, java_unsigned_autoconversion}\n\
+@end deftypefn")
+{
+#ifdef HAVE_JAVA
+  return SET_INTERNAL_VARIABLE (debug_java);
+#else
+  error ("debug_java: Octave was not compiled with Java interface");
+  return octave_value ();
+#endif
+}
+
+// Outside of #ifdef HAVE_JAVA because it is desirable to be able to
+// test for the presence of a Java object without having Java installed. 
+DEFUN (isjava, args, ,
+  "-*- texinfo -*-\n\
+@deftypefn {Built-in Function} {} isjava (@var{x})\n\
+Return true if @var{x} is a Java object.\n\
+@seealso{class, typeinfo, isa, javaObject}\n\
+@end deftypefn")
+{
+  octave_value retval;
+
+  if (args.length () != 1)
+    print_usage ();
+  else
+    retval = args(0).is_java ();
+
+  return retval;
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libinterp/octave-value/ov-java.h	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,321 @@
+/*
+
+Copyright (C) 2007 Michael Goffioul
+
+This file is part of Octave.
+
+Octave is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by the
+Free Software Foundation; either version 3 of the License, or (at your
+option) any later version.
+
+Octave 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/>.
+
+*/
+
+#if !defined (octave_java_h)
+#define octave_java_h 1
+
+#include <jni.h>
+
+#include <oct-obj.h>
+#include <ov.h>
+
+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 (void) { 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 OCTINTERP_API std::string
+jstring_to_string (JNIEnv* jni_env, jstring s);
+
+extern OCTINTERP_API std::string
+jstring_to_string (JNIEnv* jni_env, jobject obj);
+
+extern OCTINTERP_API octave_value
+box (JNIEnv* jni_env, jobject jobj, jclass jcls = 0);
+
+extern OCTINTERP_API octave_value
+box_more (JNIEnv* jni_env, jobject jobj, jclass jcls = 0);
+
+extern OCTINTERP_API int
+unbox (JNIEnv* jni_env, const octave_value& val, jobject_ref& jobj,
+       jclass_ref& jcls);
+
+extern OCTINTERP_API int
+unbox (JNIEnv* jni_env, const octave_value_list& args,
+       jobjectArray_ref& jobjs, jobjectArray_ref& jclss);
+
+extern OCTINTERP_API bool Vjava_matrix_autoconversion;
+
+extern OCTINTERP_API bool Vjava_unsigned_autoconversion;
+
+extern OCTINTERP_API bool Vdebug_java;
+
+class OCTINTERP_API octave_java : public octave_base_value
+{
+public:
+
+  octave_java (void)
+    : octave_base_value (), java_object (0), java_class (0)
+  { }
+
+  octave_java (const octave_java& jobj)
+    : octave_base_value (jobj), java_object (0), java_class (0)
+  {
+    init (jobj.java_object, jobj.java_class);
+  }
+
+  octave_java (const jobject& obj, jclass cls = 0)
+    : octave_base_value (), java_object (0)
+  {
+    init (obj, cls);
+  }
+
+  ~octave_java (void) { release (); }
+
+  jobject to_java (void) const { return java_object; }
+  jclass to_class (void) const { return java_class; }
+
+  std::string java_class_name (void) const { return java_classname; }
+
+  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 false; }
+
+  bool is_java (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_classname << ">";
+    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_java_string (void) const;
+
+  static JNIEnv* thread_jni_env (void);
+
+  octave_value do_javaMethod (JNIEnv* jni_env, const std::string& name,
+                              const octave_value_list& args);
+
+  octave_value
+  do_javaMethod (const std::string& name, const octave_value_list& args)
+  {
+    return do_javaMethod(thread_jni_env (), name, args);
+  }
+
+  static octave_value
+  do_javaMethod (JNIEnv* jni_env, const std::string& class_name,
+                 const std::string& name, const octave_value_list& args);
+
+  static octave_value
+  do_javaMethod (const std::string& class_name, const std::string& name,
+                 const octave_value_list& args)
+  {
+    return do_javaMethod(thread_jni_env (), class_name, name, args);
+  }
+
+  static octave_value
+  do_javaObject (JNIEnv* jni_env, const std::string& name,
+                 const octave_value_list& args);
+
+  static octave_value
+  do_javaObject (const std::string& name, const octave_value_list& args)
+  {
+    return do_javaObject (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_classname = jstring_to_string (current_env, resObj);
+          }
+      }
+  }
+
+  void release (void)
+  {
+    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:
+
+  jobject java_object;
+
+  jclass java_class;
+
+  std::string java_classname;
+
+  DECLARE_OCTAVE_ALLOCATOR
+
+public:
+  int type_id (void) const { return t_id; }
+  std::string type_name (void) const { return t_name; }
+  std::string class_name (void) const { return java_classname; }
+
+  static int static_type_id (void) { return t_id; }
+  static std::string static_type_name (void) { return t_name; }
+  static std::string static_class_name (void) { return "<unknown>"; }
+  static void register_type (void);
+
+private:
+  static int t_id;
+  static const std::string t_name;
+};
+
+#endif
--- a/libinterp/octave-value/ov-oncleanup.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/octave-value/ov-oncleanup.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -192,7 +192,7 @@
 elements) or returned from a function, @var{action} will be executed after\n\
 clearing the last copy of the object.  Note that if multiple local onCleanup\n\
 variables are created, the order in which they are called is unspecified.\n\
-For similar functionality @xref{The @code{unwind_protect} Statement}.\n\
+For similar functionality @xref{The unwind_protect Statement}.\n\
 @end deftypefn")
 {
   octave_value retval;
--- a/libinterp/octave-value/ov-re-mat.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/octave-value/ov-re-mat.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -906,6 +906,8 @@
       ARRAY_MAPPER (erfcinv, double, ::erfcinv);
       ARRAY_MAPPER (erfc, double, ::erfc);
       ARRAY_MAPPER (erfcx, double, ::erfcx);
+      ARRAY_MAPPER (erfi, double, ::erfi);
+      ARRAY_MAPPER (dawson, double, ::dawson);
       ARRAY_MAPPER (gamma, double, xgamma);
       RC_ARRAY_MAPPER (lgamma, Complex, rc_lgamma);
       ARRAY_MAPPER (cbrt, double, ::cbrt);
--- a/libinterp/octave-value/ov-re-sparse.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/octave-value/ov-re-sparse.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -912,6 +912,9 @@
       ARRAY_MAPPER (erfinv, double, ::erfinv);
       ARRAY_MAPPER (erfcinv, double, ::erfcinv);
       ARRAY_MAPPER (erfc, double, ::erfc);
+      ARRAY_MAPPER (erfcx, double, ::erfcx);
+      ARRAY_MAPPER (erfi, double, ::erfi);
+      ARRAY_MAPPER (dawson, double, ::dawson);
       ARRAY_MAPPER (gamma, double, xgamma);
       ARRAY_MAPPER (lgamma, Complex, rc_lgamma);
       ARRAY_MAPPER (cbrt, double, ::cbrt);
--- a/libinterp/octave-value/ov-scalar.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/octave-value/ov-scalar.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -311,6 +311,8 @@
       SCALAR_MAPPER (erfcinv, ::erfcinv);
       SCALAR_MAPPER (erfc, ::erfc);
       SCALAR_MAPPER (erfcx, ::erfcx);
+      SCALAR_MAPPER (erfi, ::erfi);
+      SCALAR_MAPPER (dawson, ::dawson);
       SCALAR_MAPPER (gamma, xgamma);
       SCALAR_MAPPER (lgamma, rc_lgamma);
       SCALAR_MAPPER (cbrt, ::cbrt);
--- a/libinterp/octave-value/ov-struct.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/octave-value/ov-struct.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -85,7 +85,8 @@
   else if (auto_add)
     retval = (numel () == 0) ? Cell (dim_vector (1, 1)) : Cell (dims ());
   else
-    error ("structure has no member '%s'", nm.c_str ());
+    error_with_id ("Octave:invalid-indexing", 
+                   "structure has no member '%s'", nm.c_str ());
 
   return retval;
 }
@@ -116,6 +117,22 @@
   error ("assignment to structure element failed");
 }
 
+static void
+maybe_warn_invalid_field_name (const std::string& key, const char *who)
+{
+  if (! valid_identifier (key))
+    {
+      if (who)
+        warning_with_id ("Octave:matlab-incompatible",
+                         "%s: invalid structure field name '%s'",
+                         who, key.c_str ());
+      else
+        warning_with_id ("Octave:matlab-incompatible",
+                         "invalid structure field name '%s'",
+                         key.c_str ());
+    }
+}
+
 octave_value_list
 octave_struct::subsref (const std::string& type,
                         const std::list<octave_value_list>& idx,
@@ -305,6 +322,11 @@
 
                 std::string key = key_idx(0).string_value ();
 
+                maybe_warn_invalid_field_name (key, "subsasgn");
+
+                if (error_state)
+                  return retval;
+
                 std::list<octave_value_list> next_idx (idx);
 
                 // We handled two index elements, so subsasgn to
@@ -363,6 +385,11 @@
 
             std::string key = key_idx(0).string_value ();
 
+            maybe_warn_invalid_field_name (key, "subsasgn");
+
+            if (error_state)
+              return retval;
+
             std::list<octave_value_list> next_idx (idx);
 
             next_idx.erase (next_idx.begin ());
@@ -431,6 +458,11 @@
 
                 std::string key = key_idx(0).string_value ();
 
+                maybe_warn_invalid_field_name (key, "subsasgn");
+
+                if (error_state)
+                  return retval;
+
                 if (! error_state)
                   {
                     if (t_rhs.is_cs_list ())
@@ -530,6 +562,11 @@
 
             std::string key = key_idx(0).string_value ();
 
+            maybe_warn_invalid_field_name (key, "subsasgn");
+
+            if (error_state)
+              return retval;
+
             if (t_rhs.is_cs_list ())
               {
                 Cell tmp_cell = Cell (t_rhs.list_value ());
@@ -1093,14 +1130,22 @@
 octave_value
 octave_scalar_struct::dotref (const octave_value_list& idx, bool auto_add)
 {
+  octave_value retval;
+
   assert (idx.length () == 1);
 
   std::string nm = idx(0).string_value ();
 
-  octave_value retval = map.getfield (nm);
+  maybe_warn_invalid_field_name (nm, "subsref");
+
+  if (error_state)
+    return retval;
+
+  retval = map.getfield (nm);
 
   if (! auto_add && retval.is_undefined ())
-    error ("structure has no member '%s'", nm.c_str ());
+    error_with_id ("Octave:invalid-indexing",
+                   "structure has no member '%s'", nm.c_str ());
 
   return retval;
 }
@@ -1218,6 +1263,11 @@
 
       std::string key = key_idx(0).string_value ();
 
+      maybe_warn_invalid_field_name (key, "subsasgn");
+
+      if (error_state)
+        return retval;
+
       if (n > 1)
         {
           std::list<octave_value_list> next_idx (idx);
@@ -1699,9 +1749,12 @@
 
 DEFUN (struct, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Built-in Function} {} struct (\"field\", @var{value}, \"field\", @var{value}, @dots{})\n\
+@deftypefn {Built-in Function} {} struct (@var{field1}, @var{value1}, @var{field2}, @var{value2}, @dots{})\n\
 \n\
-Create a structure and initialize its value.\n\
+Create a scalar or array structure and initialize its values. The\n\
+@var{field1}, @var{field2}, @dots{} variables are strings giving the\n\
+names of the fields and the @var{value1}, @var{value2}, @dots{}\n\
+variables can be any type.\n\
 \n\
 If the values are cell arrays, create a structure array and initialize\n\
 its values.  The dimensions of each cell array of values must match.\n\
@@ -1710,6 +1763,41 @@
 array with the specified field names.\n\
 \n\
 If the argument is an object, return the underlying struct.\n\
+\n\
+Observe that the syntax is optimized for struct @strong{arrays}. Consider the\n\
+following examples:\n\
+\n\
+@example\n\
+@group\n\
+struct (\"foo\", 1)\n\
+  @result{} scalar structure containing the fields:\n\
+    foo =  1\n\
+\n\
+struct (\"foo\", @{@})\n\
+  @result{} 0x0 struct array containing the fields:\n\
+    foo\n\
+\n\
+struct (\"foo\", @{ @{@} @})\n\
+  @result{} scalar structure containing the fields:\n\
+    foo = @{@}(0x0)\n\
+\n\
+struct (\"foo\", @{1, 2, 3@})\n\
+  @result{} 1x3 struct array containing the fields:\n\
+    foo\n\
+\n\
+@end group\n\
+@end example\n\
+\n\
+@noindent\n\
+The first case is an ordinary scalar struct, one field, one value. The\n\
+second produces an empty struct array with one field and no values, since\n\
+s being passed an empty cell array of struct array values. When the value is\n\
+a cell array containing a single entry, this becomes a scalar struct with\n\
+that single entry as the value of the field. That single entry happens\n\
+to be an empty cell array.\n\
+\n\
+Finally, if the value is a non-scalar cell array, then @code{struct}\n\
+produces a struct @strong{array}.\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -1805,11 +1893,10 @@
       if (error_state)
         return retval;
 
-      if (! valid_identifier (key))
-        {
-          error ("struct: invalid structure field name '%s'", key.c_str ());
-          return retval;
-        }
+      maybe_warn_invalid_field_name (key, "struct");
+
+      if (error_state)
+        return retval;
 
       // Value may be v, { v }, or { v1, v2, ... }
       // In the first two cases, we need to create a cell array of
@@ -1876,49 +1963,33 @@
   return retval;
 }
 
-DEFUN (fieldnames, args, ,
+DEFUN (__fieldnames__, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Built-in Function} {} fieldnames (@var{struct})\n\
-Return a cell array of strings naming the elements of the structure\n\
-@var{struct}.  It is an error to call @code{fieldnames} with an\n\
-argument that is not a structure.\n\
+@deftypefn  {Built-in Function} {} __fieldnames__ (@var{struct})\n\
+@deftypefnx {Built-in Function} {} __fieldnames__ (@var{obj})\n\
+Internal function.\n\
+\n\
+Implements @code{fieldnames()} for structures and Octave objects.\n\
+@seealso{fieldnames}\n\
 @end deftypefn")
 {
   octave_value retval;
 
-  int nargin = args.length ();
-
-  if (nargin == 1)
-    {
-      octave_value arg = args(0);
-
-      if (arg.is_map () || arg.is_object ())
-        {
-          octave_map m = arg.map_value ();
-
-          string_vector keys = m.fieldnames ();
-
-          if (keys.length () == 0)
-            retval = Cell (0, 1);
-          else
-            retval = Cell (keys);
-        }
-      else
-        gripe_wrong_type_arg ("fieldnames", args(0));
-    }
+  // Input validation has already been done in fieldnames.m.
+  octave_value arg = args(0);
+
+  octave_map m = arg.map_value ();
+
+  string_vector keys = m.fieldnames ();
+
+  if (keys.length () == 0)
+    retval = Cell (0, 1);
   else
-    print_usage ();
+    retval = Cell (keys);
 
   return retval;
 }
 
-/*
-## test preservation of fieldname order
-%!test
-%! x(3).d=1;  x(2).a=2; x(1).b=3;  x(2).c=3;
-%! assert (fieldnames (x), {"d"; "a"; "b"; "c"});
-*/
-
 DEFUN (isfield, args, ,
   "-*- texinfo -*-\n\
 @deftypefn {Built-in Function} {} isfield (@var{x}, @var{name})\n\
--- a/libinterp/octave-value/ov-typeinfo.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/octave-value/ov-typeinfo.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -703,5 +703,14 @@
 %!assert (typeinfo (""), "null_string")
 %!assert (typeinfo (''), "null_sq_string")
 
+%!test
+%! cvar = onCleanup (@() "");
+%! assert (typeinfo (cvar), "onCleanup");
+
+%!testif HAVE_JAVA
+%! x = javaObject ("java.lang.StringBuffer");
+%! assert (typeinfo (x), "octave_java");
+
+## Test input validation
 %!error typeinfo ("foo", 1)
 */
--- a/libinterp/octave-value/ov-usr-fcn.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/octave-value/ov-usr-fcn.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -382,7 +382,7 @@
     return retval;
 
 #ifdef HAVE_LLVM
-  if (Venable_jit_compiler && is_special_expr ()
+  if (is_special_expr ()
       && tree_jit::execute (*this, args, retval))
     return retval;
 #endif
--- a/libinterp/octave-value/ov.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/octave-value/ov.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -77,6 +77,9 @@
 #include "ov-typeinfo.h"
 #include "ov-null-mat.h"
 #include "ov-lazy-idx.h"
+#ifdef HAVE_JAVA
+#include "ov-java.h"
+#endif
 
 #include "defun.h"
 #include "error.h"
@@ -2755,6 +2758,9 @@
   octave_null_sq_str::register_type ();
   octave_lazy_index::register_type ();
   octave_oncleanup::register_type ();
+#ifdef HAVE_JAVA
+  octave_java::register_type ();
+#endif
 }
 
 DEFUN (sizeof, args, ,
--- a/libinterp/octave-value/ov.h	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/octave-value/ov.h	Sun Dec 23 13:00:02 2012 -0500
@@ -563,6 +563,9 @@
   bool is_object (void) const
     { return rep->is_object (); }
 
+  bool is_java (void) const
+    { return rep->is_java (); }
+
   bool is_cs_list (void) const
     { return rep->is_cs_list (); }
 
@@ -1126,6 +1129,8 @@
   MAPPER_FORWARD (erfcinv)
   MAPPER_FORWARD (erfc)
   MAPPER_FORWARD (erfcx)
+  MAPPER_FORWARD (erfi)
+  MAPPER_FORWARD (dawson)
   MAPPER_FORWARD (exp)
   MAPPER_FORWARD (expm1)
   MAPPER_FORWARD (finite)
--- a/libinterp/octave.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/octave.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -172,6 +172,9 @@
 // If TRUE, don't exit after evaluating code given by --eval option.
 static bool persist = false;
 
+// If TRUE, the GUI should be started.
+static bool start_gui = false;
+
 // Long options.  See the comments in getopt.h for the meanings of the
 // fields in this structure.
 #define BUILT_IN_DOCSTRINGS_FILE_OPTION 1
@@ -1031,11 +1034,8 @@
   return 0;
 }
 
-// Return int instead of bool because this function is declared
-// extern "C".
-
-int
-octave_starting_gui (void)
+static bool
+check_starting_gui (void)
 {
   if (no_window_system || ! display_info::display_available ())
     return false;
@@ -1070,6 +1070,37 @@
   return true;
 }
 
+// Return int instead of bool because this function is declared
+// extern "C".
+
+int
+octave_starting_gui (void)
+{
+  start_gui = check_starting_gui ();
+  return start_gui;
+}
+
+DEFUN (isguirunning, args, ,
+  "-*- texinfo -*-\n\
+@deftypefn {Built-in Function} {} isguirunning ()\n\
+Return true if Octave is running in GUI mode and false otherwise.\n\
+@end deftypefn")
+{
+  octave_value retval;
+
+  if (args.length () == 0)
+    retval = start_gui;
+  else
+    print_usage ();
+
+  return retval;
+}
+
+/*
+%!assert (islogical (isguirunning ()))
+%!error isguirunning (1)
+*/
+
 DEFUN (argv, args, ,
   "-*- texinfo -*-\n\
 @deftypefn {Built-in Function} {} argv ()\n\
--- a/libinterp/parse-tree/pt-assign.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/parse-tree/pt-assign.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -38,6 +38,7 @@
 #include "pt-arg-list.h"
 #include "pt-bp.h"
 #include "pt-assign.h"
+#include "pt-eval.h"
 #include "pt-walk.h"
 #include "utils.h"
 #include "variables.h"
@@ -247,7 +248,8 @@
                       else
                         retval = ult.value ();
 
-                      if (print_result ())
+                      if (print_result ()
+                          && tree_evaluator::statement_printing_enabled ())
                         {
                           // We clear any index here so that we can
                           // get the new value of the referenced
@@ -459,7 +461,8 @@
 
           if (error_state)
             break;
-          else if (print_result ())
+          else if (print_result ()
+                   && tree_evaluator::statement_printing_enabled ())
             {
               // We clear any index here so that we can get
               // the new value of the referenced object below,
--- a/libinterp/parse-tree/pt-eval.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/parse-tree/pt-eval.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -132,6 +132,13 @@
   dbstep_flag = 0;
 }
 
+bool
+tree_evaluator::statement_printing_enabled (void)
+{
+  return ! (Vsilent_functions && (statement_context == function
+                                  || statement_context == script));
+}
+
 static inline void
 do_global_init (tree_decl_elt& elt)
 {
@@ -307,7 +314,7 @@
   octave_value rhs = expr->rvalue1 ();
 
 #if HAVE_LLVM
-  if (Venable_jit_compiler && tree_jit::execute (cmd, rhs))
+  if (tree_jit::execute (cmd, rhs))
     return;
 #endif
 
@@ -723,10 +730,6 @@
               if (debug_mode)
                 do_breakpoint (expr->is_breakpoint ());
 
-              if ((statement_context == function || statement_context == script)
-                  && Vsilent_functions)
-                expr->set_print_flag (false);
-
               // FIXME -- maybe all of this should be packaged in
               // one virtual function that returns a flag saying whether
               // or not the expression will take care of binding ans and
@@ -750,7 +753,8 @@
               octave_value tmp_result = expr->rvalue1 (0);
 
               if (do_bind_ans && ! (error_state || tmp_result.is_undefined ()))
-                bind_ans (tmp_result, expr->print_result ());
+                bind_ans (tmp_result, expr->print_result ()
+                          && statement_printing_enabled ());
 
               //              if (tmp_result.is_defined ())
               //                result_values(0) = tmp_result;
@@ -1050,7 +1054,7 @@
     return;
 
 #if HAVE_LLVM
-  if (Venable_jit_compiler && tree_jit::execute (cmd))
+  if (tree_jit::execute (cmd))
     return;
 #endif
 
@@ -1142,22 +1146,6 @@
 {
   bool break_on_this_statement = false;
 
-  // Don't decrement break flag unless we are in the same frame as we
-  // were when we saw the "dbstep N" command.
-
-  if (dbstep_flag > 1)
-    {
-      if (octave_call_stack::current_frame () == current_frame)
-        {
-          // Don't allow dbstep N to step past end of current frame.
-
-          if (is_end_of_fcn_or_script)
-            dbstep_flag = 1;
-          else
-            dbstep_flag--;
-        }
-    }
-
   if (octave_debug_on_interrupt_state)
     {
       break_on_this_statement = true;
@@ -1174,17 +1162,29 @@
 
       current_frame = octave_call_stack::current_frame ();
     }
-  else if (dbstep_flag == 1)
+  else if (dbstep_flag > 0)
     {
       if (octave_call_stack::current_frame () == current_frame)
         {
-          // We get here if we are doing a "dbstep" or a "dbstep N"
-          // and the count has reached 1 and we are in the current
-          // debugging frame.
+          if (dbstep_flag == 1 || is_end_of_fcn_or_script)
+            {
+              // We get here if we are doing a "dbstep" or a "dbstep N" and the
+              // count has reached 1 so that we must stop and return to debug
+              // prompt.  Alternatively, "dbstep N" has been used but the end
+              // of the frame has been reached so we stop at the last line and
+              // return to prompt.
+
+              break_on_this_statement = true;
 
-          break_on_this_statement = true;
+              dbstep_flag = 0;
+            }
+          else
+            {
+              // Executing "dbstep N".  Decrease N by one and continue.
 
-          dbstep_flag = 0;
+              dbstep_flag--;
+            }
+
         }
     }
   else if (dbstep_flag == -1)
--- a/libinterp/parse-tree/pt-eval.h	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/parse-tree/pt-eval.h	Sun Dec 23 13:00:02 2012 -0500
@@ -138,6 +138,8 @@
 
   static void reset_debug_state (void);
 
+  static bool statement_printing_enabled (void);
+
   // If > 0, stop executing at the (N-1)th stopping point, counting
   //         from the the current execution point in the current frame.
   //
--- a/libinterp/parse-tree/pt-exp.h	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/parse-tree/pt-exp.h	Sun Dec 23 13:00:02 2012 -0500
@@ -87,6 +87,9 @@
 
   bool is_postfix_indexed (void) const { return postfix_indexed; }
 
+  // Check if the result of the expression should be printed.
+  // Should normally be used in conjunction with
+  // tree_evaluator::statement_printing_enabled.
   bool print_result (void) const { return print_flag; }
 
   virtual std::string oper (void) const { return "<unknown>"; }
--- a/libinterp/parse-tree/pt-id.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/parse-tree/pt-id.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -30,6 +30,7 @@
 #include "pager.h"
 #include "pt-bp.h"
 #include "pt-const.h"
+#include "pt-eval.h"
 #include "pt-id.h"
 #include "pt-walk.h"
 #include "symtab.h"
@@ -88,7 +89,8 @@
         }
       else
         {
-          if (print_result () && nargout == 0)
+          if (print_result () && nargout == 0
+              && tree_evaluator::statement_printing_enabled ())
             val.print_with_name (octave_stdout, name ());
 
           retval = val;
--- a/libinterp/parse-tree/pt-idx.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/libinterp/parse-tree/pt-idx.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -216,12 +216,7 @@
           octave_value t = df->rvalue1 ();
 
           if (! error_state)
-            {
-              fn = t.string_value ();
-
-              if (! valid_identifier (fn))
-                ::error ("invalid structure field name '%s'", fn.c_str ());
-            }
+            fn = t.string_value ();
         }
       else
         panic_impossible ();
--- a/liboctave/Makefile.am	Thu Nov 01 15:01:20 2012 -0400
+++ b/liboctave/Makefile.am	Sun Dec 23 13:00:02 2012 -0500
@@ -85,7 +85,7 @@
 ## It has no source code itself.
 liboctave_la_SOURCES = 
 
-liboctave_la_CPPFLAGS = @OCTAVE_DLL_DEFS@ $(AM_CPPFLAGS)
+liboctave_la_CPPFLAGS = @OCTAVE_DLL_DEFS@ @CRUFT_DLL_DEFS@ $(AM_CPPFLAGS)
 
 include link-deps.mk
 
@@ -113,6 +113,7 @@
 liboctave_la_LDFLAGS = \
   -version-info $(liboctave_version_info) \
   $(NO_UNDEFINED_LDFLAG) \
+  @XTRA_CRUFT_SH_LDFLAGS@ \
   -bindir $(bindir) \
   $(LIBOCTAVE_LINK_OPTS)
 
--- a/liboctave/array/Sparse.h	Thu Nov 01 15:01:20 2012 -0400
+++ b/liboctave/array/Sparse.h	Sun Dec 23 13:00:02 2012 -0500
@@ -87,12 +87,12 @@
       }
 
     SparseRep (octave_idx_type nr, octave_idx_type nc, octave_idx_type nz = 0)
-      : d (new T [nz]), r (new octave_idx_type [nz]),
+      : d (nz > 0 ? new T [nz] : 0),
+      r (nz > 0 ? new octave_idx_type [nz] : 0),
       c (new octave_idx_type [nc+1]), nzmx (nz), nrows (nr),
       ncols (nc), count (1)
       {
-        c[nc] = nz;
-        for (octave_idx_type i = 0; i < nc; i++)
+        for (octave_idx_type i = 0; i < nc + 1; i++)
           c[i] = 0;
       }
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/liboctave/cruft/Faddeeva/Faddeeva.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,2515 @@
+//  -*- mode:c++; tab-width:2; indent-tabs-mode:nil;  -*-
+
+/* Copyright (c) 2012 Massachusetts Institute of Technology
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
+ */
+
+/* (Note that this file can be compiled with either C++, in which
+    case it uses C++ std::complex<double>, or C, in which case it
+    uses C99 double complex.) */
+
+/* Available at: http://ab-initio.mit.edu/Faddeeva
+
+   Computes various error functions (erf, erfc, erfi, erfcx), 
+   including the Dawson integral, in the complex plane, based
+   on algorithms for the computation of the Faddeeva function 
+              w(z) = exp(-z^2) * erfc(-i*z).
+   Given w(z), the error functions are mostly straightforward
+   to compute, except for certain regions where we have to
+   switch to Taylor expansions to avoid cancellation errors
+   [e.g. near the origin for erf(z)].
+
+   To compute the Faddeeva function, we use a combination of two
+   algorithms:
+
+   For sufficiently large |z|, we use a continued-fraction expansion
+   for w(z) similar to those described in:
+
+      Walter Gautschi, "Efficient computation of the complex error
+      function," SIAM J. Numer. Anal. 7(1), pp. 187-198 (1970)
+
+      G. P. M. Poppe and C. M. J. Wijers, "More efficient computation
+      of the complex error function," ACM Trans. Math. Soft. 16(1),
+      pp. 38-46 (1990).
+
+   Unlike those papers, however, we switch to a completely different
+   algorithm for smaller |z|:
+
+      Mofreh R. Zaghloul and Ahmed N. Ali, "Algorithm 916: Computing the
+      Faddeyeva and Voigt Functions," ACM Trans. Math. Soft. 38(2), 15
+      (2011).
+
+   (I initially used this algorithm for all z, but it turned out to be
+    significantly slower than the continued-fraction expansion for
+    larger |z|.  On the other hand, it is competitive for smaller |z|, 
+    and is significantly more accurate than the Poppe & Wijers code
+    in some regions, e.g. in the vicinity of z=1+1i.)
+
+   Note that this is an INDEPENDENT RE-IMPLEMENTATION of these algorithms,
+   based on the description in the papers ONLY.  In particular, I did
+   not refer to the authors' Fortran or Matlab implementations, respectively,
+   (which are under restrictive ACM copyright terms and therefore unusable
+    in free/open-source software).
+
+   Steven G. Johnson, Massachusetts Institute of Technology
+   http://math.mit.edu/~stevenj
+   October 2012.
+
+    -- Note that Algorithm 916 assumes that the erfc(x) function, 
+       or rather the scaled function erfcx(x) = exp(x*x)*erfc(x),
+       is supplied for REAL arguments x.   I originally used an
+       erfcx routine derived from DERFC in SLATEC, but I have
+       since replaced it with a much faster routine written by
+       me which uses a combination of continued-fraction expansions
+       and a lookup table of Chebyshev polynomials.  For speed,
+       I implemented a similar algorithm for Im[w(x)] of real x,
+       since this comes up frequently in the other error functions.
+
+   A small test program is included the end, which checks
+   the w(z) etc. results against several known values.  To compile
+   the test function, compile with -DTEST_FADDEEVA (that is,
+   #define TEST_FADDEEVA).
+
+   If HAVE_CONFIG_H is #defined (e.g. by compiling with -DHAVE_CONFIG_H),
+   then we #include "config.h", which is assumed to be a GNU autoconf-style
+   header defining HAVE_* macros to indicate the presence of features. In
+   particular, if HAVE_ISNAN and HAVE_ISINF are #defined, we use those
+   functions in math.h instead of defining our own, and if HAVE_ERF and/or
+   HAVE_ERFC are defined we use those functions from <cmath> for erf and
+   erfc of real arguments, respectively, instead of defining our own.
+
+   REVISION HISTORY:
+       4 October 2012: Initial public release (SGJ)
+       5 October 2012: Revised (SGJ) to fix spelling error,
+                       start summation for large x at round(x/a) (> 1)
+                       rather than ceil(x/a) as in the original
+                       paper, which should slightly improve performance
+                       (and, apparently, slightly improves accuracy)
+      19 October 2012: Revised (SGJ) to fix bugs for large x, large -y,
+                       and 15<x<26. Performance improvements. Prototype
+                       now supplies default value for relerr.
+      24 October 2012: Switch to continued-fraction expansion for
+                       sufficiently large z, for performance reasons.
+                       Also, avoid spurious overflow for |z| > 1e154.
+                       Set relerr argument to min(relerr,0.1).
+      27 October 2012: Enhance accuracy in Re[w(z)] taken by itself,
+                       by switching to Alg. 916 in a region near
+                       the real-z axis where continued fractions
+                       have poor relative accuracy in Re[w(z)].  Thanks
+                       to M. Zaghloul for the tip.
+      29 October 2012: Replace SLATEC-derived erfcx routine with
+                       completely rewritten code by me, using a very
+                       different algorithm which is much faster.
+      30 October 2012: Implemented special-case code for real z
+                       (where real part is exp(-x^2) and imag part is
+                        Dawson integral), using algorithm similar to erfx.
+                       Export ImFaddeeva_w function to make Dawson's
+                       integral directly accessible.
+      3 November 2012: Provide implementations of erf, erfc, erfcx,
+                       and Dawson functions in Faddeeva:: namespace,
+                       in addition to Faddeeva::w.  Provide header
+                       file Faddeeva.hh.
+      4 November 2012: Slightly faster erf for real arguments.
+                       Updated MATLAB and Octave plugins.
+     27 November 2012: Support compilation with either C++ or
+                       plain C (using C99 complex numbers).
+                       For real x, use standard-library erf(x)
+                       and erfc(x) if available (for C99 or C++11).
+                       #include "config.h" if HAVE_CONFIG_H is #defined.
+     15 December 2012: Portability fixes (copysign, Inf/NaN creation),
+                       use CMPLX/__builtin_complex if available in C,
+                       slight accuracy improvements to erf and dawson
+                       functions near the origin.  Use gnulib functions
+                       if GNULIB_NAMESPACE is defined.
+*/
+
+/////////////////////////////////////////////////////////////////////////
+/* If this file is compiled as a part of a larger project,
+   support using an autoconf-style config.h header file
+   (with various "HAVE_*" #defines to indicate features)
+   if HAVE_CONFIG_H is #defined (in GNU autotools style). */
+
+#ifdef HAVE_CONFIG_H
+#  include "config.h"
+#endif
+
+/////////////////////////////////////////////////////////////////////////
+// macros to allow us to use either C++ or C (with C99 features)
+
+#ifdef __cplusplus
+
+#  include "Faddeeva.hh"
+
+#  include <cfloat>
+#  include <cmath>
+#  include <limits>
+using namespace std;
+
+// use std::numeric_limits, since 1./0. and 0./0. fail with some compilers (MS)
+#  define Inf numeric_limits<double>::infinity()
+#  define NaN numeric_limits<double>::quiet_NaN()
+
+typedef complex<double> cmplx;
+
+// Use C-like complex syntax, since the C syntax is more restrictive
+#  define cexp(z) exp(z)
+#  define creal(z) real(z)
+#  define cimag(z) imag(z)
+#  define cpolar(r,t) polar(r,t)
+
+#  define C(a,b) cmplx(a,b)
+
+#  define FADDEEVA(name) Faddeeva::name
+#  define FADDEEVA_RE(name) Faddeeva::name
+
+// isnan/isinf were introduced in C++11
+#  if (__cplusplus < 201103L) && (!defined(HAVE_ISNAN) || !defined(HAVE_ISINF))
+static inline bool my_isnan(double x) { return x != x; }
+#    define isnan my_isnan
+static inline bool my_isinf(double x) { return 1/x == 0.; }
+#    define isinf my_isinf
+#  elif (__cplusplus >= 201103L)
+// g++ gets confused between the C and C++ isnan/isinf functions
+#    define isnan std::isnan
+#    define isinf std::isinf
+#  endif
+
+// copysign was introduced in C++11 (and is also in POSIX and C99)
+#  if defined(_WIN32) || defined(__WIN32__)
+#    define copysign _copysign // of course MS had to be different
+#  elif defined(GNULIB_NAMESPACE) // we are using using gnulib <cmath>
+#    define copysign GNULIB_NAMESPACE::copysign
+#  elif (__cplusplus < 201103L) && !defined(HAVE_COPYSIGN) && !defined(__linux__) && !(defined(__APPLE__) && defined(__MACH__)) && !defined(_AIX)
+static inline double my_copysign(double x, double y) { return y<0 ? -x : x; }
+#    define copysign my_copysign
+#  endif
+
+// If we are using the gnulib <cmath> (e.g. in the GNU Octave sources),
+// gnulib generates a link warning if we use ::floor instead of gnulib::floor.
+// This warning is completely innocuous because the only difference between
+// gnulib::floor and the system ::floor (and only on ancient OSF systems)
+// has to do with floor(-0), which doesn't occur in the usage below, but
+// the Octave developers prefer that we silence the warning.
+#  ifdef GNULIB_NAMESPACE
+#    define floor GNULIB_NAMESPACE::floor
+#  endif
+
+#else // !__cplusplus, i.e. pure C (requires C99 features)
+
+#  include "Faddeeva.h"
+
+#  define _GNU_SOURCE // enable GNU libc NAN extension if possible
+
+#  include <float.h>
+#  include <math.h>
+
+typedef double complex cmplx;
+
+#  define FADDEEVA(name) Faddeeva_ ## name
+#  define FADDEEVA_RE(name) Faddeeva_ ## name ## _re
+
+/* Constructing complex numbers like 0+i*NaN is problematic in C99
+   without the C11 CMPLX macro, because 0.+I*NAN may give NaN+i*NAN if
+   I is a complex (rather than imaginary) constant.  For some reason,
+   however, it works fine in (pre-4.7) gcc if I define Inf and NaN as
+   1/0 and 0/0 (and only if I compile with optimization -O1 or more),
+   but not if I use the INFINITY or NAN macros. */
+
+/* __builtin_complex was introduced in gcc 4.7, but the C11 CMPLX macro
+   may not be defined unless we are using a recent (2012) version of
+   glibc and compile with -std=c11... note that icc lies about being
+   gcc and probably doesn't have this builtin(?), so exclude icc explicitly */
+#  if !defined(CMPLX) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)) && !(defined(__ICC) || defined(__INTEL_COMPILER))
+#    define CMPLX(a,b) __builtin_complex((double) (a), (double) (b))
+#  endif
+
+#  ifdef CMPLX // C11
+#    define C(a,b) CMPLX(a,b)
+#    define Inf INFINITY // C99 infinity
+#    ifdef NAN // GNU libc extension
+#      define NaN NAN
+#    else
+#      define NaN (0./0.) // NaN
+#    endif
+#  else
+#    define C(a,b) ((a) + I*(b))
+#    define Inf (1./0.) 
+#    define NaN (0./0.) 
+#  endif
+
+static inline cmplx cpolar(double r, double t)
+{
+  if (r == 0.0 && !isnan(t))
+    return 0.0;
+  else
+    return C(r * cos(t), r * sin(t));
+}
+
+#endif // !__cplusplus, i.e. pure C (requires C99 features)
+
+/////////////////////////////////////////////////////////////////////////
+// Auxiliary routines to compute other special functions based on w(z)
+
+// compute erfcx(z) = exp(z^2) erfz(z)
+cmplx FADDEEVA(erfcx)(cmplx z, double relerr)
+{
+  return FADDEEVA(w)(C(-cimag(z), creal(z)), relerr);
+}
+
+// compute the error function erf(x)
+double FADDEEVA_RE(erf)(double x)
+{
+#if !defined(__cplusplus)
+  return erf(x); // C99 supplies erf in math.h
+#elif (__cplusplus >= 201103L) || defined(HAVE_ERF)
+  return ::erf(x); // C++11 supplies std::erf in cmath
+#else
+  double mx2 = -x*x;
+  if (mx2 < -750) // underflow
+    return (x >= 0 ? 1.0 : -1.0);
+
+  if (x >= 0) {
+    if (x < 8e-2) goto taylor;
+    return 1.0 - exp(mx2) * FADDEEVA_RE(erfcx)(x);
+  }
+  else { // x < 0
+    if (x > -8e-2) goto taylor;
+    return exp(mx2) * FADDEEVA_RE(erfcx)(-x) - 1.0;
+  }
+
+  // Use Taylor series for small |x|, to avoid cancellation inaccuracy
+  //   erf(x) = 2/sqrt(pi) * x * (1 - x^2/3 + x^4/10 - x^6/42 + x^8/216 + ...)
+ taylor:
+  return x * (1.1283791670955125739
+              + mx2 * (0.37612638903183752464
+                       + mx2 * (0.11283791670955125739
+                                + mx2 * (0.026866170645131251760
+                                         + mx2 * 0.0052239776254421878422))));
+#endif
+}
+
+// compute the error function erf(z)
+cmplx FADDEEVA(erf)(cmplx z, double relerr)
+{
+  double x = creal(z), y = cimag(z);
+
+  if (y == 0)
+    return C(FADDEEVA_RE(erf)(x),
+             y); // preserve sign of 0
+  if (x == 0) // handle separately for speed & handling of y = Inf or NaN
+    return C(x, // preserve sign of 0
+             /* handle y -> Inf limit manually, since
+                exp(y^2) -> Inf but Im[w(y)] -> 0, so
+                IEEE will give us a NaN when it should be Inf */
+             y*y > 720 ? (y > 0 ? Inf : -Inf)
+             : exp(y*y) * FADDEEVA(w_im)(y));
+  
+  double mRe_z2 = (y - x) * (x + y); // Re(-z^2), being careful of overflow
+  double mIm_z2 = -2*x*y; // Im(-z^2)
+  if (mRe_z2 < -750) // underflow
+    return (x >= 0 ? 1.0 : -1.0);
+
+  /* Handle positive and negative x via different formulas,
+     using the mirror symmetries of w, to avoid overflow/underflow
+     problems from multiplying exponentially large and small quantities. */
+  if (x >= 0) {
+    if (x < 8e-2) {
+      if (fabs(y) < 1e-2)
+        goto taylor;
+      else if (fabs(mIm_z2) < 5e-3 && x < 5e-3)
+        goto taylor_erfi;
+    }
+    /* don't use complex exp function, since that will produce spurious NaN
+       values when multiplying w in an overflow situation. */
+    return 1.0 - exp(mRe_z2) *
+      (C(cos(mIm_z2), sin(mIm_z2))
+       * FADDEEVA(w)(C(-y,x), relerr));
+  }
+  else { // x < 0
+    if (x > -8e-2) { // duplicate from above to avoid fabs(x) call
+      if (fabs(y) < 1e-2)
+        goto taylor;
+      else if (fabs(mIm_z2) < 5e-3 && x > -5e-3)
+        goto taylor_erfi;
+    }
+    else if (isnan(x))
+      return C(NaN, y == 0 ? 0 : NaN);
+    /* don't use complex exp function, since that will produce spurious NaN
+       values when multiplying w in an overflow situation. */
+    return exp(mRe_z2) *
+      (C(cos(mIm_z2), sin(mIm_z2))
+       * FADDEEVA(w)(C(y,-x), relerr)) - 1.0;
+  }
+
+  // Use Taylor series for small |z|, to avoid cancellation inaccuracy
+  //   erf(z) = 2/sqrt(pi) * z * (1 - z^2/3 + z^4/10 - z^6/42 + z^8/216 + ...)
+ taylor:
+  {
+    cmplx mz2 = C(mRe_z2, mIm_z2); // -z^2
+    return z * (1.1283791670955125739
+                + mz2 * (0.37612638903183752464
+                         + mz2 * (0.11283791670955125739
+                                  + mz2 * (0.026866170645131251760
+                                          + mz2 * 0.0052239776254421878422))));
+  }
+
+  /* for small |x| and small |xy|, 
+     use Taylor series to avoid cancellation inaccuracy:
+       erf(x+iy) = erf(iy)
+          + 2*exp(y^2)/sqrt(pi) *
+            [ x * (1 - x^2 * (1+2y^2)/3 + x^4 * (3+12y^2+4y^4)/30 + ... 
+              - i * x^2 * y * (1 - x^2 * (3+2y^2)/6 + ...) ]
+     where:
+        erf(iy) = exp(y^2) * Im[w(y)]
+  */
+ taylor_erfi:
+  {
+    double x2 = x*x, y2 = y*y;
+    double expy2 = exp(y2);
+    return C
+      (expy2 * x * (1.1283791670955125739
+                    - x2 * (0.37612638903183752464
+                            + 0.75225277806367504925*y2)
+                    + x2*x2 * (0.11283791670955125739
+                               + y2 * (0.45135166683820502956
+                                       + 0.15045055561273500986*y2))),
+       expy2 * (FADDEEVA(w_im)(y)
+                - x2*y * (1.1283791670955125739 
+                          - x2 * (0.56418958354775628695 
+                                  + 0.37612638903183752464*y2))));
+  }
+}
+
+// erfi(z) = -i erf(iz)
+cmplx FADDEEVA(erfi)(cmplx z, double relerr)
+{
+  cmplx e = FADDEEVA(erf)(C(-cimag(z),creal(z)), relerr);
+  return C(cimag(e), -creal(e));
+}
+
+// erfi(x) = -i erf(ix)
+double FADDEEVA_RE(erfi)(double x)
+{
+  return x*x > 720 ? (x > 0 ? Inf : -Inf)
+    : exp(x*x) * FADDEEVA(w_im)(x);
+}
+
+// erfc(x) = 1 - erf(x)
+double FADDEEVA_RE(erfc)(double x)
+{
+#if !defined(__cplusplus)
+  return erfc(x); // C99 supplies erfc in math.h
+#elif (__cplusplus >= 201103L) || defined(HAVE_ERFC)
+  return ::erfc(x); // C++11 supplies std::erfc in cmath
+#else
+  if (x*x > 750) // underflow
+    return (x >= 0 ? 0.0 : 2.0);
+  return x >= 0 ? exp(-x*x) * FADDEEVA_RE(erfcx)(x) 
+    : 2. - exp(-x*x) * FADDEEVA_RE(erfcx)(-x);
+#endif
+}
+
+// erfc(z) = 1 - erf(z)
+cmplx FADDEEVA(erfc)(cmplx z, double relerr)
+{
+  double x = creal(z), y = cimag(z);
+
+  if (x == 0.)
+    return C(1,
+             /* handle y -> Inf limit manually, since
+                exp(y^2) -> Inf but Im[w(y)] -> 0, so
+                IEEE will give us a NaN when it should be Inf */
+             y*y > 720 ? (y > 0 ? -Inf : Inf)
+             : -exp(y*y) * FADDEEVA(w_im)(y));
+  if (y == 0.) {
+    if (x*x > 750) // underflow
+      return C(x >= 0 ? 0.0 : 2.0,
+               -y); // preserve sign of 0
+    return C(x >= 0 ? exp(-x*x) * FADDEEVA_RE(erfcx)(x) 
+             : 2. - exp(-x*x) * FADDEEVA_RE(erfcx)(-x),
+             -y); // preserve sign of zero
+  }
+
+  double mRe_z2 = (y - x) * (x + y); // Re(-z^2), being careful of overflow
+  double mIm_z2 = -2*x*y; // Im(-z^2)
+  if (mRe_z2 < -750) // underflow
+    return (x >= 0 ? 0.0 : 2.0);
+
+  if (x >= 0)
+    return cexp(C(mRe_z2, mIm_z2))
+      * FADDEEVA(w)(C(-y,x), relerr);
+  else
+    return 2.0 - cexp(C(mRe_z2, mIm_z2))
+      * FADDEEVA(w)(C(y,-x), relerr);
+}
+
+// compute Dawson(x) = sqrt(pi)/2  *  exp(-x^2) * erfi(x)
+double FADDEEVA_RE(Dawson)(double x)
+{
+  const double spi2 = 0.8862269254527580136490837416705725913990; // sqrt(pi)/2
+  return spi2 * FADDEEVA(w_im)(x);
+}
+
+// compute Dawson(z) = sqrt(pi)/2  *  exp(-z^2) * erfi(z)
+cmplx FADDEEVA(Dawson)(cmplx z, double relerr)
+{
+  const double spi2 = 0.8862269254527580136490837416705725913990; // sqrt(pi)/2
+  double x = creal(z), y = cimag(z);
+
+  // handle axes separately for speed & proper handling of x or y = Inf or NaN
+  if (y == 0)
+    return C(spi2 * FADDEEVA(w_im)(x),
+             -y); // preserve sign of 0
+  if (x == 0) {
+    double y2 = y*y;
+    if (y2 < 2.5e-5) { // Taylor expansion
+      return C(x, // preserve sign of 0
+               y * (1.
+                    + y2 * (0.6666666666666666666666666666666666666667
+                            + y2 * 0.26666666666666666666666666666666666667)));
+    }
+    return C(x, // preserve sign of 0
+             spi2 * (y >= 0 
+                     ? exp(y2) - FADDEEVA_RE(erfcx)(y)
+                     : FADDEEVA_RE(erfcx)(-y) - exp(y2)));
+  }
+
+  double mRe_z2 = (y - x) * (x + y); // Re(-z^2), being careful of overflow
+  double mIm_z2 = -2*x*y; // Im(-z^2)
+  cmplx mz2 = C(mRe_z2, mIm_z2); // -z^2
+
+  /* Handle positive and negative x via different formulas,
+     using the mirror symmetries of w, to avoid overflow/underflow
+     problems from multiplying exponentially large and small quantities. */
+  if (y >= 0) {
+    if (y < 5e-3) {
+      if (fabs(x) < 5e-3)
+        goto taylor;
+      else if (fabs(mIm_z2) < 5e-3)
+        goto taylor_realaxis;
+    }
+    cmplx res = cexp(mz2) - FADDEEVA(w)(z, relerr);
+    return spi2 * C(-cimag(res), creal(res));
+  }
+  else { // y < 0
+    if (y > -5e-3) { // duplicate from above to avoid fabs(x) call
+      if (fabs(x) < 5e-3)
+        goto taylor;
+      else if (fabs(mIm_z2) < 5e-3)
+        goto taylor_realaxis;
+    }
+    else if (isnan(y))
+      return C(x == 0 ? 0 : NaN, NaN);
+    cmplx res = FADDEEVA(w)(-z, relerr) - cexp(mz2);
+    return spi2 * C(-cimag(res), creal(res));
+  }
+
+  // Use Taylor series for small |z|, to avoid cancellation inaccuracy
+  //     dawson(z) = z - 2/3 z^3 + 4/15 z^5 + ...
+ taylor:
+  return z * (1.
+              + mz2 * (0.6666666666666666666666666666666666666667
+                       + mz2 * 0.2666666666666666666666666666666666666667));
+
+  /* for small |y| and small |xy|, 
+     use Taylor series to avoid cancellation inaccuracy:
+       dawson(x + iy)
+        = D + y^2 (D + x - 2Dx^2)
+            + y^4 (D/2 + 5x/6 - 2Dx^2 - x^3/3 + 2Dx^4/3)
+        + iy [ (1-2Dx) + 2/3 y^2 (1 - 3Dx - x^2 + 2Dx^3)
+              + y^4/15 (4 - 15Dx - 9x^2 + 20Dx^3 + 2x^4 - 4Dx^5) ] + ...
+     where D = dawson(x) 
+
+     However, for large |x|, 2Dx -> 1 which gives cancellation problems in
+     this series (many of the leading terms cancel).  So, for large |x|,
+     we need to substitute a continued-fraction expansion for D.
+
+        dawson(x) = 0.5 / (x-0.5/(x-1/(x-1.5/(x-2/(x-2.5/(x...))))))
+
+     The 6 terms shown here seems to be the minimum needed to be
+     accurate as soon as the simpler Taylor expansion above starts
+     breaking down.  Using this 6-term expansion, factoring out the
+     denominator, and simplifying with Maple, we obtain:
+
+      Re dawson(x + iy) * (-15 + 90x^2 - 60x^4 + 8x^6) / x
+        = 33 - 28x^2 + 4x^4 + y^2 (18 - 4x^2) + 4 y^4
+      Im dawson(x + iy) * (-15 + 90x^2 - 60x^4 + 8x^6) / y
+        = -15 + 24x^2 - 4x^4 + 2/3 y^2 (6x^2 - 15) - 4 y^4
+
+     Finally, for |x| > 5e7, we can use a simpler 1-term continued-fraction
+     expansion for the real part, and a 2-term expansion for the imaginary
+     part.  (This avoids overflow problems for huge |x|.)  This yields:
+     
+     Re dawson(x + iy) = [1 + y^2 (1 + y^2/2 - (xy)^2/3)] / (2x)
+     Im dawson(x + iy) = y [ -1 - 2/3 y^2 + y^4/15 (2x^2 - 4) ] / (2x^2 - 1)
+
+ */
+ taylor_realaxis:
+  {
+    double x2 = x*x;
+    if (x2 > 1600) { // |x| > 40
+      double y2 = y*y;
+      if (x2 > 25e14) {// |x| > 5e7
+        double xy2 = (x*y)*(x*y);
+        return C((0.5 + y2 * (0.5 + 0.25*y2
+                              - 0.16666666666666666667*xy2)) / x,
+                 y * (-1 + y2 * (-0.66666666666666666667
+                                 + 0.13333333333333333333*xy2
+                                 - 0.26666666666666666667*y2))
+                 / (2*x2 - 1));
+      }
+      return (1. / (-15 + x2*(90 + x2*(-60 + 8*x2)))) *
+        C(x * (33 + x2 * (-28 + 4*x2)
+               + y2 * (18 - 4*x2 + 4*y2)),
+          y * (-15 + x2 * (24 - 4*x2)
+               + y2 * (4*x2 - 10 - 4*y2)));
+    }
+    else {
+      double D = spi2 * FADDEEVA(w_im)(x);
+      double x2 = x*x, y2 = y*y;
+      return C
+        (D + y2 * (D + x - 2*D*x2)
+         + y2*y2 * (D * (0.5 - x2 * (2 - 0.66666666666666666667*x2))
+                    + x * (0.83333333333333333333
+                           - 0.33333333333333333333 * x2)),
+         y * (1 - 2*D*x
+              + y2 * 0.66666666666666666667 * (1 - x2 - D*x * (3 - 2*x2))
+              + y2*y2 * (0.26666666666666666667 -
+                         x2 * (0.6 - 0.13333333333333333333 * x2)
+                         - D*x * (1 - x2 * (1.3333333333333333333
+                                            - 0.26666666666666666667 * x2)))));
+    }
+  }
+}
+
+/////////////////////////////////////////////////////////////////////////
+
+// return sinc(x) = sin(x)/x, given both x and sin(x) 
+// [since we only use this in cases where sin(x) has already been computed]
+static inline double sinc(double x, double sinx) { 
+  return fabs(x) < 1e-4 ? 1 - (0.1666666666666666666667)*x*x : sinx / x; 
+}
+
+// sinh(x) via Taylor series, accurate to machine precision for |x| < 1e-2
+static inline double sinh_taylor(double x) {
+  return x * (1 + (x*x) * (0.1666666666666666666667
+                           + 0.00833333333333333333333 * (x*x)));
+}
+
+static inline double sqr(double x) { return x*x; }
+
+// precomputed table of expa2n2[n-1] = exp(-a2*n*n)
+// for double-precision a2 = 0.26865... in FADDEEVA(w), below.
+static const double expa2n2[] = {
+  7.64405281671221563e-01,
+  3.41424527166548425e-01,
+  8.91072646929412548e-02,
+  1.35887299055460086e-02,
+  1.21085455253437481e-03,
+  6.30452613933449404e-05,
+  1.91805156577114683e-06,
+  3.40969447714832381e-08,
+  3.54175089099469393e-10,
+  2.14965079583260682e-12,
+  7.62368911833724354e-15,
+  1.57982797110681093e-17,
+  1.91294189103582677e-20,
+  1.35344656764205340e-23,
+  5.59535712428588720e-27,
+  1.35164257972401769e-30,
+  1.90784582843501167e-34,
+  1.57351920291442930e-38,
+  7.58312432328032845e-43,
+  2.13536275438697082e-47,
+  3.51352063787195769e-52,
+  3.37800830266396920e-57,
+  1.89769439468301000e-62,
+  6.22929926072668851e-68,
+  1.19481172006938722e-73,
+  1.33908181133005953e-79,
+  8.76924303483223939e-86,
+  3.35555576166254986e-92,
+  7.50264110688173024e-99,
+  9.80192200745410268e-106,
+  7.48265412822268959e-113,
+  3.33770122566809425e-120,
+  8.69934598159861140e-128,
+  1.32486951484088852e-135,
+  1.17898144201315253e-143,
+  6.13039120236180012e-152,
+  1.86258785950822098e-160,
+  3.30668408201432783e-169,
+  3.43017280887946235e-178,
+  2.07915397775808219e-187,
+  7.36384545323984966e-197,
+  1.52394760394085741e-206,
+  1.84281935046532100e-216,
+  1.30209553802992923e-226,
+  5.37588903521080531e-237,
+  1.29689584599763145e-247,
+  1.82813078022866562e-258,
+  1.50576355348684241e-269,
+  7.24692320799294194e-281,
+  2.03797051314726829e-292,
+  3.34880215927873807e-304,
+  0.0 // underflow (also prevents reads past array end, below)
+};
+
+/////////////////////////////////////////////////////////////////////////
+
+cmplx FADDEEVA(w)(cmplx z, double relerr)
+{
+  if (creal(z) == 0.0)
+    return C(FADDEEVA_RE(erfcx)(cimag(z)), 
+             creal(z)); // give correct sign of 0 in cimag(w)
+  else if (cimag(z) == 0)
+    return C(exp(-sqr(creal(z))),
+             FADDEEVA(w_im)(creal(z)));
+
+  double a, a2, c;
+  if (relerr <= DBL_EPSILON) {
+    relerr = DBL_EPSILON;
+    a = 0.518321480430085929872; // pi / sqrt(-log(eps*0.5))
+    c = 0.329973702884629072537; // (2/pi) * a;
+    a2 = 0.268657157075235951582; // a^2
+  }
+  else {
+    const double pi = 3.14159265358979323846264338327950288419716939937510582;
+    if (relerr > 0.1) relerr = 0.1; // not sensible to compute < 1 digit
+    a = pi / sqrt(-log(relerr*0.5));
+    c = (2/pi)*a;
+    a2 = a*a;
+  }
+  const double x = fabs(creal(z));
+  const double y = cimag(z), ya = fabs(y);
+
+  cmplx ret = 0.; // return value
+
+  double sum1 = 0, sum2 = 0, sum3 = 0, sum4 = 0, sum5 = 0;
+
+#define USE_CONTINUED_FRACTION 1 // 1 to use continued fraction for large |z|
+
+#if USE_CONTINUED_FRACTION
+  if (ya > 7 || (x > 6  // continued fraction is faster
+                 /* As pointed out by M. Zaghloul, the continued
+                    fraction seems to give a large relative error in
+                    Re w(z) for |x| ~ 6 and small |y|, so use
+                    algorithm 816 in this region: */
+                 && (ya > 0.1 || (x > 8 && ya > 1e-10) || x > 28))) {
+    
+    /* Poppe & Wijers suggest using a number of terms
+           nu = 3 + 1442 / (26*rho + 77)
+       where rho = sqrt((x/x0)^2 + (y/y0)^2) where x0=6.3, y0=4.4.
+       (They only use this expansion for rho >= 1, but rho a little less
+        than 1 seems okay too.)
+       Instead, I did my own fit to a slightly different function
+       that avoids the hypotenuse calculation, using NLopt to minimize
+       the sum of the squares of the errors in nu with the constraint
+       that the estimated nu be >= minimum nu to attain machine precision.
+       I also separate the regions where nu == 2 and nu == 1. */
+    const double ispi = 0.56418958354775628694807945156; // 1 / sqrt(pi)
+    double xs = y < 0 ? -creal(z) : creal(z); // compute for -z if y < 0
+    if (x + ya > 4000) { // nu <= 2
+      if (x + ya > 1e7) { // nu == 1, w(z) = i/sqrt(pi) / z
+        // scale to avoid overflow
+        if (x > ya) {
+          double yax = ya / xs; 
+          double denom = ispi / (xs + yax*ya);
+          ret = C(denom*yax, denom);
+        }
+        else if (isinf(ya))
+          return ((isnan(x) || y < 0) 
+                  ? C(NaN,NaN) : C(0,0));
+        else {
+          double xya = xs / ya;
+          double denom = ispi / (xya*xs + ya);
+          ret = C(denom, denom*xya);
+        }
+      }
+      else { // nu == 2, w(z) = i/sqrt(pi) * z / (z*z - 0.5)
+        double dr = xs*xs - ya*ya - 0.5, di = 2*xs*ya;
+        double denom = ispi / (dr*dr + di*di);
+        ret = C(denom * (xs*di-ya*dr), denom * (xs*dr+ya*di));
+      }
+    }
+    else { // compute nu(z) estimate and do general continued fraction
+      const double c0=3.9, c1=11.398, c2=0.08254, c3=0.1421, c4=0.2023; // fit
+      double nu = floor(c0 + c1 / (c2*x + c3*ya + c4));
+      double wr = xs, wi = ya;
+      for (nu = 0.5 * (nu - 1); nu > 0.4; nu -= 0.5) {
+        // w <- z - nu/w:
+        double denom = nu / (wr*wr + wi*wi);
+        wr = xs - wr * denom;
+        wi = ya + wi * denom;
+      }
+      { // w(z) = i/sqrt(pi) / w:
+        double denom = ispi / (wr*wr + wi*wi);
+        ret = C(denom*wi, denom*wr);
+      }
+    }
+    if (y < 0) {
+      // use w(z) = 2.0*exp(-z*z) - w(-z), 
+      // but be careful of overflow in exp(-z*z) 
+      //                                = exp(-(xs*xs-ya*ya) -2*i*xs*ya) 
+      return 2.0*cexp(C((ya-xs)*(xs+ya), 2*xs*y)) - ret;
+    }
+    else
+      return ret;
+  }
+#else // !USE_CONTINUED_FRACTION
+  if (x + ya > 1e7) { // w(z) = i/sqrt(pi) / z, to machine precision
+    const double ispi = 0.56418958354775628694807945156; // 1 / sqrt(pi)
+    double xs = y < 0 ? -creal(z) : creal(z); // compute for -z if y < 0
+    // scale to avoid overflow
+    if (x > ya) {
+      double yax = ya / xs; 
+      double denom = ispi / (xs + yax*ya);
+      ret = C(denom*yax, denom);
+    }
+    else {
+      double xya = xs / ya;
+      double denom = ispi / (xya*xs + ya);
+      ret = C(denom, denom*xya);
+    }
+    if (y < 0) {
+      // use w(z) = 2.0*exp(-z*z) - w(-z), 
+      // but be careful of overflow in exp(-z*z) 
+      //                                = exp(-(xs*xs-ya*ya) -2*i*xs*ya) 
+      return 2.0*cexp(C((ya-xs)*(xs+ya), 2*xs*y)) - ret;
+    }
+    else
+      return ret;
+  }
+#endif // !USE_CONTINUED_FRACTION 
+
+  /* Note: The test that seems to be suggested in the paper is x <
+     sqrt(-log(DBL_MIN)), about 26.6, since otherwise exp(-x^2)
+     underflows to zero and sum1,sum2,sum4 are zero.  However, long
+     before this occurs, the sum1,sum2,sum4 contributions are
+     negligible in double precision; I find that this happens for x >
+     about 6, for all y.  On the other hand, I find that the case
+     where we compute all of the sums is faster (at least with the
+     precomputed expa2n2 table) until about x=10.  Furthermore, if we
+     try to compute all of the sums for x > 20, I find that we
+     sometimes run into numerical problems because underflow/overflow
+     problems start to appear in the various coefficients of the sums,
+     below.  Therefore, we use x < 10 here. */
+  else if (x < 10) {
+    double prod2ax = 1, prodm2ax = 1;
+    double expx2;
+
+    if (isnan(y))
+      return C(y,y);
+    
+    /* Somewhat ugly copy-and-paste duplication here, but I see significant
+       speedups from using the special-case code with the precomputed
+       exponential, and the x < 5e-4 special case is needed for accuracy. */
+
+    if (relerr == DBL_EPSILON) { // use precomputed exp(-a2*(n*n)) table
+      if (x < 5e-4) { // compute sum4 and sum5 together as sum5-sum4
+        const double x2 = x*x;
+        expx2 = 1 - x2 * (1 - 0.5*x2); // exp(-x*x) via Taylor
+        // compute exp(2*a*x) and exp(-2*a*x) via Taylor, to double precision
+        const double ax2 = 1.036642960860171859744*x; // 2*a*x
+        const double exp2ax =
+          1 + ax2 * (1 + ax2 * (0.5 + 0.166666666666666666667*ax2));
+        const double expm2ax =
+          1 - ax2 * (1 - ax2 * (0.5 - 0.166666666666666666667*ax2));
+        for (int n = 1; 1; ++n) {
+          const double coef = expa2n2[n-1] * expx2 / (a2*(n*n) + y*y);
+          prod2ax *= exp2ax;
+          prodm2ax *= expm2ax;
+          sum1 += coef;
+          sum2 += coef * prodm2ax;
+          sum3 += coef * prod2ax;
+          
+          // really = sum5 - sum4
+          sum5 += coef * (2*a) * n * sinh_taylor((2*a)*n*x);
+          
+          // test convergence via sum3
+          if (coef * prod2ax < relerr * sum3) break;
+        }
+      }
+      else { // x > 5e-4, compute sum4 and sum5 separately
+        expx2 = exp(-x*x);
+        const double exp2ax = exp((2*a)*x), expm2ax = 1 / exp2ax;
+        for (int n = 1; 1; ++n) {
+          const double coef = expa2n2[n-1] * expx2 / (a2*(n*n) + y*y);
+          prod2ax *= exp2ax;
+          prodm2ax *= expm2ax;
+          sum1 += coef;
+          sum2 += coef * prodm2ax;
+          sum4 += (coef * prodm2ax) * (a*n);
+          sum3 += coef * prod2ax;
+          sum5 += (coef * prod2ax) * (a*n);
+          // test convergence via sum5, since this sum has the slowest decay
+          if ((coef * prod2ax) * (a*n) < relerr * sum5) break;
+        }
+      }
+    }
+    else { // relerr != DBL_EPSILON, compute exp(-a2*(n*n)) on the fly
+      const double exp2ax = exp((2*a)*x), expm2ax = 1 / exp2ax;
+      if (x < 5e-4) { // compute sum4 and sum5 together as sum5-sum4
+        const double x2 = x*x;
+        expx2 = 1 - x2 * (1 - 0.5*x2); // exp(-x*x) via Taylor
+        for (int n = 1; 1; ++n) {
+          const double coef = exp(-a2*(n*n)) * expx2 / (a2*(n*n) + y*y);
+          prod2ax *= exp2ax;
+          prodm2ax *= expm2ax;
+          sum1 += coef;
+          sum2 += coef * prodm2ax;
+          sum3 += coef * prod2ax;
+          
+          // really = sum5 - sum4
+          sum5 += coef * (2*a) * n * sinh_taylor((2*a)*n*x);
+          
+          // test convergence via sum3
+          if (coef * prod2ax < relerr * sum3) break;
+        }
+      }
+      else { // x > 5e-4, compute sum4 and sum5 separately
+        expx2 = exp(-x*x);
+        for (int n = 1; 1; ++n) {
+          const double coef = exp(-a2*(n*n)) * expx2 / (a2*(n*n) + y*y);
+          prod2ax *= exp2ax;
+          prodm2ax *= expm2ax;
+          sum1 += coef;
+          sum2 += coef * prodm2ax;
+          sum4 += (coef * prodm2ax) * (a*n);
+          sum3 += coef * prod2ax;
+          sum5 += (coef * prod2ax) * (a*n);
+          // test convergence via sum5, since this sum has the slowest decay
+          if ((coef * prod2ax) * (a*n) < relerr * sum5) break;
+        }
+      }
+    }
+    const double expx2erfcxy = // avoid spurious overflow for large negative y
+      y > -6 // for y < -6, erfcx(y) = 2*exp(y*y) to double precision
+      ? expx2*FADDEEVA_RE(erfcx)(y) : 2*exp(y*y-x*x);
+    if (y > 5) { // imaginary terms cancel
+      const double sinxy = sin(x*y);
+      ret = (expx2erfcxy - c*y*sum1) * cos(2*x*y)
+        + (c*x*expx2) * sinxy * sinc(x*y, sinxy);
+    }
+    else {
+      double xs = creal(z);
+      const double sinxy = sin(xs*y);
+      const double sin2xy = sin(2*xs*y), cos2xy = cos(2*xs*y);
+      const double coef1 = expx2erfcxy - c*y*sum1;
+      const double coef2 = c*xs*expx2;
+      ret = C(coef1 * cos2xy + coef2 * sinxy * sinc(xs*y, sinxy),
+              coef2 * sinc(2*xs*y, sin2xy) - coef1 * sin2xy);
+    }
+  }
+  else { // x large: only sum3 & sum5 contribute (see above note)    
+    if (isnan(x))
+      return C(x,x);
+    if (isnan(y))
+      return C(y,y);
+
+#if USE_CONTINUED_FRACTION
+    ret = exp(-x*x); // |y| < 1e-10, so we only need exp(-x*x) term
+#else
+    if (y < 0) {
+      /* erfcx(y) ~ 2*exp(y*y) + (< 1) if y < 0, so
+         erfcx(y)*exp(-x*x) ~ 2*exp(y*y-x*x) term may not be negligible
+         if y*y - x*x > -36 or so.  So, compute this term just in case.
+         We also need the -exp(-x*x) term to compute Re[w] accurately
+         in the case where y is very small. */
+      ret = cpolar(2*exp(y*y-x*x) - exp(-x*x), -2*creal(z)*y);
+    }
+    else
+      ret = exp(-x*x); // not negligible in real part if y very small
+#endif
+    // (round instead of ceil as in original paper; note that x/a > 1 here)
+    double n0 = floor(x/a + 0.5); // sum in both directions, starting at n0
+    double dx = a*n0 - x;
+    sum3 = exp(-dx*dx) / (a2*(n0*n0) + y*y);
+    sum5 = a*n0 * sum3;
+    double exp1 = exp(4*a*dx), exp1dn = 1;
+    int dn;
+    for (dn = 1; n0 - dn > 0; ++dn) { // loop over n0-dn and n0+dn terms
+      double np = n0 + dn, nm = n0 - dn;
+      double tp = exp(-sqr(a*dn+dx));
+      double tm = tp * (exp1dn *= exp1); // trick to get tm from tp
+      tp /= (a2*(np*np) + y*y);
+      tm /= (a2*(nm*nm) + y*y);
+      sum3 += tp + tm;
+      sum5 += a * (np * tp + nm * tm);
+      if (a * (np * tp + nm * tm) < relerr * sum5) goto finish;
+    }
+    while (1) { // loop over n0+dn terms only (since n0-dn <= 0)
+      double np = n0 + dn++;
+      double tp = exp(-sqr(a*dn+dx)) / (a2*(np*np) + y*y);
+      sum3 += tp;
+      sum5 += a * np * tp;
+      if (a * np * tp < relerr * sum5) goto finish;
+    }
+  }
+ finish:
+  return ret + C((0.5*c)*y*(sum2+sum3), 
+                 (0.5*c)*copysign(sum5-sum4, creal(z)));
+}
+
+/////////////////////////////////////////////////////////////////////////
+
+/* erfcx(x) = exp(x^2) erfc(x) function, for real x, written by
+   Steven G. Johnson, October 2012.
+
+   This function combines a few different ideas.
+
+   First, for x > 50, it uses a continued-fraction expansion (same as
+   for the Faddeeva function, but with algebraic simplifications for z=i*x).
+
+   Second, for 0 <= x <= 50, it uses Chebyshev polynomial approximations,
+   but with two twists:
+
+      a) It maps x to y = 4 / (4+x) in [0,1].  This simple transformation,
+         inspired by a similar transformation in the octave-forge/specfun
+         erfcx by Soren Hauberg, results in much faster Chebyshev convergence
+         than other simple transformations I have examined.
+
+      b) Instead of using a single Chebyshev polynomial for the entire
+         [0,1] y interval, we break the interval up into 100 equal
+         subintervals, with a switch/lookup table, and use much lower
+         degree Chebyshev polynomials in each subinterval. This greatly
+         improves performance in my tests.
+
+   For x < 0, we use the relationship erfcx(-x) = 2 exp(x^2) - erfc(x),
+   with the usual checks for overflow etcetera.
+
+   Performance-wise, it seems to be substantially faster than either
+   the SLATEC DERFC function [or an erfcx function derived therefrom]
+   or Cody's CALERF function (from netlib.org/specfun), while
+   retaining near machine precision in accuracy.  */
+
+/* Given y100=100*y, where y = 4/(4+x) for x >= 0, compute erfc(x).
+
+   Uses a look-up table of 100 different Chebyshev polynomials
+   for y intervals [0,0.01], [0.01,0.02], ...., [0.99,1], generated
+   with the help of Maple and a little shell script.   This allows
+   the Chebyshev polynomials to be of significantly lower degree (about 1/4)
+   compared to fitting the whole [0,1] interval with a single polynomial. */
+static double erfcx_y100(double y100)
+{
+  switch ((int) y100) {
+case 0: {
+double t = 2*y100 - 1;
+return 0.70878032454106438663e-3 + (0.71234091047026302958e-3 + (0.35779077297597742384e-5 + (0.17403143962587937815e-7 + (0.81710660047307788845e-10 + (0.36885022360434957634e-12 + 0.15917038551111111111e-14 * t) * t) * t) * t) * t) * t;
+}
+case 1: {
+double t = 2*y100 - 3;
+return 0.21479143208285144230e-2 + (0.72686402367379996033e-3 + (0.36843175430938995552e-5 + (0.18071841272149201685e-7 + (0.85496449296040325555e-10 + (0.38852037518534291510e-12 + 0.16868473576888888889e-14 * t) * t) * t) * t) * t) * t;
+}
+case 2: {
+double t = 2*y100 - 5;
+return 0.36165255935630175090e-2 + (0.74182092323555510862e-3 + (0.37948319957528242260e-5 + (0.18771627021793087350e-7 + (0.89484715122415089123e-10 + (0.40935858517772440862e-12 + 0.17872061464888888889e-14 * t) * t) * t) * t) * t) * t;
+}
+case 3: {
+double t = 2*y100 - 7;
+return 0.51154983860031979264e-2 + (0.75722840734791660540e-3 + (0.39096425726735703941e-5 + (0.19504168704300468210e-7 + (0.93687503063178993915e-10 + (0.43143925959079664747e-12 + 0.18939926435555555556e-14 * t) * t) * t) * t) * t) * t;
+}
+case 4: {
+double t = 2*y100 - 9;
+return 0.66457513172673049824e-2 + (0.77310406054447454920e-3 + (0.40289510589399439385e-5 + (0.20271233238288381092e-7 + (0.98117631321709100264e-10 + (0.45484207406017752971e-12 + 0.20076352213333333333e-14 * t) * t) * t) * t) * t) * t;
+}
+case 5: {
+double t = 2*y100 - 11;
+return 0.82082389970241207883e-2 + (0.78946629611881710721e-3 + (0.41529701552622656574e-5 + (0.21074693344544655714e-7 + (0.10278874108587317989e-9 + (0.47965201390613339638e-12 + 0.21285907413333333333e-14 * t) * t) * t) * t) * t) * t;
+}
+case 6: {
+double t = 2*y100 - 13;
+return 0.98039537275352193165e-2 + (0.80633440108342840956e-3 + (0.42819241329736982942e-5 + (0.21916534346907168612e-7 + (0.10771535136565470914e-9 + (0.50595972623692822410e-12 + 0.22573462684444444444e-14 * t) * t) * t) * t) * t) * t;
+}
+case 7: {
+double t = 2*y100 - 15;
+return 0.11433927298290302370e-1 + (0.82372858383196561209e-3 + (0.44160495311765438816e-5 + (0.22798861426211986056e-7 + (0.11291291745879239736e-9 + (0.53386189365816880454e-12 + 0.23944209546666666667e-14 * t) * t) * t) * t) * t) * t;
+}
+case 8: {
+double t = 2*y100 - 17;
+return 0.13099232878814653979e-1 + (0.84167002467906968214e-3 + (0.45555958988457506002e-5 + (0.23723907357214175198e-7 + (0.11839789326602695603e-9 + (0.56346163067550237877e-12 + 0.25403679644444444444e-14 * t) * t) * t) * t) * t) * t;
+}
+case 9: {
+double t = 2*y100 - 19;
+return 0.14800987015587535621e-1 + (0.86018092946345943214e-3 + (0.47008265848816866105e-5 + (0.24694040760197315333e-7 + (0.12418779768752299093e-9 + (0.59486890370320261949e-12 + 0.26957764568888888889e-14 * t) * t) * t) * t) * t) * t;
+}
+case 10: {
+double t = 2*y100 - 21;
+return 0.16540351739394069380e-1 + (0.87928458641241463952e-3 + (0.48520195793001753903e-5 + (0.25711774900881709176e-7 + (0.13030128534230822419e-9 + (0.62820097586874779402e-12 + 0.28612737351111111111e-14 * t) * t) * t) * t) * t) * t;
+}
+case 11: {
+double t = 2*y100 - 23;
+return 0.18318536789842392647e-1 + (0.89900542647891721692e-3 + (0.50094684089553365810e-5 + (0.26779777074218070482e-7 + (0.13675822186304615566e-9 + (0.66358287745352705725e-12 + 0.30375273884444444444e-14 * t) * t) * t) * t) * t) * t;
+}
+case 12: {
+double t = 2*y100 - 25;
+return 0.20136801964214276775e-1 + (0.91936908737673676012e-3 + (0.51734830914104276820e-5 + (0.27900878609710432673e-7 + (0.14357976402809042257e-9 + (0.70114790311043728387e-12 + 0.32252476000000000000e-14 * t) * t) * t) * t) * t) * t;
+}
+case 13: {
+double t = 2*y100 - 27;
+return 0.21996459598282740954e-1 + (0.94040248155366777784e-3 + (0.53443911508041164739e-5 + (0.29078085538049374673e-7 + (0.15078844500329731137e-9 + (0.74103813647499204269e-12 + 0.34251892320000000000e-14 * t) * t) * t) * t) * t) * t;
+}
+case 14: {
+double t = 2*y100 - 29;
+return 0.23898877187226319502e-1 + (0.96213386835900177540e-3 + (0.55225386998049012752e-5 + (0.30314589961047687059e-7 + (0.15840826497296335264e-9 + (0.78340500472414454395e-12 + 0.36381553564444444445e-14 * t) * t) * t) * t) * t) * t;
+}
+case 15: {
+double t = 2*y100 - 31;
+return 0.25845480155298518485e-1 + (0.98459293067820123389e-3 + (0.57082915920051843672e-5 + (0.31613782169164830118e-7 + (0.16646478745529630813e-9 + (0.82840985928785407942e-12 + 0.38649975768888888890e-14 * t) * t) * t) * t) * t) * t;
+}
+case 16: {
+double t = 2*y100 - 33;
+return 0.27837754783474696598e-1 + (0.10078108563256892757e-2 + (0.59020366493792212221e-5 + (0.32979263553246520417e-7 + (0.17498524159268458073e-9 + (0.87622459124842525110e-12 + 0.41066206488888888890e-14 * t) * t) * t) * t) * t) * t;
+}
+case 17: {
+double t = 2*y100 - 35;
+return 0.29877251304899307550e-1 + (0.10318204245057349310e-2 + (0.61041829697162055093e-5 + (0.34414860359542720579e-7 + (0.18399863072934089607e-9 + (0.92703227366365046533e-12 + 0.43639844053333333334e-14 * t) * t) * t) * t) * t) * t;
+}
+case 18: {
+double t = 2*y100 - 37;
+return 0.31965587178596443475e-1 + (0.10566560976716574401e-2 + (0.63151633192414586770e-5 + (0.35924638339521924242e-7 + (0.19353584758781174038e-9 + (0.98102783859889264382e-12 + 0.46381060817777777779e-14 * t) * t) * t) * t) * t) * t;
+}
+case 19: {
+double t = 2*y100 - 39;
+return 0.34104450552588334840e-1 + (0.10823541191350532574e-2 + (0.65354356159553934436e-5 + (0.37512918348533521149e-7 + (0.20362979635817883229e-9 + (0.10384187833037282363e-11 + 0.49300625262222222221e-14 * t) * t) * t) * t) * t) * t;
+}
+case 20: {
+double t = 2*y100 - 41;
+return 0.36295603928292425716e-1 + (0.11089526167995268200e-2 + (0.67654845095518363577e-5 + (0.39184292949913591646e-7 + (0.21431552202133775150e-9 + (0.10994259106646731797e-11 + 0.52409949102222222221e-14 * t) * t) * t) * t) * t) * t;
+}
+case 21: {
+double t = 2*y100 - 43;
+return 0.38540888038840509795e-1 + (0.11364917134175420009e-2 + (0.70058230641246312003e-5 + (0.40943644083718586939e-7 + (0.22563034723692881631e-9 + (0.11642841011361992885e-11 + 0.55721092871111111110e-14 * t) * t) * t) * t) * t) * t;
+}
+case 22: {
+double t = 2*y100 - 45;
+return 0.40842225954785960651e-1 + (0.11650136437945673891e-2 + (0.72569945502343006619e-5 + (0.42796161861855042273e-7 + (0.23761401711005024162e-9 + (0.12332431172381557035e-11 + 0.59246802364444444445e-14 * t) * t) * t) * t) * t) * t;
+}
+case 23: {
+double t = 2*y100 - 47;
+return 0.43201627431540222422e-1 + (0.11945628793917272199e-2 + (0.75195743532849206263e-5 + (0.44747364553960993492e-7 + (0.25030885216472953674e-9 + (0.13065684400300476484e-11 + 0.63000532853333333334e-14 * t) * t) * t) * t) * t) * t;
+}
+case 24: {
+double t = 2*y100 - 49;
+return 0.45621193513810471438e-1 + (0.12251862608067529503e-2 + (0.77941720055551920319e-5 + (0.46803119830954460212e-7 + (0.26375990983978426273e-9 + (0.13845421370977119765e-11 + 0.66996477404444444445e-14 * t) * t) * t) * t) * t) * t;
+}
+case 25: {
+double t = 2*y100 - 51;
+return 0.48103121413299865517e-1 + (0.12569331386432195113e-2 + (0.80814333496367673980e-5 + (0.48969667335682018324e-7 + (0.27801515481905748484e-9 + (0.14674637611609884208e-11 + 0.71249589351111111110e-14 * t) * t) * t) * t) * t) * t;
+}
+case 26: {
+double t = 2*y100 - 53;
+return 0.50649709676983338501e-1 + (0.12898555233099055810e-2 + (0.83820428414568799654e-5 + (0.51253642652551838659e-7 + (0.29312563849675507232e-9 + (0.15556512782814827846e-11 + 0.75775607822222222221e-14 * t) * t) * t) * t) * t) * t;
+}
+case 27: {
+double t = 2*y100 - 55;
+return 0.53263363664388864181e-1 + (0.13240082443256975769e-2 + (0.86967260015007658418e-5 + (0.53662102750396795566e-7 + (0.30914568786634796807e-9 + (0.16494420240828493176e-11 + 0.80591079644444444445e-14 * t) * t) * t) * t) * t) * t;
+}
+case 28: {
+double t = 2*y100 - 57;
+return 0.55946601353500013794e-1 + (0.13594491197408190706e-2 + (0.90262520233016380987e-5 + (0.56202552975056695376e-7 + (0.32613310410503135996e-9 + (0.17491936862246367398e-11 + 0.85713381688888888890e-14 * t) * t) * t) * t) * t) * t;
+}
+case 29: {
+double t = 2*y100 - 59;
+return 0.58702059496154081813e-1 + (0.13962391363223647892e-2 + (0.93714365487312784270e-5 + (0.58882975670265286526e-7 + (0.34414937110591753387e-9 + (0.18552853109751857859e-11 + 0.91160736711111111110e-14 * t) * t) * t) * t) * t) * t;
+}
+case 30: {
+double t = 2*y100 - 61;
+return 0.61532500145144778048e-1 + (0.14344426411912015247e-2 + (0.97331446201016809696e-5 + (0.61711860507347175097e-7 + (0.36325987418295300221e-9 + (0.19681183310134518232e-11 + 0.96952238400000000000e-14 * t) * t) * t) * t) * t) * t;
+}
+case 31: {
+double t = 2*y100 - 63;
+return 0.64440817576653297993e-1 + (0.14741275456383131151e-2 + (0.10112293819576437838e-4 + (0.64698236605933246196e-7 + (0.38353412915303665586e-9 + (0.20881176114385120186e-11 + 0.10310784480000000000e-13 * t) * t) * t) * t) * t) * t;
+}
+case 32: {
+double t = 2*y100 - 65;
+return 0.67430045633130393282e-1 + (0.15153655418916540370e-2 + (0.10509857606888328667e-4 + (0.67851706529363332855e-7 + (0.40504602194811140006e-9 + (0.22157325110542534469e-11 + 0.10964842115555555556e-13 * t) * t) * t) * t) * t) * t;
+}
+case 33: {
+double t = 2*y100 - 67;
+return 0.70503365513338850709e-1 + (0.15582323336495709827e-2 + (0.10926868866865231089e-4 + (0.71182482239613507542e-7 + (0.42787405890153386710e-9 + (0.23514379522274416437e-11 + 0.11659571751111111111e-13 * t) * t) * t) * t) * t) * t;
+}
+case 34: {
+double t = 2*y100 - 69;
+return 0.73664114037944596353e-1 + (0.16028078812438820413e-2 + (0.11364423678778207991e-4 + (0.74701423097423182009e-7 + (0.45210162777476488324e-9 + (0.24957355004088569134e-11 + 0.12397238257777777778e-13 * t) * t) * t) * t) * t) * t;
+}
+case 35: {
+double t = 2*y100 - 71;
+return 0.76915792420819562379e-1 + (0.16491766623447889354e-2 + (0.11823685320041302169e-4 + (0.78420075993781544386e-7 + (0.47781726956916478925e-9 + (0.26491544403815724749e-11 + 0.13180196462222222222e-13 * t) * t) * t) * t) * t) * t;
+}
+case 36: {
+double t = 2*y100 - 73;
+return 0.80262075578094612819e-1 + (0.16974279491709504117e-2 + (0.12305888517309891674e-4 + (0.82350717698979042290e-7 + (0.50511496109857113929e-9 + (0.28122528497626897696e-11 + 0.14010889635555555556e-13 * t) * t) * t) * t) * t) * t;
+}
+case 37: {
+double t = 2*y100 - 75;
+return 0.83706822008980357446e-1 + (0.17476561032212656962e-2 + (0.12812343958540763368e-4 + (0.86506399515036435592e-7 + (0.53409440823869467453e-9 + (0.29856186620887555043e-11 + 0.14891851591111111111e-13 * t) * t) * t) * t) * t) * t;
+}
+case 38: {
+double t = 2*y100 - 77;
+return 0.87254084284461718231e-1 + (0.17999608886001962327e-2 + (0.13344443080089492218e-4 + (0.90900994316429008631e-7 + (0.56486134972616465316e-9 + (0.31698707080033956934e-11 + 0.15825697795555555556e-13 * t) * t) * t) * t) * t) * t;
+}
+case 39: {
+double t = 2*y100 - 79;
+return 0.90908120182172748487e-1 + (0.18544478050657699758e-2 + (0.13903663143426120077e-4 + (0.95549246062549906177e-7 + (0.59752787125242054315e-9 + (0.33656597366099099413e-11 + 0.16815130613333333333e-13 * t) * t) * t) * t) * t) * t;
+}
+case 40: {
+double t = 2*y100 - 81;
+return 0.94673404508075481121e-1 + (0.19112284419887303347e-2 + (0.14491572616545004930e-4 + (0.10046682186333613697e-6 + (0.63221272959791000515e-9 + (0.35736693975589130818e-11 + 0.17862931591111111111e-13 * t) * t) * t) * t) * t) * t;
+}
+case 41: {
+double t = 2*y100 - 83;
+return 0.98554641648004456555e-1 + (0.19704208544725622126e-2 + (0.15109836875625443935e-4 + (0.10567036667675984067e-6 + (0.66904168640019354565e-9 + (0.37946171850824333014e-11 + 0.18971959040000000000e-13 * t) * t) * t) * t) * t) * t;
+}
+case 42: {
+double t = 2*y100 - 85;
+return 0.10255677889470089531e0 + (0.20321499629472857418e-2 + (0.15760224242962179564e-4 + (0.11117756071353507391e-6 + (0.70814785110097658502e-9 + (0.40292553276632563925e-11 + 0.20145143075555555556e-13 * t) * t) * t) * t) * t) * t;
+}
+case 43: {
+double t = 2*y100 - 87;
+return 0.10668502059865093318e0 + (0.20965479776148731610e-2 + (0.16444612377624983565e-4 + (0.11700717962026152749e-6 + (0.74967203250938418991e-9 + (0.42783716186085922176e-11 + 0.21385479360000000000e-13 * t) * t) * t) * t) * t) * t;
+}
+case 44: {
+double t = 2*y100 - 89;
+return 0.11094484319386444474e0 + (0.21637548491908170841e-2 + (0.17164995035719657111e-4 + (0.12317915750735938089e-6 + (0.79376309831499633734e-9 + (0.45427901763106353914e-11 + 0.22696025653333333333e-13 * t) * t) * t) * t) * t) * t;
+}
+case 45: {
+double t = 2*y100 - 91;
+return 0.11534201115268804714e0 + (0.22339187474546420375e-2 + (0.17923489217504226813e-4 + (0.12971465288245997681e-6 + (0.84057834180389073587e-9 + (0.48233721206418027227e-11 + 0.24079890062222222222e-13 * t) * t) * t) * t) * t) * t;
+}
+case 46: {
+double t = 2*y100 - 93;
+return 0.11988259392684094740e0 + (0.23071965691918689601e-2 + (0.18722342718958935446e-4 + (0.13663611754337957520e-6 + (0.89028385488493287005e-9 + (0.51210161569225846701e-11 + 0.25540227111111111111e-13 * t) * t) * t) * t) * t) * t;
+}
+case 47: {
+double t = 2*y100 - 95;
+return 0.12457298393509812907e0 + (0.23837544771809575380e-2 + (0.19563942105711612475e-4 + (0.14396736847739470782e-6 + (0.94305490646459247016e-9 + (0.54366590583134218096e-11 + 0.27080225920000000000e-13 * t) * t) * t) * t) * t) * t;
+}
+case 48: {
+double t = 2*y100 - 97;
+return 0.12941991566142438816e0 + (0.24637684719508859484e-2 + (0.20450821127475879816e-4 + (0.15173366280523906622e-6 + (0.99907632506389027739e-9 + (0.57712760311351625221e-11 + 0.28703099555555555556e-13 * t) * t) * t) * t) * t) * t;
+}
+case 49: {
+double t = 2*y100 - 99;
+return 0.13443048593088696613e0 + (0.25474249981080823877e-2 + (0.21385669591362915223e-4 + (0.15996177579900443030e-6 + (0.10585428844575134013e-8 + (0.61258809536787882989e-11 + 0.30412080142222222222e-13 * t) * t) * t) * t) * t) * t;
+}
+case 50: {
+double t = 2*y100 - 101;
+return 0.13961217543434561353e0 + (0.26349215871051761416e-2 + (0.22371342712572567744e-4 + (0.16868008199296822247e-6 + (0.11216596910444996246e-8 + (0.65015264753090890662e-11 + 0.32210394506666666666e-13 * t) * t) * t) * t) * t) * t;
+}
+case 51: {
+double t = 2*y100 - 103;
+return 0.14497287157673800690e0 + (0.27264675383982439814e-2 + (0.23410870961050950197e-4 + (0.17791863939526376477e-6 + (0.11886425714330958106e-8 + (0.68993039665054288034e-11 + 0.34101266222222222221e-13 * t) * t) * t) * t) * t) * t;
+}
+case 52: {
+double t = 2*y100 - 105;
+return 0.15052089272774618151e0 + (0.28222846410136238008e-2 + (0.24507470422713397006e-4 + (0.18770927679626136909e-6 + (0.12597184587583370712e-8 + (0.73203433049229821618e-11 + 0.36087889048888888890e-13 * t) * t) * t) * t) * t) * t;
+}
+case 53: {
+double t = 2*y100 - 107;
+return 0.15626501395774612325e0 + (0.29226079376196624949e-2 + (0.25664553693768450545e-4 + (0.19808568415654461964e-6 + (0.13351257759815557897e-8 + (0.77658124891046760667e-11 + 0.38173420035555555555e-13 * t) * t) * t) * t) * t) * t;
+}
+case 54: {
+double t = 2*y100 - 109;
+return 0.16221449434620737567e0 + (0.30276865332726475672e-2 + (0.26885741326534564336e-4 + (0.20908350604346384143e-6 + (0.14151148144240728728e-8 + (0.82369170665974313027e-11 + 0.40360957457777777779e-13 * t) * t) * t) * t) * t) * t;
+}
+case 55: {
+double t = 2*y100 - 111;
+return 0.16837910595412130659e0 + (0.31377844510793082301e-2 + (0.28174873844911175026e-4 + (0.22074043807045782387e-6 + (0.14999481055996090039e-8 + (0.87348993661930809254e-11 + 0.42653528977777777779e-13 * t) * t) * t) * t) * t) * t;
+}
+case 56: {
+double t = 2*y100 - 113;
+return 0.17476916455659369953e0 + (0.32531815370903068316e-2 + (0.29536024347344364074e-4 + (0.23309632627767074202e-6 + (0.15899007843582444846e-8 + (0.92610375235427359475e-11 + 0.45054073102222222221e-13 * t) * t) * t) * t) * t) * t;
+}
+case 57: {
+double t = 2*y100 - 115;
+return 0.18139556223643701364e0 + (0.33741744168096996041e-2 + (0.30973511714709500836e-4 + (0.24619326937592290996e-6 + (0.16852609412267750744e-8 + (0.98166442942854895573e-11 + 0.47565418097777777779e-13 * t) * t) * t) * t) * t) * t;
+}
+case 58: {
+double t = 2*y100 - 117;
+return 0.18826980194443664549e0 + (0.35010775057740317997e-2 + (0.32491914440014267480e-4 + (0.26007572375886319028e-6 + (0.17863299617388376116e-8 + (0.10403065638343878679e-10 + 0.50190265831111111110e-13 * t) * t) * t) * t) * t) * t;
+}
+case 59: {
+double t = 2*y100 - 119;
+return 0.19540403413693967350e0 + (0.36342240767211326315e-2 + (0.34096085096200907289e-4 + (0.27479061117017637474e-6 + (0.18934228504790032826e-8 + (0.11021679075323598664e-10 + 0.52931171733333333334e-13 * t) * t) * t) * t) * t) * t;
+}
+case 60: {
+double t = 2*y100 - 121;
+return 0.20281109560651886959e0 + (0.37739673859323597060e-2 + (0.35791165457592409054e-4 + (0.29038742889416172404e-6 + (0.20068685374849001770e-8 + (0.11673891799578381999e-10 + 0.55790523093333333334e-13 * t) * t) * t) * t) * t) * t;
+}
+case 61: {
+double t = 2*y100 - 123;
+return 0.21050455062669334978e0 + (0.39206818613925652425e-2 + (0.37582602289680101704e-4 + (0.30691836231886877385e-6 + (0.21270101645763677824e-8 + (0.12361138551062899455e-10 + 0.58770520160000000000e-13 * t) * t) * t) * t) * t) * t;
+}
+case 62: {
+double t = 2*y100 - 125;
+return 0.21849873453703332479e0 + (0.40747643554689586041e-2 + (0.39476163820986711501e-4 + (0.32443839970139918836e-6 + (0.22542053491518680200e-8 + (0.13084879235290858490e-10 + 0.61873153262222222221e-13 * t) * t) * t) * t) * t) * t;
+}
+case 63: {
+double t = 2*y100 - 127;
+return 0.22680879990043229327e0 + (0.42366354648628516935e-2 + (0.41477956909656896779e-4 + (0.34300544894502810002e-6 + (0.23888264229264067658e-8 + (0.13846596292818514601e-10 + 0.65100183751111111110e-13 * t) * t) * t) * t) * t) * t;
+}
+case 64: {
+double t = 2*y100 - 129;
+return 0.23545076536988703937e0 + (0.44067409206365170888e-2 + (0.43594444916224700881e-4 + (0.36268045617760415178e-6 + (0.25312606430853202748e-8 + (0.14647791812837903061e-10 + 0.68453122631111111110e-13 * t) * t) * t) * t) * t) * t;
+}
+case 65: {
+double t = 2*y100 - 131;
+return 0.24444156740777432838e0 + (0.45855530511605787178e-2 + (0.45832466292683085475e-4 + (0.38352752590033030472e-6 + (0.26819103733055603460e-8 + (0.15489984390884756993e-10 + 0.71933206364444444445e-13 * t) * t) * t) * t) * t) * t;
+}
+case 66: {
+double t = 2*y100 - 133;
+return 0.25379911500634264643e0 + (0.47735723208650032167e-2 + (0.48199253896534185372e-4 + (0.40561404245564732314e-6 + (0.28411932320871165585e-8 + (0.16374705736458320149e-10 + 0.75541379822222222221e-13 * t) * t) * t) * t) * t) * t;
+}
+case 67: {
+double t = 2*y100 - 135;
+return 0.26354234756393613032e0 + (0.49713289477083781266e-2 + (0.50702455036930367504e-4 + (0.42901079254268185722e-6 + (0.30095422058900481753e-8 + (0.17303497025347342498e-10 + 0.79278273368888888890e-13 * t) * t) * t) * t) * t) * t;
+}
+case 68: {
+double t = 2*y100 - 137;
+return 0.27369129607732343398e0 + (0.51793846023052643767e-2 + (0.53350152258326602629e-4 + (0.45379208848865015485e-6 + (0.31874057245814381257e-8 + (0.18277905010245111046e-10 + 0.83144182364444444445e-13 * t) * t) * t) * t) * t) * t;
+}
+case 69: {
+double t = 2*y100 - 139;
+return 0.28426714781640316172e0 + (0.53983341916695141966e-2 + (0.56150884865255810638e-4 + (0.48003589196494734238e-6 + (0.33752476967570796349e-8 + (0.19299477888083469086e-10 + 0.87139049137777777779e-13 * t) * t) * t) * t) * t) * t;
+}
+case 70: {
+double t = 2*y100 - 141;
+return 0.29529231465348519920e0 + (0.56288077305420795663e-2 + (0.59113671189913307427e-4 + (0.50782393781744840482e-6 + (0.35735475025851713168e-8 + (0.20369760937017070382e-10 + 0.91262442613333333334e-13 * t) * t) * t) * t) * t) * t;
+}
+case 71: {
+double t = 2*y100 - 143;
+return 0.30679050522528838613e0 + (0.58714723032745403331e-2 + (0.62248031602197686791e-4 + (0.53724185766200945789e-6 + (0.37827999418960232678e-8 + (0.21490291930444538307e-10 + 0.95513539182222222221e-13 * t) * t) * t) * t) * t) * t;
+}
+case 72: {
+double t = 2*y100 - 145;
+return 0.31878680111173319425e0 + (0.61270341192339103514e-2 + (0.65564012259707640976e-4 + (0.56837930287837738996e-6 + (0.40035151353392378882e-8 + (0.22662596341239294792e-10 + 0.99891109760000000000e-13 * t) * t) * t) * t) * t) * t;
+}
+case 73: {
+double t = 2*y100 - 147;
+return 0.33130773722152622027e0 + (0.63962406646798080903e-2 + (0.69072209592942396666e-4 + (0.60133006661885941812e-6 + (0.42362183765883466691e-8 + (0.23888182347073698382e-10 + 0.10439349811555555556e-12 * t) * t) * t) * t) * t) * t;
+}
+case 74: {
+double t = 2*y100 - 149;
+return 0.34438138658041336523e0 + (0.66798829540414007258e-2 + (0.72783795518603561144e-4 + (0.63619220443228800680e-6 + (0.44814499336514453364e-8 + (0.25168535651285475274e-10 + 0.10901861383111111111e-12 * t) * t) * t) * t) * t) * t;
+}
+case 75: {
+double t = 2*y100 - 151;
+return 0.35803744972380175583e0 + (0.69787978834882685031e-2 + (0.76710543371454822497e-4 + (0.67306815308917386747e-6 + (0.47397647975845228205e-8 + (0.26505114141143050509e-10 + 0.11376390933333333333e-12 * t) * t) * t) * t) * t) * t;
+}
+case 76: {
+double t = 2*y100 - 153;
+return 0.37230734890119724188e0 + (0.72938706896461381003e-2 + (0.80864854542670714092e-4 + (0.71206484718062688779e-6 + (0.50117323769745883805e-8 + (0.27899342394100074165e-10 + 0.11862637614222222222e-12 * t) * t) * t) * t) * t) * t;
+}
+case 77: {
+double t = 2*y100 - 155;
+return 0.38722432730555448223e0 + (0.76260375162549802745e-2 + (0.85259785810004603848e-4 + (0.75329383305171327677e-6 + (0.52979361368388119355e-8 + (0.29352606054164086709e-10 + 0.12360253370666666667e-12 * t) * t) * t) * t) * t) * t;
+}
+case 78: {
+double t = 2*y100 - 157;
+return 0.40282355354616940667e0 + (0.79762880915029728079e-2 + (0.89909077342438246452e-4 + (0.79687137961956194579e-6 + (0.55989731807360403195e-8 + (0.30866246101464869050e-10 + 0.12868841946666666667e-12 * t) * t) * t) * t) * t) * t;
+}
+case 79: {
+double t = 2*y100 - 159;
+return 0.41914223158913787649e0 + (0.83456685186950463538e-2 + (0.94827181359250161335e-4 + (0.84291858561783141014e-6 + (0.59154537751083485684e-8 + (0.32441553034347469291e-10 + 0.13387957943111111111e-12 * t) * t) * t) * t) * t) * t;
+}
+case 80: {
+double t = 2*y100 - 161;
+return 0.43621971639463786896e0 + (0.87352841828289495773e-2 + (0.10002929142066799966e-3 + (0.89156148280219880024e-6 + (0.62480008150788597147e-8 + (0.34079760983458878910e-10 + 0.13917107176888888889e-12 * t) * t) * t) * t) * t) * t;
+}
+case 81: {
+double t = 2*y100 - 163;
+return 0.45409763548534330981e0 + (0.91463027755548240654e-2 + (0.10553137232446167258e-3 + (0.94293113464638623798e-6 + (0.65972492312219959885e-8 + (0.35782041795476563662e-10 + 0.14455745872000000000e-12 * t) * t) * t) * t) * t) * t;
+}
+case 82: {
+double t = 2*y100 - 165;
+return 0.47282001668512331468e0 + (0.95799574408860463394e-2 + (0.11135019058000067469e-3 + (0.99716373005509038080e-6 + (0.69638453369956970347e-8 + (0.37549499088161345850e-10 + 0.15003280712888888889e-12 * t) * t) * t) * t) * t) * t;
+}
+case 83: {
+double t = 2*y100 - 167;
+return 0.49243342227179841649e0 + (0.10037550043909497071e-1 + (0.11750334542845234952e-3 + (0.10544006716188967172e-5 + (0.73484461168242224872e-8 + (0.39383162326435752965e-10 + 0.15559069118222222222e-12 * t) * t) * t) * t) * t) * t;
+}
+case 84: {
+double t = 2*y100 - 169;
+return 0.51298708979209258326e0 + (0.10520454564612427224e-1 + (0.12400930037494996655e-3 + (0.11147886579371265246e-5 + (0.77517184550568711454e-8 + (0.41283980931872622611e-10 + 0.16122419680000000000e-12 * t) * t) * t) * t) * t) * t;
+}
+case 85: {
+double t = 2*y100 - 171;
+return 0.53453307979101369843e0 + (0.11030120618800726938e-1 + (0.13088741519572269581e-3 + (0.11784797595374515432e-5 + (0.81743383063044825400e-8 + (0.43252818449517081051e-10 + 0.16692592640000000000e-12 * t) * t) * t) * t) * t) * t;
+}
+case 86: {
+double t = 2*y100 - 173;
+return 0.55712643071169299478e0 + (0.11568077107929735233e-1 + (0.13815797838036651289e-3 + (0.12456314879260904558e-5 + (0.86169898078969313597e-8 + (0.45290446811539652525e-10 + 0.17268801084444444444e-12 * t) * t) * t) * t) * t) * t;
+}
+case 87: {
+double t = 2*y100 - 175;
+return 0.58082532122519320968e0 + (0.12135935999503877077e-1 + (0.14584223996665838559e-3 + (0.13164068573095710742e-5 + (0.90803643355106020163e-8 + (0.47397540713124619155e-10 + 0.17850211608888888889e-12 * t) * t) * t) * t) * t) * t;
+}
+case 88: {
+double t = 2*y100 - 177;
+return 0.60569124025293375554e0 + (0.12735396239525550361e-1 + (0.15396244472258863344e-3 + (0.13909744385382818253e-5 + (0.95651595032306228245e-8 + (0.49574672127669041550e-10 + 0.18435945564444444444e-12 * t) * t) * t) * t) * t) * t;
+}
+case 89: {
+double t = 2*y100 - 179;
+return 0.63178916494715716894e0 + (0.13368247798287030927e-1 + (0.16254186562762076141e-3 + (0.14695084048334056083e-5 + (0.10072078109604152350e-7 + (0.51822304995680707483e-10 + 0.19025081422222222222e-12 * t) * t) * t) * t) * t) * t;
+}
+case 90: {
+double t = 2*y100 - 181;
+return 0.65918774689725319200e0 + (0.14036375850601992063e-1 + (0.17160483760259706354e-3 + (0.15521885688723188371e-5 + (0.10601827031535280590e-7 + (0.54140790105837520499e-10 + 0.19616655146666666667e-12 * t) * t) * t) * t) * t) * t;
+}
+case 91: {
+double t = 2*y100 - 183;
+return 0.68795950683174433822e0 + (0.14741765091365869084e-1 + (0.18117679143520433835e-3 + (0.16392004108230585213e-5 + (0.11155116068018043001e-7 + (0.56530360194925690374e-10 + 0.20209663662222222222e-12 * t) * t) * t) * t) * t) * t;
+}
+case 92: {
+double t = 2*y100 - 185;
+return 0.71818103808729967036e0 + (0.15486504187117112279e-1 + (0.19128428784550923217e-3 + (0.17307350969359975848e-5 + (0.11732656736113607751e-7 + (0.58991125287563833603e-10 + 0.20803065333333333333e-12 * t) * t) * t) * t) * t) * t;
+}
+case 93: {
+double t = 2*y100 - 187;
+return 0.74993321911726254661e0 + (0.16272790364044783382e-1 + (0.20195505163377912645e-3 + (0.18269894883203346953e-5 + (0.12335161021630225535e-7 + (0.61523068312169087227e-10 + 0.21395783431111111111e-12 * t) * t) * t) * t) * t) * t;
+}
+case 94: {
+double t = 2*y100 - 189;
+return 0.78330143531283492729e0 + (0.17102934132652429240e-1 + (0.21321800585063327041e-3 + (0.19281661395543913713e-5 + (0.12963340087354341574e-7 + (0.64126040998066348872e-10 + 0.21986708942222222222e-12 * t) * t) * t) * t) * t) * t;
+}
+case 95: {
+double t = 2*y100 - 191;
+return 0.81837581041023811832e0 + (0.17979364149044223802e-1 + (0.22510330592753129006e-3 + (0.20344732868018175389e-5 + (0.13617902941839949718e-7 + (0.66799760083972474642e-10 + 0.22574701262222222222e-12 * t) * t) * t) * t) * t) * t;
+}
+case 96: {
+double t = 2*y100 - 193;
+return 0.85525144775685126237e0 + (0.18904632212547561026e-1 + (0.23764237370371255638e-3 + (0.21461248251306387979e-5 + (0.14299555071870523786e-7 + (0.69543803864694171934e-10 + 0.23158593688888888889e-12 * t) * t) * t) * t) * t) * t;
+}
+case 97: {
+double t = 2*y100 - 195;
+return 0.89402868170849933734e0 + (0.19881418399127202569e-1 + (0.25086793128395995798e-3 + (0.22633402747585233180e-5 + (0.15008997042116532283e-7 + (0.72357609075043941261e-10 + 0.23737194737777777778e-12 * t) * t) * t) * t) * t) * t;
+}
+case 98: {
+double t = 2*y100 - 197;
+return 0.93481333942870796363e0 + (0.20912536329780368893e-1 + (0.26481403465998477969e-3 + (0.23863447359754921676e-5 + (0.15746923065472184451e-7 + (0.75240468141720143653e-10 + 0.24309291271111111111e-12 * t) * t) * t) * t) * t) * t;
+}
+case 99: {
+double t = 2*y100 - 199;
+return 0.97771701335885035464e0 + (0.22000938572830479551e-1 + (0.27951610702682383001e-3 + (0.25153688325245314530e-5 + (0.16514019547822821453e-7 + (0.78191526829368231251e-10 + 0.24873652355555555556e-12 * t) * t) * t) * t) * t) * t;
+}
+  }
+  // we only get here if y = 1, i.e. |x| < 4*eps, in which case
+  // erfcx is within 1e-15 of 1..
+  return 1.0;
+}
+
+double FADDEEVA_RE(erfcx)(double x)
+{
+  if (x >= 0) {
+    if (x > 50) { // continued-fraction expansion is faster
+      const double ispi = 0.56418958354775628694807945156; // 1 / sqrt(pi)
+      if (x > 5e7) // 1-term expansion, important to avoid overflow
+        return ispi / x;
+      /* 5-term expansion (rely on compiler for CSE), simplified from:
+                ispi / (x+0.5/(x+1/(x+1.5/(x+2/x))))  */
+      return ispi*((x*x) * (x*x+4.5) + 2) / (x * ((x*x) * (x*x+5) + 3.75));
+    }
+    return erfcx_y100(400/(4+x));
+  }
+  else
+    return x < -26.7 ? HUGE_VAL : (x < -6.1 ? 2*exp(x*x) 
+                                   : 2*exp(x*x) - erfcx_y100(400/(4-x)));
+}
+
+/////////////////////////////////////////////////////////////////////////
+/* Compute a scaled Dawson integral 
+            FADDEEVA(w_im)(x) = 2*Dawson(x)/sqrt(pi)
+   equivalent to the imaginary part w(x) for real x.
+
+   Uses methods similar to the erfcx calculation above: continued fractions
+   for large |x|, a lookup table of Chebyshev polynomials for smaller |x|,
+   and finally a Taylor expansion for |x|<0.01.
+   
+   Steven G. Johnson, October 2012. */
+
+/* Given y100=100*y, where y = 1/(1+x) for x >= 0, compute w_im(x).
+
+   Uses a look-up table of 100 different Chebyshev polynomials
+   for y intervals [0,0.01], [0.01,0.02], ...., [0.99,1], generated
+   with the help of Maple and a little shell script.   This allows
+   the Chebyshev polynomials to be of significantly lower degree (about 1/30)
+   compared to fitting the whole [0,1] interval with a single polynomial. */
+static double w_im_y100(double y100, double x) {
+  switch ((int) y100) {
+    case 0: {
+      double t = 2*y100 - 1;
+      return 0.28351593328822191546e-2 + (0.28494783221378400759e-2 + (0.14427470563276734183e-4 + (0.10939723080231588129e-6 + (0.92474307943275042045e-9 + (0.89128907666450075245e-11 + 0.92974121935111111110e-13 * t) * t) * t) * t) * t) * t;
+    }
+    case 1: {
+      double t = 2*y100 - 3;
+      return 0.85927161243940350562e-2 + (0.29085312941641339862e-2 + (0.15106783707725582090e-4 + (0.11716709978531327367e-6 + (0.10197387816021040024e-8 + (0.10122678863073360769e-10 + 0.10917479678400000000e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 2: {
+      double t = 2*y100 - 5;
+      return 0.14471159831187703054e-1 + (0.29703978970263836210e-2 + (0.15835096760173030976e-4 + (0.12574803383199211596e-6 + (0.11278672159518415848e-8 + (0.11547462300333495797e-10 + 0.12894535335111111111e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 3: {
+      double t = 2*y100 - 7;
+      return 0.20476320420324610618e-1 + (0.30352843012898665856e-2 + (0.16617609387003727409e-4 + (0.13525429711163116103e-6 + (0.12515095552507169013e-8 + (0.13235687543603382345e-10 + 0.15326595042666666667e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 4: {
+      double t = 2*y100 - 9;
+      return 0.26614461952489004566e-1 + (0.31034189276234947088e-2 + (0.17460268109986214274e-4 + (0.14582130824485709573e-6 + (0.13935959083809746345e-8 + (0.15249438072998932900e-10 + 0.18344741882133333333e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 5: {
+      double t = 2*y100 - 11;
+      return 0.32892330248093586215e-1 + (0.31750557067975068584e-2 + (0.18369907582308672632e-4 + (0.15761063702089457882e-6 + (0.15577638230480894382e-8 + (0.17663868462699097951e-10 + (0.22126732680711111111e-12 + 0.30273474177737853668e-14 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 6: {
+      double t = 2*y100 - 13;
+      return 0.39317207681134336024e-1 + (0.32504779701937539333e-2 + (0.19354426046513400534e-4 + (0.17081646971321290539e-6 + (0.17485733959327106250e-8 + (0.20593687304921961410e-10 + (0.26917401949155555556e-12 + 0.38562123837725712270e-14 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 7: {
+      double t = 2*y100 - 15;
+      return 0.45896976511367738235e-1 + (0.33300031273110976165e-2 + (0.20423005398039037313e-4 + (0.18567412470376467303e-6 + (0.19718038363586588213e-8 + (0.24175006536781219807e-10 + (0.33059982791466666666e-12 + 0.49756574284439426165e-14 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 8: {
+      double t = 2*y100 - 17;
+      return 0.52640192524848962855e-1 + (0.34139883358846720806e-2 + (0.21586390240603337337e-4 + (0.20247136501568904646e-6 + (0.22348696948197102935e-8 + (0.28597516301950162548e-10 + (0.41045502119111111110e-12 + 0.65151614515238361946e-14 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 9: {
+      double t = 2*y100 - 19;
+      return 0.59556171228656770456e-1 + (0.35028374386648914444e-2 + (0.22857246150998562824e-4 + (0.22156372146525190679e-6 + (0.25474171590893813583e-8 + (0.34122390890697400584e-10 + (0.51593189879111111110e-12 + 0.86775076853908006938e-14 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 10: {
+      double t = 2*y100 - 21;
+      return 0.66655089485108212551e-1 + (0.35970095381271285568e-2 + (0.24250626164318672928e-4 + (0.24339561521785040536e-6 + (0.29221990406518411415e-8 + (0.41117013527967776467e-10 + (0.65786450716444444445e-12 + 0.11791885745450623331e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 11: {
+      double t = 2*y100 - 23;
+      return 0.73948106345519174661e-1 + (0.36970297216569341748e-2 + (0.25784588137312868792e-4 + (0.26853012002366752770e-6 + (0.33763958861206729592e-8 + (0.50111549981376976397e-10 + (0.85313857496888888890e-12 + 0.16417079927706899860e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 12: {
+      double t = 2*y100 - 25;
+      return 0.81447508065002963203e-1 + (0.38035026606492705117e-2 + (0.27481027572231851896e-4 + (0.29769200731832331364e-6 + (0.39336816287457655076e-8 + (0.61895471132038157624e-10 + (0.11292303213511111111e-11 + 0.23558532213703884304e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 13: {
+      double t = 2*y100 - 27;
+      return 0.89166884027582716628e-1 + (0.39171301322438946014e-2 + (0.29366827260422311668e-4 + (0.33183204390350724895e-6 + (0.46276006281647330524e-8 + (0.77692631378169813324e-10 + (0.15335153258844444444e-11 + 0.35183103415916026911e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 14: {
+      double t = 2*y100 - 29;
+      return 0.97121342888032322019e-1 + (0.40387340353207909514e-2 + (0.31475490395950776930e-4 + (0.37222714227125135042e-6 + (0.55074373178613809996e-8 + (0.99509175283990337944e-10 + (0.21552645758222222222e-11 + 0.55728651431872687605e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 15: {
+      double t = 2*y100 - 31;
+      return 0.10532778218603311137e0 + (0.41692873614065380607e-2 + (0.33849549774889456984e-4 + (0.42064596193692630143e-6 + (0.66494579697622432987e-8 + (0.13094103581931802337e-9 + (0.31896187409777777778e-11 + 0.97271974184476560742e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 16: {
+      double t = 2*y100 - 33;
+      return 0.11380523107427108222e0 + (0.43099572287871821013e-2 + (0.36544324341565929930e-4 + (0.47965044028581857764e-6 + (0.81819034238463698796e-8 + (0.17934133239549647357e-9 + (0.50956666166186293627e-11 + (0.18850487318190638010e-12 + 0.79697813173519853340e-14 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 17: {
+      double t = 2*y100 - 35;
+      return 0.12257529703447467345e0 + (0.44621675710026986366e-2 + (0.39634304721292440285e-4 + (0.55321553769873381819e-6 + (0.10343619428848520870e-7 + (0.26033830170470368088e-9 + (0.87743837749108025357e-11 + (0.34427092430230063401e-12 + 0.10205506615709843189e-13 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 18: {
+      double t = 2*y100 - 37;
+      return 0.13166276955656699478e0 + (0.46276970481783001803e-2 + (0.43225026380496399310e-4 + (0.64799164020016902656e-6 + (0.13580082794704641782e-7 + (0.39839800853954313927e-9 + (0.14431142411840000000e-10 + 0.42193457308830027541e-12 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 19: {
+      double t = 2*y100 - 39;
+      return 0.14109647869803356475e0 + (0.48088424418545347758e-2 + (0.47474504753352150205e-4 + (0.77509866468724360352e-6 + (0.18536851570794291724e-7 + (0.60146623257887570439e-9 + (0.18533978397305276318e-10 + (0.41033845938901048380e-13 - 0.46160680279304825485e-13 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 20: {
+      double t = 2*y100 - 41;
+      return 0.15091057940548936603e0 + (0.50086864672004685703e-2 + (0.52622482832192230762e-4 + (0.95034664722040355212e-6 + (0.25614261331144718769e-7 + (0.80183196716888606252e-9 + (0.12282524750534352272e-10 + (-0.10531774117332273617e-11 - 0.86157181395039646412e-13 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 21: {
+      double t = 2*y100 - 43;
+      return 0.16114648116017010770e0 + (0.52314661581655369795e-2 + (0.59005534545908331315e-4 + (0.11885518333915387760e-5 + (0.33975801443239949256e-7 + (0.82111547144080388610e-9 + (-0.12357674017312854138e-10 + (-0.24355112256914479176e-11 - 0.75155506863572930844e-13 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 22: {
+      double t = 2*y100 - 45;
+      return 0.17185551279680451144e0 + (0.54829002967599420860e-2 + (0.67013226658738082118e-4 + (0.14897400671425088807e-5 + (0.40690283917126153701e-7 + (0.44060872913473778318e-9 + (-0.52641873433280000000e-10 - 0.30940587864543343124e-11 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 23: {
+      double t = 2*y100 - 47;
+      return 0.18310194559815257381e0 + (0.57701559375966953174e-2 + (0.76948789401735193483e-4 + (0.18227569842290822512e-5 + (0.41092208344387212276e-7 + (-0.44009499965694442143e-9 + (-0.92195414685628803451e-10 + (-0.22657389705721753299e-11 + 0.10004784908106839254e-12 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 24: {
+      double t = 2*y100 - 49;
+      return 0.19496527191546630345e0 + (0.61010853144364724856e-2 + (0.88812881056342004864e-4 + (0.21180686746360261031e-5 + (0.30652145555130049203e-7 + (-0.16841328574105890409e-8 + (-0.11008129460612823934e-9 + (-0.12180794204544515779e-12 + 0.15703325634590334097e-12 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 25: {
+      double t = 2*y100 - 51;
+      return 0.20754006813966575720e0 + (0.64825787724922073908e-2 + (0.10209599627522311893e-3 + (0.22785233392557600468e-5 + (0.73495224449907568402e-8 + (-0.29442705974150112783e-8 + (-0.94082603434315016546e-10 + (0.23609990400179321267e-11 + 0.14141908654269023788e-12 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 26: {
+      double t = 2*y100 - 53;
+      return 0.22093185554845172146e0 + (0.69182878150187964499e-2 + (0.11568723331156335712e-3 + (0.22060577946323627739e-5 + (-0.26929730679360840096e-7 + (-0.38176506152362058013e-8 + (-0.47399503861054459243e-10 + (0.40953700187172127264e-11 + 0.69157730376118511127e-13 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 27: {
+      double t = 2*y100 - 55;
+      return 0.23524827304057813918e0 + (0.74063350762008734520e-2 + (0.12796333874615790348e-3 + (0.18327267316171054273e-5 + (-0.66742910737957100098e-7 + (-0.40204740975496797870e-8 + (0.14515984139495745330e-10 + (0.44921608954536047975e-11 - 0.18583341338983776219e-13 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 28: {
+      double t = 2*y100 - 57;
+      return 0.25058626331812744775e0 + (0.79377285151602061328e-2 + (0.13704268650417478346e-3 + (0.11427511739544695861e-5 + (-0.10485442447768377485e-6 + (-0.34850364756499369763e-8 + (0.72656453829502179208e-10 + (0.36195460197779299406e-11 - 0.84882136022200714710e-13 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 29: {
+      double t = 2*y100 - 59;
+      return 0.26701724900280689785e0 + (0.84959936119625864274e-2 + (0.14112359443938883232e-3 + (0.17800427288596909634e-6 + (-0.13443492107643109071e-6 + (-0.23512456315677680293e-8 + (0.11245846264695936769e-9 + (0.19850501334649565404e-11 - 0.11284666134635050832e-12 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 30: {
+      double t = 2*y100 - 61;
+      return 0.28457293586253654144e0 + (0.90581563892650431899e-2 + (0.13880520331140646738e-3 + (-0.97262302362522896157e-6 + (-0.15077100040254187366e-6 + (-0.88574317464577116689e-9 + (0.12760311125637474581e-9 + (0.20155151018282695055e-12 - 0.10514169375181734921e-12 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 31: {
+      double t = 2*y100 - 63;
+      return 0.30323425595617385705e0 + (0.95968346790597422934e-2 + (0.12931067776725883939e-3 + (-0.21938741702795543986e-5 + (-0.15202888584907373963e-6 + (0.61788350541116331411e-9 + (0.11957835742791248256e-9 + (-0.12598179834007710908e-11 - 0.75151817129574614194e-13 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 32: {
+      double t = 2*y100 - 65;
+      return 0.32292521181517384379e0 + (0.10082957727001199408e-1 + (0.11257589426154962226e-3 + (-0.33670890319327881129e-5 + (-0.13910529040004008158e-6 + (0.19170714373047512945e-8 + (0.94840222377720494290e-10 + (-0.21650018351795353201e-11 - 0.37875211678024922689e-13 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 33: {
+      double t = 2*y100 - 67;
+      return 0.34351233557911753862e0 + (0.10488575435572745309e-1 + (0.89209444197248726614e-4 + (-0.43893459576483345364e-5 + (-0.11488595830450424419e-6 + (0.28599494117122464806e-8 + (0.61537542799857777779e-10 - 0.24935749227658002212e-11 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 34: {
+      double t = 2*y100 - 69;
+      return 0.36480946642143669093e0 + (0.10789304203431861366e-1 + (0.60357993745283076834e-4 + (-0.51855862174130669389e-5 + (-0.83291664087289801313e-7 + (0.33898011178582671546e-8 + (0.27082948188277716482e-10 + (-0.23603379397408694974e-11 + 0.19328087692252869842e-13 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 35: {
+      double t = 2*y100 - 71;
+      return 0.38658679935694939199e0 + (0.10966119158288804999e-1 + (0.27521612041849561426e-4 + (-0.57132774537670953638e-5 + (-0.48404772799207914899e-7 + (0.35268354132474570493e-8 + (-0.32383477652514618094e-11 + (-0.19334202915190442501e-11 + 0.32333189861286460270e-13 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 36: {
+      double t = 2*y100 - 73;
+      return 0.40858275583808707870e0 + (0.11006378016848466550e-1 + (-0.76396376685213286033e-5 + (-0.59609835484245791439e-5 + (-0.13834610033859313213e-7 + (0.33406952974861448790e-8 + (-0.26474915974296612559e-10 + (-0.13750229270354351983e-11 + 0.36169366979417390637e-13 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 37: {
+      double t = 2*y100 - 75;
+      return 0.43051714914006682977e0 + (0.10904106549500816155e-1 + (-0.43477527256787216909e-4 + (-0.59429739547798343948e-5 + (0.17639200194091885949e-7 + (0.29235991689639918688e-8 + (-0.41718791216277812879e-10 + (-0.81023337739508049606e-12 + 0.33618915934461994428e-13 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 38: {
+      double t = 2*y100 - 77;
+      return 0.45210428135559607406e0 + (0.10659670756384400554e-1 + (-0.78488639913256978087e-4 + (-0.56919860886214735936e-5 + (0.44181850467477733407e-7 + (0.23694306174312688151e-8 + (-0.49492621596685443247e-10 + (-0.31827275712126287222e-12 + 0.27494438742721623654e-13 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 39: {
+      double t = 2*y100 - 79;
+      return 0.47306491195005224077e0 + (0.10279006119745977570e-1 + (-0.11140268171830478306e-3 + (-0.52518035247451432069e-5 + (0.64846898158889479518e-7 + (0.17603624837787337662e-8 + (-0.51129481592926104316e-10 + (0.62674584974141049511e-13 + 0.20055478560829935356e-13 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 40: {
+      double t = 2*y100 - 81;
+      return 0.49313638965719857647e0 + (0.97725799114772017662e-2 + (-0.14122854267291533334e-3 + (-0.46707252568834951907e-5 + (0.79421347979319449524e-7 + (0.11603027184324708643e-8 + (-0.48269605844397175946e-10 + (0.32477251431748571219e-12 + 0.12831052634143527985e-13 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 41: {
+      double t = 2*y100 - 83;
+      return 0.51208057433416004042e0 + (0.91542422354009224951e-2 + (-0.16726530230228647275e-3 + (-0.39964621752527649409e-5 + (0.88232252903213171454e-7 + (0.61343113364949928501e-9 + (-0.42516755603130443051e-10 + (0.47910437172240209262e-12 + 0.66784341874437478953e-14 * t) * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 42: {
+      double t = 2*y100 - 85;
+      return 0.52968945458607484524e0 + (0.84400880445116786088e-2 + (-0.18908729783854258774e-3 + (-0.32725905467782951931e-5 + (0.91956190588652090659e-7 + (0.14593989152420122909e-9 + (-0.35239490687644444445e-10 + 0.54613829888448694898e-12 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 43: {
+      double t = 2*y100 - 87;
+      return 0.54578857454330070965e0 + (0.76474155195880295311e-2 + (-0.20651230590808213884e-3 + (-0.25364339140543131706e-5 + (0.91455367999510681979e-7 + (-0.23061359005297528898e-9 + (-0.27512928625244444444e-10 + 0.54895806008493285579e-12 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 44: {
+      double t = 2*y100 - 89;
+      return 0.56023851910298493910e0 + (0.67938321739997196804e-2 + (-0.21956066613331411760e-3 + (-0.18181127670443266395e-5 + (0.87650335075416845987e-7 + (-0.51548062050366615977e-9 + (-0.20068462174044444444e-10 + 0.50912654909758187264e-12 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 45: {
+      double t = 2*y100 - 91;
+      return 0.57293478057455721150e0 + (0.58965321010394044087e-2 + (-0.22841145229276575597e-3 + (-0.11404605562013443659e-5 + (0.81430290992322326296e-7 + (-0.71512447242755357629e-9 + (-0.13372664928000000000e-10 + 0.44461498336689298148e-12 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 46: {
+      double t = 2*y100 - 93;
+      return 0.58380635448407827360e0 + (0.49717469530842831182e-2 + (-0.23336001540009645365e-3 + (-0.51952064448608850822e-6 + (0.73596577815411080511e-7 + (-0.84020916763091566035e-9 + (-0.76700972702222222221e-11 + 0.36914462807972467044e-12 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 47: {
+      double t = 2*y100 - 95;
+      return 0.59281340237769489597e0 + (0.40343592069379730568e-2 + (-0.23477963738658326185e-3 + (0.34615944987790224234e-7 + (0.64832803248395814574e-7 + (-0.90329163587627007971e-9 + (-0.30421940400000000000e-11 + 0.29237386653743536669e-12 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 48: {
+      double t = 2*y100 - 97;
+      return 0.59994428743114271918e0 + (0.30976579788271744329e-2 + (-0.23308875765700082835e-3 + (0.51681681023846925160e-6 + (0.55694594264948268169e-7 + (-0.91719117313243464652e-9 + (0.53982743680000000000e-12 + 0.22050829296187771142e-12 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 49: {
+      double t = 2*y100 - 99;
+      return 0.60521224471819875444e0 + (0.21732138012345456060e-2 + (-0.22872428969625997456e-3 + (0.92588959922653404233e-6 + (0.46612665806531930684e-7 + (-0.89393722514414153351e-9 + (0.31718550353777777778e-11 + 0.15705458816080549117e-12 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 50: {
+      double t = 2*y100 - 101;
+      return 0.60865189969791123620e0 + (0.12708480848877451719e-2 + (-0.22212090111534847166e-3 + (0.12636236031532793467e-5 + (0.37904037100232937574e-7 + (-0.84417089968101223519e-9 + (0.49843180828444444445e-11 + 0.10355439441049048273e-12 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 51: {
+      double t = 2*y100 - 103;
+      return 0.61031580103499200191e0 + (0.39867436055861038223e-3 + (-0.21369573439579869291e-3 + (0.15339402129026183670e-5 + (0.29787479206646594442e-7 + (-0.77687792914228632974e-9 + (0.61192452741333333334e-11 + 0.60216691829459295780e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 52: {
+      double t = 2*y100 - 105;
+      return 0.61027109047879835868e0 + (-0.43680904508059878254e-3 + (-0.20383783788303894442e-3 + (0.17421743090883439959e-5 + (0.22400425572175715576e-7 + (-0.69934719320045128997e-9 + (0.67152759655111111110e-11 + 0.26419960042578359995e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 53: {
+      double t = 2*y100 - 107;
+      return 0.60859639489217430521e0 + (-0.12305921390962936873e-2 + (-0.19290150253894682629e-3 + (0.18944904654478310128e-5 + (0.15815530398618149110e-7 + (-0.61726850580964876070e-9 + 0.68987888999111111110e-11 * t) * t) * t) * t) * t) * t;
+    }
+    case 54: {
+      double t = 2*y100 - 109;
+      return 0.60537899426486075181e0 + (-0.19790062241395705751e-2 + (-0.18120271393047062253e-3 + (0.19974264162313241405e-5 + (0.10055795094298172492e-7 + (-0.53491997919318263593e-9 + (0.67794550295111111110e-11 - 0.17059208095741511603e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 55: {
+      double t = 2*y100 - 111;
+      return 0.60071229457904110537e0 + (-0.26795676776166354354e-2 + (-0.16901799553627508781e-3 + (0.20575498324332621581e-5 + (0.51077165074461745053e-8 + (-0.45536079828057221858e-9 + (0.64488005516444444445e-11 - 0.29311677573152766338e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 56: {
+      double t = 2*y100 - 113;
+      return 0.59469361520112714738e0 + (-0.33308208190600993470e-2 + (-0.15658501295912405679e-3 + (0.20812116912895417272e-5 + (0.93227468760614182021e-9 + (-0.38066673740116080415e-9 + (0.59806790359111111110e-11 - 0.36887077278950440597e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 57: {
+      double t = 2*y100 - 115;
+      return 0.58742228631775388268e0 + (-0.39321858196059227251e-2 + (-0.14410441141450122535e-3 + (0.20743790018404020716e-5 + (-0.25261903811221913762e-8 + (-0.31212416519526924318e-9 + (0.54328422462222222221e-11 - 0.40864152484979815972e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 58: {
+      double t = 2*y100 - 117;
+      return 0.57899804200033018447e0 + (-0.44838157005618913447e-2 + (-0.13174245966501437965e-3 + (0.20425306888294362674e-5 + (-0.53330296023875447782e-8 + (-0.25041289435539821014e-9 + (0.48490437205333333334e-11 - 0.42162206939169045177e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 59: {
+      double t = 2*y100 - 119;
+      return 0.56951968796931245974e0 + (-0.49864649488074868952e-2 + (-0.11963416583477567125e-3 + (0.19906021780991036425e-5 + (-0.75580140299436494248e-8 + (-0.19576060961919820491e-9 + (0.42613011928888888890e-11 - 0.41539443304115604377e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 60: {
+      double t = 2*y100 - 121;
+      return 0.55908401930063918964e0 + (-0.54413711036826877753e-2 + (-0.10788661102511914628e-3 + (0.19229663322982839331e-5 + (-0.92714731195118129616e-8 + (-0.14807038677197394186e-9 + (0.36920870298666666666e-11 - 0.39603726688419162617e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 61: {
+      double t = 2*y100 - 123;
+      return 0.54778496152925675315e0 + (-0.58501497933213396670e-2 + (-0.96582314317855227421e-4 + (0.18434405235069270228e-5 + (-0.10541580254317078711e-7 + (-0.10702303407788943498e-9 + (0.31563175582222222222e-11 - 0.36829748079110481422e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 62: {
+      double t = 2*y100 - 125;
+      return 0.53571290831682823999e0 + (-0.62147030670760791791e-2 + (-0.85782497917111760790e-4 + (0.17553116363443470478e-5 + (-0.11432547349815541084e-7 + (-0.72157091369041330520e-10 + (0.26630811607111111111e-11 - 0.33578660425893164084e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 63: {
+      double t = 2*y100 - 127;
+      return 0.52295422962048434978e0 + (-0.65371404367776320720e-2 + (-0.75530164941473343780e-4 + (0.16613725797181276790e-5 + (-0.12003521296598910761e-7 + (-0.42929753689181106171e-10 + (0.22170894940444444444e-11 - 0.30117697501065110505e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 64: {
+      double t = 2*y100 - 129;
+      return 0.50959092577577886140e0 + (-0.68197117603118591766e-2 + (-0.65852936198953623307e-4 + (0.15639654113906716939e-5 + (-0.12308007991056524902e-7 + (-0.18761997536910939570e-10 + (0.18198628922666666667e-11 - 0.26638355362285200932e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 65: {
+      double t = 2*y100 - 131;
+      return 0.49570040481823167970e0 + (-0.70647509397614398066e-2 + (-0.56765617728962588218e-4 + (0.14650274449141448497e-5 + (-0.12393681471984051132e-7 + (0.92904351801168955424e-12 + (0.14706755960177777778e-11 - 0.23272455351266325318e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 66: {
+      double t = 2*y100 - 133;
+      return 0.48135536250935238066e0 + (-0.72746293327402359783e-2 + (-0.48272489495730030780e-4 + (0.13661377309113939689e-5 + (-0.12302464447599382189e-7 + (0.16707760028737074907e-10 + (0.11672928324444444444e-11 - 0.20105801424709924499e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 67: {
+      double t = 2*y100 - 135;
+      return 0.46662374675511439448e0 + (-0.74517177649528487002e-2 + (-0.40369318744279128718e-4 + (0.12685621118898535407e-5 + (-0.12070791463315156250e-7 + (0.29105507892605823871e-10 + (0.90653314645333333334e-12 - 0.17189503312102982646e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 68: {
+      double t = 2*y100 - 137;
+      return 0.45156879030168268778e0 + (-0.75983560650033817497e-2 + (-0.33045110380705139759e-4 + (0.11732956732035040896e-5 + (-0.11729986947158201869e-7 + (0.38611905704166441308e-10 + (0.68468768305777777779e-12 - 0.14549134330396754575e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 69: {
+      double t = 2*y100 - 139;
+      return 0.43624909769330896904e0 + (-0.77168291040309554679e-2 + (-0.26283612321339907756e-4 + (0.10811018836893550820e-5 + (-0.11306707563739851552e-7 + (0.45670446788529607380e-10 + (0.49782492549333333334e-12 - 0.12191983967561779442e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 70: {
+      double t = 2*y100 - 141;
+      return 0.42071877443548481181e0 + (-0.78093484015052730097e-2 + (-0.20064596897224934705e-4 + (0.99254806680671890766e-6 + (-0.10823412088884741451e-7 + (0.50677203326904716247e-10 + (0.34200547594666666666e-12 - 0.10112698698356194618e-13 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 71: {
+      double t = 2*y100 - 143;
+      return 0.40502758809710844280e0 + (-0.78780384460872937555e-2 + (-0.14364940764532853112e-4 + (0.90803709228265217384e-6 + (-0.10298832847014466907e-7 + (0.53981671221969478551e-10 + (0.21342751381333333333e-12 - 0.82975901848387729274e-14 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 72: {
+      double t = 2*y100 - 145;
+      return 0.38922115269731446690e0 + (-0.79249269708242064120e-2 + (-0.91595258799106970453e-5 + (0.82783535102217576495e-6 + (-0.97484311059617744437e-8 + (0.55889029041660225629e-10 + (0.10851981336888888889e-12 - 0.67278553237853459757e-14 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 73: {
+      double t = 2*y100 - 147;
+      return 0.37334112915460307335e0 + (-0.79519385109223148791e-2 + (-0.44219833548840469752e-5 + (0.75209719038240314732e-6 + (-0.91848251458553190451e-8 + (0.56663266668051433844e-10 + (0.23995894257777777778e-13 - 0.53819475285389344313e-14 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 74: {
+      double t = 2*y100 - 149;
+      return 0.35742543583374223085e0 + (-0.79608906571527956177e-2 + (-0.12530071050975781198e-6 + (0.68088605744900552505e-6 + (-0.86181844090844164075e-8 + (0.56530784203816176153e-10 + (-0.43120012248888888890e-13 - 0.42372603392496813810e-14 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 75: {
+      double t = 2*y100 - 151;
+      return 0.34150846431979618536e0 + (-0.79534924968773806029e-2 + (0.37576885610891515813e-5 + (0.61419263633090524326e-6 + (-0.80565865409945960125e-8 + (0.55684175248749269411e-10 + (-0.95486860764444444445e-13 - 0.32712946432984510595e-14 * t) * t) * t) * t) * t) * t) * t;
+    }
+    case 76: {
+      double t = 2*y100 - 153;
+      return 0.32562129649136346824e0 + (-0.79313448067948884309e-2 + (0.72539159933545300034e-5 + (0.55195028297415503083e-6 + (-0.75063365335570475258e-8 + (0.54281686749699595941e-10 - 0.13545424295111111111e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 77: {
+      double t = 2*y100 - 155;
+      return 0.30979191977078391864e0 + (-0.78959416264207333695e-2 + (0.10389774377677210794e-4 + (0.49404804463196316464e-6 + (-0.69722488229411164685e-8 + (0.52469254655951393842e-10 - 0.16507860650666666667e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 78: {
+      double t = 2*y100 - 157;
+      return 0.29404543811214459904e0 + (-0.78486728990364155356e-2 + (0.13190885683106990459e-4 + (0.44034158861387909694e-6 + (-0.64578942561562616481e-8 + (0.50354306498006928984e-10 - 0.18614473550222222222e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 79: {
+      double t = 2*y100 - 159;
+      return 0.27840427686253660515e0 + (-0.77908279176252742013e-2 + (0.15681928798708548349e-4 + (0.39066226205099807573e-6 + (-0.59658144820660420814e-8 + (0.48030086420373141763e-10 - 0.20018995173333333333e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 80: {
+      double t = 2*y100 - 161;
+      return 0.26288838011163800908e0 + (-0.77235993576119469018e-2 + (0.17886516796198660969e-4 + (0.34482457073472497720e-6 + (-0.54977066551955420066e-8 + (0.45572749379147269213e-10 - 0.20852924954666666667e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 81: {
+      double t = 2*y100 - 163;
+      return 0.24751539954181029717e0 + (-0.76480877165290370975e-2 + (0.19827114835033977049e-4 + (0.30263228619976332110e-6 + (-0.50545814570120129947e-8 + (0.43043879374212005966e-10 - 0.21228012028444444444e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 82: {
+      double t = 2*y100 - 165;
+      return 0.23230087411688914593e0 + (-0.75653060136384041587e-2 + (0.21524991113020016415e-4 + (0.26388338542539382413e-6 + (-0.46368974069671446622e-8 + (0.40492715758206515307e-10 - 0.21238627815111111111e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 83: {
+      double t = 2*y100 - 167;
+      return 0.21725840021297341931e0 + (-0.74761846305979730439e-2 + (0.23000194404129495243e-4 + (0.22837400135642906796e-6 + (-0.42446743058417541277e-8 + (0.37958104071765923728e-10 - 0.20963978568888888889e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 84: {
+      double t = 2*y100 - 169;
+      return 0.20239979200788191491e0 + (-0.73815761980493466516e-2 + (0.24271552727631854013e-4 + (0.19590154043390012843e-6 + (-0.38775884642456551753e-8 + (0.35470192372162901168e-10 - 0.20470131678222222222e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 85: {
+      double t = 2*y100 - 171;
+      return 0.18773523211558098962e0 + (-0.72822604530339834448e-2 + (0.25356688567841293697e-4 + (0.16626710297744290016e-6 + (-0.35350521468015310830e-8 + (0.33051896213898864306e-10 - 0.19811844544000000000e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 86: {
+      double t = 2*y100 - 173;
+      return 0.17327341258479649442e0 + (-0.71789490089142761950e-2 + (0.26272046822383820476e-4 + (0.13927732375657362345e-6 + (-0.32162794266956859603e-8 + (0.30720156036105652035e-10 - 0.19034196304000000000e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 87: {
+      double t = 2*y100 - 175;
+      return 0.15902166648328672043e0 + (-0.70722899934245504034e-2 + (0.27032932310132226025e-4 + (0.11474573347816568279e-6 + (-0.29203404091754665063e-8 + (0.28487010262547971859e-10 - 0.18174029063111111111e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 88: {
+      double t = 2*y100 - 177;
+      return 0.14498609036610283865e0 + (-0.69628725220045029273e-2 + (0.27653554229160596221e-4 + (0.92493727167393036470e-7 + (-0.26462055548683583849e-8 + (0.26360506250989943739e-10 - 0.17261211260444444444e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 89: {
+      double t = 2*y100 - 179;
+      return 0.13117165798208050667e0 + (-0.68512309830281084723e-2 + (0.28147075431133863774e-4 + (0.72351212437979583441e-7 + (-0.23927816200314358570e-8 + (0.24345469651209833155e-10 - 0.16319736960000000000e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 90: {
+      double t = 2*y100 - 181;
+      return 0.11758232561160626306e0 + (-0.67378491192463392927e-2 + (0.28525664781722907847e-4 + (0.54156999310046790024e-7 + (-0.21589405340123827823e-8 + (0.22444150951727334619e-10 - 0.15368675584000000000e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 91: {
+      double t = 2*y100 - 183;
+      return 0.10422112945361673560e0 + (-0.66231638959845581564e-2 + (0.28800551216363918088e-4 + (0.37758983397952149613e-7 + (-0.19435423557038933431e-8 + (0.20656766125421362458e-10 - 0.14422990012444444444e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 92: {
+      double t = 2*y100 - 185;
+      return 0.91090275493541084785e-1 + (-0.65075691516115160062e-2 + (0.28982078385527224867e-4 + (0.23014165807643012781e-7 + (-0.17454532910249875958e-8 + (0.18981946442680092373e-10 - 0.13494234691555555556e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 93: {
+      double t = 2*y100 - 187;
+      return 0.78191222288771379358e-1 + (-0.63914190297303976434e-2 + (0.29079759021299682675e-4 + (0.97885458059415717014e-8 + (-0.15635596116134296819e-8 + (0.17417110744051331974e-10 - 0.12591151763555555556e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 94: {
+      double t = 2*y100 - 189;
+      return 0.65524757106147402224e-1 + (-0.62750311956082444159e-2 + (0.29102328354323449795e-4 + (-0.20430838882727954582e-8 + (-0.13967781903855367270e-8 + (0.15958771833747057569e-10 - 0.11720175765333333333e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 95: {
+      double t = 2*y100 - 191;
+      return 0.53091065838453612773e-1 + (-0.61586898417077043662e-2 + (0.29057796072960100710e-4 + (-0.12597414620517987536e-7 + (-0.12440642607426861943e-8 + (0.14602787128447932137e-10 - 0.10885859114666666667e-12 * t) * t) * t) * t) * t) * t;
+    }
+    case 96: {
+      double t = 2*y100 - 193;
+      return 0.40889797115352738582e-1 + (-0.60426484889413678200e-2 + (0.28953496450191694606e-4 + (-0.21982952021823718400e-7 + (-0.11044169117553026211e-8 + (0.13344562332430552171e-10 - 0.10091231402844444444e-12 * t) * t) * t) * t) * t) * t;
+    }
+  case 97: case 98:
+  case 99: case 100: { // use Taylor expansion for small x (|x| <= 0.0309...)
+      //  (2/sqrt(pi)) * (x - 2/3 x^3  + 4/15 x^5  - 8/105 x^7 + 16/945 x^9) 
+      double x2 = x*x;
+      return x * (1.1283791670955125739
+                  - x2 * (0.75225277806367504925
+                          - x2 * (0.30090111122547001970
+                                  - x2 * (0.085971746064420005629
+                                          - x2 * 0.016931216931216931217))));
+    }
+  }
+  /* Since 0 <= y100 < 101, this is only reached if x is NaN,
+     in which case we should return NaN. */
+  return NaN;
+}
+
+double FADDEEVA(w_im)(double x)
+{
+  if (x >= 0) {
+    if (x > 45) { // continued-fraction expansion is faster
+      const double ispi = 0.56418958354775628694807945156; // 1 / sqrt(pi)
+      if (x > 5e7) // 1-term expansion, important to avoid overflow
+        return ispi / x;
+      /* 5-term expansion (rely on compiler for CSE), simplified from:
+                ispi / (x-0.5/(x-1/(x-1.5/(x-2/x))))  */
+      return ispi*((x*x) * (x*x-4.5) + 2) / (x * ((x*x) * (x*x-5) + 3.75));
+    }
+    return w_im_y100(100/(1+x), x);
+  }
+  else { // = -FADDEEVA(w_im)(-x)
+    if (x < -45) { // continued-fraction expansion is faster
+      const double ispi = 0.56418958354775628694807945156; // 1 / sqrt(pi)
+      if (x < -5e7) // 1-term expansion, important to avoid overflow
+        return ispi / x;
+      /* 5-term expansion (rely on compiler for CSE), simplified from:
+                ispi / (x-0.5/(x-1/(x-1.5/(x-2/x))))  */
+      return ispi*((x*x) * (x*x-4.5) + 2) / (x * ((x*x) * (x*x-5) + 3.75));
+    }
+    return -w_im_y100(100/(1-x), -x);
+  }
+}
+
+/////////////////////////////////////////////////////////////////////////
+
+// Compile with -DTEST_FADDEEVA to compile a little test program
+#ifdef TEST_FADDEEVA
+
+#ifdef __cplusplus
+#  include <cstdio>
+#else
+#  include <stdio.h>
+#endif
+
+// compute relative error |b-a|/|a|, handling case of NaN and Inf,
+static double relerr(double a, double b) {
+  if (isnan(a) || isnan(b) || isinf(a) || isinf(b)) {
+    if ((isnan(a) && !isnan(b)) || (!isnan(a) && isnan(b)) ||
+        (isinf(a) && !isinf(b)) || (!isinf(a) && isinf(b)) ||
+        (isinf(a) && isinf(b) && a*b < 0))
+      return Inf; // "infinite" error
+    return 0; // matching infinity/nan results counted as zero error
+  }
+  if (a == 0)
+    return b == 0 ? 0 : Inf;
+  else
+    return fabs((b-a) / a);
+}
+
+int main(void) {
+  double errmax_all = 0;
+  {
+    printf("############# w(z) tests #############\n");
+#define NTST 57 // define instead of const for C compatibility
+    cmplx z[NTST] = {
+      C(624.2,-0.26123),
+      C(-0.4,3.),
+      C(0.6,2.),
+      C(-1.,1.),
+      C(-1.,-9.),
+      C(-1.,9.),
+      C(-0.0000000234545,1.1234),
+      C(-3.,5.1),
+      C(-53,30.1),
+      C(0.0,0.12345),
+      C(11,1),
+      C(-22,-2),
+      C(9,-28),
+      C(21,-33),
+      C(1e5,1e5),
+      C(1e14,1e14),
+      C(-3001,-1000),
+      C(1e160,-1e159),
+      C(-6.01,0.01),
+      C(-0.7,-0.7),
+      C(2.611780000000000e+01, 4.540909610972489e+03),
+      C(0.8e7,0.3e7),
+      C(-20,-19.8081),
+      C(1e-16,-1.1e-16),
+      C(2.3e-8,1.3e-8),
+      C(6.3,-1e-13),
+      C(6.3,1e-20),
+      C(1e-20,6.3),
+      C(1e-20,16.3),
+      C(9,1e-300),
+      C(6.01,0.11),
+      C(8.01,1.01e-10),
+      C(28.01,1e-300),
+      C(10.01,1e-200),
+      C(10.01,-1e-200),
+      C(10.01,0.99e-10),
+      C(10.01,-0.99e-10),
+      C(1e-20,7.01),
+      C(-1,7.01),
+      C(5.99,7.01),
+      C(1,0),
+      C(55,0),
+      C(-0.1,0),
+      C(1e-20,0),
+      C(0,5e-14),
+      C(0,51),
+      C(Inf,0),
+      C(-Inf,0),
+      C(0,Inf),
+      C(0,-Inf),
+      C(Inf,Inf),
+      C(Inf,-Inf),
+      C(NaN,NaN),
+      C(NaN,0),
+      C(0,NaN),
+      C(NaN,Inf),
+      C(Inf,NaN)
+    };
+    cmplx w[NTST] = { /* w(z), computed with WolframAlpha
+                                   ... note that WolframAlpha is problematic
+                                   some of the above inputs, so I had to
+                                   use the continued-fraction expansion
+                                   in WolframAlpha in some cases, or switch
+                                   to Maple */
+      C(-3.78270245518980507452677445620103199303131110e-7,
+        0.000903861276433172057331093754199933411710053155),
+      C(0.1764906227004816847297495349730234591778719532788,
+        -0.02146550539468457616788719893991501311573031095617),
+      C(0.2410250715772692146133539023007113781272362309451,
+        0.06087579663428089745895459735240964093522265589350),
+      C(0.30474420525691259245713884106959496013413834051768,
+        -0.20821893820283162728743734725471561394145872072738),
+      C(7.317131068972378096865595229600561710140617977e34,
+        8.321873499714402777186848353320412813066170427e34),
+      C(0.0615698507236323685519612934241429530190806818395,
+        -0.00676005783716575013073036218018565206070072304635),
+      C(0.3960793007699874918961319170187598400134746631,
+        -5.593152259116644920546186222529802777409274656e-9),
+      C(0.08217199226739447943295069917990417630675021771804,
+        -0.04701291087643609891018366143118110965272615832184),
+      C(0.00457246000350281640952328010227885008541748668738,
+        -0.00804900791411691821818731763401840373998654987934),
+      C(0.8746342859608052666092782112565360755791467973338452,
+        0.),
+      C(0.00468190164965444174367477874864366058339647648741,
+        0.0510735563901306197993676329845149741675029197050),
+      C(-0.0023193175200187620902125853834909543869428763219,
+        -0.025460054739731556004902057663500272721780776336),
+      C(9.11463368405637174660562096516414499772662584e304,
+        3.97101807145263333769664875189354358563218932e305),
+      C(-4.4927207857715598976165541011143706155432296e281,
+        -2.8019591213423077494444700357168707775769028e281),
+      C(2.820947917809305132678577516325951485807107151e-6,
+        2.820947917668257736791638444590253942253354058e-6),
+      C(2.82094791773878143474039725787438662716372268e-15,
+        2.82094791773878143474039725773333923127678361e-15),
+      C(-0.0000563851289696244350147899376081488003110150498,
+        -0.000169211755126812174631861529808288295454992688),
+      C(-5.586035480670854326218608431294778077663867e-162,
+        5.586035480670854326218608431294778077663867e-161),
+      C(0.00016318325137140451888255634399123461580248456,
+        -0.095232456573009287370728788146686162555021209999),
+      C(0.69504753678406939989115375989939096800793577783885,
+        -1.8916411171103639136680830887017670616339912024317),
+      C(0.0001242418269653279656612334210746733213167234822,
+        7.145975826320186888508563111992099992116786763e-7),
+      C(2.318587329648353318615800865959225429377529825e-8,
+        6.182899545728857485721417893323317843200933380e-8),
+      C(-0.0133426877243506022053521927604277115767311800303,
+        -0.0148087097143220769493341484176979826888871576145),
+      C(1.00000000000000012412170838050638522857747934,
+        1.12837916709551279389615890312156495593616433e-16),
+      C(0.9999999853310704677583504063775310832036830015,
+        2.595272024519678881897196435157270184030360773e-8),
+      C(-1.4731421795638279504242963027196663601154624e-15,
+        0.090727659684127365236479098488823462473074709),
+      C(5.79246077884410284575834156425396800754409308e-18,
+        0.0907276596841273652364790985059772809093822374),
+      C(0.0884658993528521953466533278764830881245144368,
+        1.37088352495749125283269718778582613192166760e-22),
+      C(0.0345480845419190424370085249304184266813447878,
+        2.11161102895179044968099038990446187626075258e-23),
+      C(6.63967719958073440070225527042829242391918213e-36,
+        0.0630820900592582863713653132559743161572639353),
+      C(0.00179435233208702644891092397579091030658500743634,
+        0.0951983814805270647939647438459699953990788064762),
+      C(9.09760377102097999924241322094863528771095448e-13,
+        0.0709979210725138550986782242355007611074966717),
+      C(7.2049510279742166460047102593255688682910274423e-304,
+        0.0201552956479526953866611812593266285000876784321),
+      C(3.04543604652250734193622967873276113872279682e-44,
+        0.0566481651760675042930042117726713294607499165),
+      C(3.04543604652250734193622967873276113872279682e-44,
+        0.0566481651760675042930042117726713294607499165),
+      C(0.5659928732065273429286988428080855057102069081e-12,
+        0.056648165176067504292998527162143030538756683302),
+      C(-0.56599287320652734292869884280802459698927645e-12,
+        0.0566481651760675042929985271621430305387566833029),
+      C(0.0796884251721652215687859778119964009569455462,
+        1.11474461817561675017794941973556302717225126e-22),
+      C(0.07817195821247357458545539935996687005781943386550,
+        -0.01093913670103576690766705513142246633056714279654),
+      C(0.04670032980990449912809326141164730850466208439937,
+        0.03944038961933534137558064191650437353429669886545),
+      C(0.36787944117144232159552377016146086744581113103176,
+        0.60715770584139372911503823580074492116122092866515),
+      C(0,
+        0.010259688805536830986089913987516716056946786526145),
+      C(0.99004983374916805357390597718003655777207908125383,
+        -0.11208866436449538036721343053869621153527769495574),
+      C(0.99999999999999999999999999999999999999990000,
+        1.12837916709551257389615890312154517168802603e-20),
+      C(0.999999999999943581041645226871305192054749891144158,
+        0),
+      C(0.0110604154853277201542582159216317923453996211744250,
+        0),
+      C(0,0),
+      C(0,0),
+      C(0,0),
+      C(Inf,0),
+      C(0,0),
+      C(NaN,NaN),
+      C(NaN,NaN),
+      C(NaN,NaN),
+      C(NaN,0),
+      C(NaN,NaN),
+      C(NaN,NaN)
+    };
+    double errmax = 0;
+    for (int i = 0; i < NTST; ++i) {
+      cmplx fw = FADDEEVA(w)(z[i],0.);
+      double re_err = relerr(creal(w[i]), creal(fw));
+      double im_err = relerr(cimag(w[i]), cimag(fw));
+      printf("w(%g%+gi) = %g%+gi (vs. %g%+gi), re/im rel. err. = %0.2g/%0.2g)\n",
+             creal(z[i]),cimag(z[i]), creal(fw),cimag(fw), creal(w[i]),cimag(w[i]),
+             re_err, im_err);
+      if (re_err > errmax) errmax = re_err;
+      if (im_err > errmax) errmax = im_err;
+    }
+    if (errmax > 1e-13) {
+      printf("FAILURE -- relative error %g too large!\n", errmax);
+      return 1;
+    }
+    printf("SUCCESS (max relative error = %g)\n", errmax);
+    if (errmax > errmax_all) errmax_all = errmax;
+  }
+  {
+#undef NTST
+#define NTST 41 // define instead of const for C compatibility
+    cmplx z[NTST] = {
+      C(1,2),
+      C(-1,2),
+      C(1,-2),
+      C(-1,-2),
+      C(9,-28),
+      C(21,-33),
+      C(1e3,1e3),
+      C(-3001,-1000),
+      C(1e160,-1e159),
+      C(5.1e-3, 1e-8),
+      C(-4.9e-3, 4.95e-3),
+      C(4.9e-3, 0.5),
+      C(4.9e-4, -0.5e1),
+      C(-4.9e-5, -0.5e2),
+      C(5.1e-3, 0.5),
+      C(5.1e-4, -0.5e1),
+      C(-5.1e-5, -0.5e2),
+      C(1e-6,2e-6),
+      C(0,2e-6),
+      C(0,2),
+      C(0,20),
+      C(0,200),
+      C(Inf,0),
+      C(-Inf,0),
+      C(0,Inf),
+      C(0,-Inf),
+      C(Inf,Inf),
+      C(Inf,-Inf),
+      C(NaN,NaN),
+      C(NaN,0),
+      C(0,NaN),
+      C(NaN,Inf),
+      C(Inf,NaN),
+      C(1e-3,NaN),
+      C(7e-2,7e-2),
+      C(7e-2,-7e-4),
+      C(-9e-2,7e-4),
+      C(-9e-2,9e-2),
+      C(-7e-4,9e-2),
+      C(7e-2,0.9e-2),
+      C(7e-2,1.1e-2)
+    };
+    cmplx w[NTST] = { // erf(z[i]), evaluated with Maple
+      C(-0.5366435657785650339917955593141927494421,
+        -5.049143703447034669543036958614140565553),
+      C(0.5366435657785650339917955593141927494421,
+        -5.049143703447034669543036958614140565553),
+      C(-0.5366435657785650339917955593141927494421,
+        5.049143703447034669543036958614140565553),
+      C(0.5366435657785650339917955593141927494421,
+        5.049143703447034669543036958614140565553),
+      C(0.3359473673830576996788000505817956637777e304,
+        -0.1999896139679880888755589794455069208455e304),
+      C(0.3584459971462946066523939204836760283645e278,
+        0.3818954885257184373734213077678011282505e280),
+      C(0.9996020422657148639102150147542224526887,
+        0.00002801044116908227889681753993542916894856),
+      C(-1, 0),
+      C(1, 0),
+      C(0.005754683859034800134412990541076554934877,
+        0.1128349818335058741511924929801267822634e-7),
+      C(-0.005529149142341821193633460286828381876955,
+        0.005585388387864706679609092447916333443570),
+      C(0.007099365669981359632319829148438283865814,
+        0.6149347012854211635026981277569074001219),
+      C(0.3981176338702323417718189922039863062440e8,
+        -0.8298176341665249121085423917575122140650e10),
+      C(-Inf,
+        -Inf),
+      C(0.007389128308257135427153919483147229573895,
+        0.6149332524601658796226417164791221815139),
+      C(0.4143671923267934479245651547534414976991e8,
+        -0.8298168216818314211557046346850921446950e10),
+      C(-Inf,
+        -Inf),
+      C(0.1128379167099649964175513742247082845155e-5,
+        0.2256758334191777400570377193451519478895e-5),
+      C(0,
+        0.2256758334194034158904576117253481476197e-5),
+      C(0,
+        18.56480241457555259870429191324101719886),
+      C(0,
+        0.1474797539628786202447733153131835124599e173),
+      C(0,
+        Inf),
+      C(1,0),
+      C(-1,0),
+      C(0,Inf),
+      C(0,-Inf),
+      C(NaN,NaN),
+      C(NaN,NaN),
+      C(NaN,NaN),
+      C(NaN,0),
+      C(0,NaN),
+      C(NaN,NaN),
+      C(NaN,NaN),
+      C(NaN,NaN),
+      C(0.07924380404615782687930591956705225541145,
+        0.07872776218046681145537914954027729115247),
+      C(0.07885775828512276968931773651224684454495,
+        -0.0007860046704118224342390725280161272277506),
+      C(-0.1012806432747198859687963080684978759881,
+        0.0007834934747022035607566216654982820299469),
+      C(-0.1020998418798097910247132140051062512527,
+        0.1010030778892310851309082083238896270340),
+      C(-0.0007962891763147907785684591823889484764272,
+        0.1018289385936278171741809237435404896152),
+      C(0.07886408666470478681566329888615410479530,
+        0.01010604288780868961492224347707949372245),
+      C(0.07886723099940260286824654364807981336591,
+        0.01235199327873258197931147306290916629654)
+    };
+#define TST(f,isc)                                                      \
+    printf("############# " #f "(z) tests #############\n");            \
+    double errmax = 0;                                                  \
+    for (int i = 0; i < NTST; ++i) {                                    \
+      cmplx fw = FADDEEVA(f)(z[i],0.);                  \
+      double re_err = relerr(creal(w[i]), creal(fw));                   \
+      double im_err = relerr(cimag(w[i]), cimag(fw));                   \
+      printf(#f "(%g%+gi) = %g%+gi (vs. %g%+gi), re/im rel. err. = %0.2g/%0.2g)\n", \
+             creal(z[i]),cimag(z[i]), creal(fw),cimag(fw), creal(w[i]),cimag(w[i]), \
+             re_err, im_err);                                           \
+      if (re_err > errmax) errmax = re_err;                             \
+      if (im_err > errmax) errmax = im_err;                             \
+    }                                                                   \
+    if (errmax > 1e-13) {                                               \
+      printf("FAILURE -- relative error %g too large!\n", errmax);      \
+      return 1;                                                         \
+    }                                                                   \
+    printf("Checking " #f "(x) special case...\n");                     \
+    for (int i = 0; i < 10000; ++i) {                                   \
+      double x = pow(10., -300. + i * 600. / (10000 - 1));              \
+      double re_err = relerr(FADDEEVA_RE(f)(x),                         \
+                             creal(FADDEEVA(f)(C(x,x*isc),0.)));        \
+      if (re_err > errmax) errmax = re_err;                             \
+      re_err = relerr(FADDEEVA_RE(f)(-x),                               \
+                      creal(FADDEEVA(f)(C(-x,x*isc),0.)));              \
+      if (re_err > errmax) errmax = re_err;                             \
+    }                                                                   \
+    {                                                                   \
+      double re_err = relerr(FADDEEVA_RE(f)(Inf),                       \
+                             creal(FADDEEVA(f)(C(Inf,0.),0.))); \
+      if (re_err > errmax) errmax = re_err;                             \
+      re_err = relerr(FADDEEVA_RE(f)(-Inf),                             \
+                      creal(FADDEEVA(f)(C(-Inf,0.),0.)));               \
+      if (re_err > errmax) errmax = re_err;                             \
+      re_err = relerr(FADDEEVA_RE(f)(NaN),                              \
+                      creal(FADDEEVA(f)(C(NaN,0.),0.)));                \
+      if (re_err > errmax) errmax = re_err;                             \
+    }                                                                   \
+    if (errmax > 1e-13) {                                               \
+      printf("FAILURE -- relative error %g too large!\n", errmax);      \
+      return 1;                                                         \
+    }                                                                   \
+    printf("SUCCESS (max relative error = %g)\n", errmax);              \
+    if (errmax > errmax_all) errmax_all = errmax
+
+    TST(erf, 1e-20);
+  }
+  {
+    // since erfi just calls through to erf, just one test should
+    // be sufficient to make sure I didn't screw up the signs or something
+#undef NTST
+#define NTST 1 // define instead of const for C compatibility
+    cmplx z[NTST] = { C(1.234,0.5678) };
+    cmplx w[NTST] = { // erfi(z[i]), computed with Maple
+      C(1.081032284405373149432716643834106923212,
+        1.926775520840916645838949402886591180834)
+    };
+    TST(erfi, 0);
+  }
+  {
+    // since erfcx just calls through to w, just one test should
+    // be sufficient to make sure I didn't screw up the signs or something
+#undef NTST
+#define NTST 1 // define instead of const for C compatibility
+    cmplx z[NTST] = { C(1.234,0.5678) };
+    cmplx w[NTST] = { // erfcx(z[i]), computed with Maple
+      C(0.3382187479799972294747793561190487832579,
+        -0.1116077470811648467464927471872945833154)
+    };
+    TST(erfcx, 0);
+  }
+  {
+#undef NTST
+#define NTST 30 // define instead of const for C compatibility
+    cmplx z[NTST] = {
+      C(1,2),
+      C(-1,2),
+      C(1,-2),
+      C(-1,-2),
+      C(9,-28),
+      C(21,-33),
+      C(1e3,1e3),
+      C(-3001,-1000),
+      C(1e160,-1e159),
+      C(5.1e-3, 1e-8),
+      C(0,2e-6),
+      C(0,2),
+      C(0,20),
+      C(0,200),
+      C(2e-6,0),
+      C(2,0),
+      C(20,0),
+      C(200,0),
+      C(Inf,0),
+      C(-Inf,0),
+      C(0,Inf),
+      C(0,-Inf),
+      C(Inf,Inf),
+      C(Inf,-Inf),
+      C(NaN,NaN),
+      C(NaN,0),
+      C(0,NaN),
+      C(NaN,Inf),
+      C(Inf,NaN),
+      C(88,0)
+    };
+    cmplx w[NTST] = { // erfc(z[i]), evaluated with Maple
+      C(1.536643565778565033991795559314192749442,
+        5.049143703447034669543036958614140565553),
+      C(0.4633564342214349660082044406858072505579,
+        5.049143703447034669543036958614140565553),
+      C(1.536643565778565033991795559314192749442,
+        -5.049143703447034669543036958614140565553),
+      C(0.4633564342214349660082044406858072505579,
+        -5.049143703447034669543036958614140565553),
+      C(-0.3359473673830576996788000505817956637777e304,
+        0.1999896139679880888755589794455069208455e304),
+      C(-0.3584459971462946066523939204836760283645e278,
+        -0.3818954885257184373734213077678011282505e280),
+      C(0.0003979577342851360897849852457775473112748,
+        -0.00002801044116908227889681753993542916894856),
+      C(2, 0),
+      C(0, 0),
+      C(0.9942453161409651998655870094589234450651,
+        -0.1128349818335058741511924929801267822634e-7),
+      C(1,
+        -0.2256758334194034158904576117253481476197e-5),
+      C(1,
+        -18.56480241457555259870429191324101719886),
+      C(1,
+        -0.1474797539628786202447733153131835124599e173),
+      C(1, -Inf),
+      C(0.9999977432416658119838633199332831406314,
+        0),
+      C(0.004677734981047265837930743632747071389108,
+        0),
+      C(0.5395865611607900928934999167905345604088e-175,
+        0),
+      C(0, 0),
+      C(0, 0),
+      C(2, 0),
+      C(1, -Inf),
+      C(1, Inf),
+      C(NaN, NaN),
+      C(NaN, NaN),
+      C(NaN, NaN),
+      C(NaN, 0),
+      C(1, NaN),
+      C(NaN, NaN),
+      C(NaN, NaN),
+      C(0,0)
+    };
+    TST(erfc, 1e-20);
+  }
+  {
+#undef NTST
+#define NTST 48 // define instead of const for C compatibility
+    cmplx z[NTST] = {
+      C(2,1),
+      C(-2,1),
+      C(2,-1),
+      C(-2,-1),
+      C(-28,9),
+      C(33,-21),
+      C(1e3,1e3),
+      C(-1000,-3001),
+      C(1e-8, 5.1e-3),
+      C(4.95e-3, -4.9e-3),
+      C(5.1e-3, 5.1e-3),
+      C(0.5, 4.9e-3),
+      C(-0.5e1, 4.9e-4),
+      C(-0.5e2, -4.9e-5),
+      C(0.5e3, 4.9e-6),
+      C(0.5, 5.1e-3),
+      C(-0.5e1, 5.1e-4),
+      C(-0.5e2, -5.1e-5),
+      C(1e-6,2e-6),
+      C(2e-6,0),
+      C(2,0),
+      C(20,0),
+      C(200,0),
+      C(0,4.9e-3),
+      C(0,-5.1e-3),
+      C(0,2e-6),
+      C(0,-2),
+      C(0,20),
+      C(0,-200),
+      C(Inf,0),
+      C(-Inf,0),
+      C(0,Inf),
+      C(0,-Inf),
+      C(Inf,Inf),
+      C(Inf,-Inf),
+      C(NaN,NaN),
+      C(NaN,0),
+      C(0,NaN),
+      C(NaN,Inf),
+      C(Inf,NaN),
+      C(39, 6.4e-5),
+      C(41, 6.09e-5),
+      C(4.9e7, 5e-11),
+      C(5.1e7, 4.8e-11),
+      C(1e9, 2.4e-12),
+      C(1e11, 2.4e-14),
+      C(1e13, 2.4e-16),
+      C(1e300, 2.4e-303)
+    };
+    cmplx w[NTST] = { // dawson(z[i]), evaluated with Maple
+      C(0.1635394094345355614904345232875688576839,
+        -0.1531245755371229803585918112683241066853),
+      C(-0.1635394094345355614904345232875688576839,
+        -0.1531245755371229803585918112683241066853),
+      C(0.1635394094345355614904345232875688576839,
+        0.1531245755371229803585918112683241066853),
+      C(-0.1635394094345355614904345232875688576839,
+        0.1531245755371229803585918112683241066853),
+      C(-0.01619082256681596362895875232699626384420,
+        -0.005210224203359059109181555401330902819419),
+      C(0.01078377080978103125464543240346760257008,
+        0.006866888783433775382193630944275682670599),
+      C(-0.5808616819196736225612296471081337245459,
+        0.6688593905505562263387760667171706325749),
+      C(Inf,
+        -Inf),
+      C(0.1000052020902036118082966385855563526705e-7,
+        0.005100088434920073153418834680320146441685),
+      C(0.004950156837581592745389973960217444687524,
+        -0.004899838305155226382584756154100963570500),
+      C(0.005100176864319675957314822982399286703798,
+        0.005099823128319785355949825238269336481254),
+      C(0.4244534840871830045021143490355372016428,
+        0.002820278933186814021399602648373095266538),
+      C(-0.1021340733271046543881236523269967674156,
+        -0.00001045696456072005761498961861088944159916),
+      C(-0.01000200120119206748855061636187197886859,
+        0.9805885888237419500266621041508714123763e-8),
+      C(0.001000002000012000023960527532953151819595,
+        -0.9800058800588007290937355024646722133204e-11),
+      C(0.4244549085628511778373438768121222815752,
+        0.002935393851311701428647152230552122898291),
+      C(-0.1021340732357117208743299813648493928105,
+        -0.00001088377943049851799938998805451564893540),
+      C(-0.01000200120119126652710792390331206563616,
+        0.1020612612857282306892368985525393707486e-7),
+      C(0.1000000000007333333333344266666666664457e-5,
+        0.2000000000001333333333323199999999978819e-5),
+      C(0.1999999999994666666666675199999999990248e-5,
+        0),
+      C(0.3013403889237919660346644392864226952119,
+        0),
+      C(0.02503136792640367194699495234782353186858,
+        0),
+      C(0.002500031251171948248596912483183760683918,
+        0),
+      C(0,0.004900078433419939164774792850907128053308),
+      C(0,-0.005100088434920074173454208832365950009419),
+      C(0,0.2000000000005333333333341866666666676419e-5),
+      C(0,-48.16001211429122974789822893525016528191),
+      C(0,0.4627407029504443513654142715903005954668e174),
+      C(0,-Inf),
+      C(0,0),
+      C(-0,0),
+      C(0, Inf),
+      C(0, -Inf),
+      C(NaN, NaN),
+      C(NaN, NaN),
+      C(NaN, NaN),
+      C(NaN, 0),
+      C(0, NaN),
+      C(NaN, NaN),
+      C(NaN, NaN),
+      C(0.01282473148489433743567240624939698290584,
+        -0.2105957276516618621447832572909153498104e-7),
+      C(0.01219875253423634378984109995893708152885,
+        -0.1813040560401824664088425926165834355953e-7),
+      C(0.1020408163265306334945473399689037886997e-7,
+        -0.1041232819658476285651490827866174985330e-25),
+      C(0.9803921568627452865036825956835185367356e-8,
+        -0.9227220299884665067601095648451913375754e-26),
+      C(0.5000000000000000002500000000000000003750e-9,
+        -0.1200000000000000001800000188712838420241e-29),
+      C(5.00000000000000000000025000000000000000000003e-12,
+        -1.20000000000000000000018000000000000000000004e-36),
+      C(5.00000000000000000000000002500000000000000000e-14,
+        -1.20000000000000000000000001800000000000000000e-42),
+      C(5e-301, 0)
+    };
+    TST(Dawson, 1e-20);
+  }
+  printf("#####################################\n");
+  printf("SUCCESS (max relative error = %g)\n", errmax_all);
+}
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/liboctave/cruft/Faddeeva/Faddeeva.hh	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,62 @@
+/* Copyright (c) 2012 Massachusetts Institute of Technology
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
+ */
+
+/* Available at: http://ab-initio.mit.edu/Faddeeva
+
+   Header file for Faddeeva.cc; see that file for more information. */
+
+#ifndef FADDEEVA_HH
+#define FADDEEVA_HH 1
+
+#include <complex>
+
+namespace Faddeeva {
+
+// compute w(z) = exp(-z^2) erfc(-iz) [ Faddeeva / scaled complex error func ]
+extern std::complex<double> w(std::complex<double> z,double relerr=0);
+extern double w_im(double x); // special-case code for Im[w(x)] of real x
+
+// Various functions that we can compute with the help of w(z)
+
+// compute erfcx(z) = exp(z^2) erfc(z)
+extern std::complex<double> erfcx(std::complex<double> z, double relerr=0);
+extern double erfcx(double x); // special case for real x
+
+// compute erf(z), the error function of complex arguments
+extern std::complex<double> erf(std::complex<double> z, double relerr=0);
+extern double erf(double x); // special case for real x
+
+// compute erfi(z) = -i erf(iz), the imaginary error function
+extern std::complex<double> erfi(std::complex<double> z, double relerr=0);
+extern double erfi(double x); // special case for real x
+
+// compute erfc(z) = 1 - erf(z), the complementary error function
+extern std::complex<double> erfc(std::complex<double> z, double relerr=0);
+extern double erfc(double x); // special case for real x
+
+// compute Dawson(z) = sqrt(pi)/2  *  exp(-z^2) * erfi(z)
+extern std::complex<double> Dawson(std::complex<double> z, double relerr=0);
+extern double Dawson(double x); // special case for real x
+
+} // namespace Faddeeva
+
+#endif // FADDEEVA_HH
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/liboctave/cruft/Faddeeva/module.mk	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,3 @@
+EXTRA_DIST += Faddeeva/module.mk
+
+libcruft_la_SOURCES += Faddeeva/Faddeeva.cc Faddeeva/Faddeeva.hh
--- a/liboctave/cruft/Makefile.am	Thu Nov 01 15:01:20 2012 -0400
+++ b/liboctave/cruft/Makefile.am	Sun Dec 23 13:00:02 2012 -0500
@@ -47,6 +47,7 @@
 include daspk/module.mk
 include dasrt/module.mk
 include dassl/module.mk
+include Faddeeva/module.mk
 include fftpack/module.mk
 include lapack-xtra/module.mk
 include misc/module.mk
--- a/liboctave/numeric/lo-specfun.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/liboctave/numeric/lo-specfun.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -50,6 +50,8 @@
 #define M_PI 3.14159265358979323846
 #endif
 
+#include "Faddeeva.hh"
+
 extern "C"
 {
   F77_RET_T
@@ -287,6 +289,82 @@
 }
 #endif
 
+// Complex error function from the Faddeeva package
+Complex
+erf (const Complex& x)
+{
+  return Faddeeva::erf (x);
+}
+FloatComplex
+erf (const FloatComplex& x)
+{
+  Complex xd (real (x), imag (x));
+  Complex ret = Faddeeva::erf (xd, std::numeric_limits<float>::epsilon ());
+  return FloatComplex (real (ret), imag (ret));
+}
+
+// Complex complementary error function from the Faddeeva package
+Complex
+erfc (const Complex& x)
+{
+  return Faddeeva::erfc (x);
+}
+FloatComplex
+erfc (const FloatComplex& x)
+{
+  Complex xd (real (x), imag (x));
+  Complex ret = Faddeeva::erfc (xd, std::numeric_limits<float>::epsilon ());
+  return FloatComplex (real (ret), imag (ret));
+}
+
+// Real and complex scaled complementary error function from Faddeeva package
+float erfcx (float x) { return Faddeeva::erfcx(x); }
+double erfcx (double x) { return Faddeeva::erfcx(x); }
+Complex
+erfcx (const Complex& x)
+{
+  return Faddeeva::erfcx (x);
+}
+FloatComplex
+erfcx (const FloatComplex& x)
+{
+  Complex xd (real (x), imag (x));
+  Complex ret = Faddeeva::erfcx (xd, std::numeric_limits<float>::epsilon ());
+  return FloatComplex (real (ret), imag (ret));
+}
+
+// Real and complex imaginary error function from Faddeeva package
+float erfi (float x) { return Faddeeva::erfi(x); }
+double erfi (double x) { return Faddeeva::erfi(x); }
+Complex
+erfi (const Complex& x)
+{
+  return Faddeeva::erfi (x);
+}
+FloatComplex
+erfi (const FloatComplex& x)
+{
+  Complex xd (real (x), imag (x));
+  Complex ret = Faddeeva::erfi (xd, std::numeric_limits<float>::epsilon ());
+  return FloatComplex (real (ret), imag (ret));
+}
+
+// Real and complex Dawson function (= scaled erfi) from Faddeeva package
+float dawson (float x) { return Faddeeva::Dawson(x); }
+double dawson (double x) { return Faddeeva::Dawson(x); }
+Complex
+dawson (const Complex& x)
+{
+  return Faddeeva::Dawson (x);
+}
+FloatComplex
+dawson (const FloatComplex& x)
+{
+  Complex xd (real (x), imag (x));
+  Complex ret = Faddeeva::Dawson (xd, std::numeric_limits<float>::epsilon ());
+  return FloatComplex (real (ret), imag (ret));
+}
+
 double
 xgamma (double x)
 {
@@ -3029,106 +3107,6 @@
   return do_erfcinv (x, false);
 }
 
-// Implementation based on the Fortran code by W.J.Cody
-// see http://www.netlib.org/specfun/erf.
-// Templatized and simplified workflow.
-
-// FIXME: Maybe this should be globally visible.
-static inline float erfc (float x) { return erfcf (x); }
-
-template <class T>
-static T
-erfcx_impl (T x)
-{
-  static const T c[] =
-    {
-      5.64188496988670089e-1,8.88314979438837594,
-      6.61191906371416295e+1,2.98635138197400131e+2,
-      8.81952221241769090e+2,1.71204761263407058e+3,
-      2.05107837782607147e+3,1.23033935479799725e+3,
-      2.15311535474403846e-8
-    };
-
-  static const T d[] =
-    {
-      1.57449261107098347e+1,1.17693950891312499e+2,
-      5.37181101862009858e+2,1.62138957456669019e+3,
-      3.29079923573345963e+3,4.36261909014324716e+3,
-      3.43936767414372164e+3,1.23033935480374942e+3
-    };
-
-  static const T p[] =
-    {
-      3.05326634961232344e-1,3.60344899949804439e-1,
-      1.25781726111229246e-1,1.60837851487422766e-2,
-      6.58749161529837803e-4,1.63153871373020978e-2
-    };
-
-  static const T q[] =
-    {
-      2.56852019228982242,1.87295284992346047,
-      5.27905102951428412e-1,6.05183413124413191e-2,
-      2.33520497626869185e-3
-    };
-
-  static const T sqrpi = 5.6418958354775628695e-1;
-  static const T xhuge = sqrt (1.0 / std::numeric_limits<T>::epsilon ());
-  static const T xneg = -sqrt (log (std::numeric_limits<T>::max ()/2.0));
-
-  double y = fabs (x), result;
-  if (x < xneg)
-    result = octave_Inf;
-  else if (y <= 0.46875)
-    result = std::exp (x*x) * erfc (x);
-  else
-    {
-      if (y <= 4.0)
-        {
-          double xnum = c[8]*y, xden = y;
-          for (int i = 0; i < 7; i++)
-            {
-              xnum = (xnum + c[i]) * y;
-              xden = (xden + d[i]) * y;
-            }
-
-          result = (xnum + c[7]) / (xden + d[7]);
-        }
-      else if (y <= xhuge)
-        {
-          double y2 = 1/(y*y), xnum = p[5]*y2, xden = y2;
-          for (int i = 0; i < 4; i++)
-            {
-              xnum = (xnum + p[i]) * y2;
-              xden = (xden + q[i]) * y2;
-            }
-
-          result = y2 * (xnum + p[4]) / (xden + q[4]);
-          result = (sqrpi - result) / y;
-        }
-      else
-        result = sqrpi / y;
-
-      // Fix up negative argument.
-      if (x < 0)
-        {
-          double y2 = ceil (x / 16.0) * 16.0, del = (x-y2)*(x+y2);
-          result = 2*(std::exp (y2*y2) * std::exp (del)) - result;
-        }
-    }
-
-  return result;
-}
-
-double erfcx (double x)
-{
-  return erfcx_impl (x);
-}
-
-float erfcx (float x)
-{
-  return erfcx_impl (x);
-}
-
 //
 //  Incomplete Beta function ratio
 //
--- a/liboctave/numeric/lo-specfun.h	Thu Nov 01 15:01:20 2012 -0400
+++ b/liboctave/numeric/lo-specfun.h	Sun Dec 23 13:00:02 2012 -0500
@@ -56,10 +56,14 @@
 #if !defined (HAVE_ERF)
 extern OCTAVE_API double erf (double);
 #endif
+extern OCTAVE_API Complex erf (const Complex& x);
+extern OCTAVE_API FloatComplex erf (const FloatComplex& x);
 
 #if !defined (HAVE_ERFC)
 extern OCTAVE_API double erfc (double);
 #endif
+extern OCTAVE_API Complex erfc (const Complex& x);
+extern OCTAVE_API FloatComplex erfc (const FloatComplex& x);
 
 #if !defined (HAVE_ACOSHF)
 extern OCTAVE_API float acoshf (float);
@@ -578,8 +582,20 @@
 extern OCTAVE_API double erfcinv (double x);
 extern OCTAVE_API float erfcinv (float x);
 
+extern OCTAVE_API float erfcx (float x);
 extern OCTAVE_API double erfcx (double x);
-extern OCTAVE_API float erfcx (float x);
+extern OCTAVE_API Complex erfcx (const Complex& x);
+extern OCTAVE_API FloatComplex erfcx (const FloatComplex& x);
+
+extern OCTAVE_API float erfi (float x);
+extern OCTAVE_API double erfi (double x);
+extern OCTAVE_API Complex erfi (const Complex& x);
+extern OCTAVE_API FloatComplex erfi (const FloatComplex& x);
+
+extern OCTAVE_API float dawson (float x);
+extern OCTAVE_API double dawson (double x);
+extern OCTAVE_API Complex dawson (const Complex& x);
+extern OCTAVE_API FloatComplex dawson (const FloatComplex& x);
 
 extern OCTAVE_API double betaincinv (double x, double a, double b);
 extern OCTAVE_API Array<double> betaincinv (double x, double a, const Array<double>& b);
--- a/liboctave/numeric/module.mk	Thu Nov 01 15:01:20 2012 -0400
+++ b/liboctave/numeric/module.mk	Sun Dec 23 13:00:02 2012 -0500
@@ -179,6 +179,7 @@
 numeric_libnumeric_la_CPPFLAGS = \
   $(liboctave_la_CPPFLAGS) \
   $(ARPACK_CPPFLAGS) \
+  -I$(srcdir)/cruft/Faddeeva \
   $(FFTW_XCPPFLAGS) \
   $(SPARSE_XCPPFLAGS)
 
--- a/liboctave/numeric/oct-fftw.h	Thu Nov 01 15:01:20 2012 -0400
+++ b/liboctave/numeric/oct-fftw.h	Sun Dec 23 13:00:02 2012 -0500
@@ -225,14 +225,14 @@
   {
     static FftwMethod dummy;
 
-    return instance_ok () ? instance->method () : dummy;
+    return instance_ok () ? instance->do_method () : dummy;
   }
 
   static FftwMethod method (FftwMethod _meth)
   {
     static FftwMethod dummy;
 
-    return instance_ok () ? instance->method (_meth) : dummy;
+    return instance_ok () ? instance->do_method (_meth) : dummy;
   }
 
 private:
--- a/liboctave/util/oct-shlib.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/liboctave/util/oct-shlib.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -75,7 +75,7 @@
 octave_shlib::shlib_rep::is_out_of_date (void) const
 {
   file_stat fs (file);
-  return fs.is_newer (tm_loaded);
+  return (fs && fs.is_newer (tm_loaded));
 }
 
 void
@@ -83,7 +83,7 @@
 {
   // We can't actually reload the library, but we'll pretend we did.
   file_stat fs (file);
-  if (fs.is_newer (tm_loaded))
+  if (fs && fs.is_newer (tm_loaded))
     {
       tm_loaded = fs.mtime ();
 
--- a/liboctave/util/regexp.cc	Thu Nov 01 15:01:20 2012 -0400
+++ b/liboctave/util/regexp.cc	Sun Dec 23 13:00:02 2012 -0500
@@ -426,11 +426,7 @@
 {
   regexp::match_data rx_lst = match (buffer);
 
-  regexp::match_data::const_iterator p = rx_lst.begin ();
-
-  std::string match_string = p->match_string ();
-
-  return ! match_string.empty ();
+  return rx_lst.size () > 0;
 }
 
 Array<bool>
--- a/m4/acinclude.m4	Thu Nov 01 15:01:20 2012 -0400
+++ b/m4/acinclude.m4	Sun Dec 23 13:00:02 2012 -0500
@@ -153,7 +153,7 @@
     [octave_cv_func_findfirst_modern],
     [AC_LANG_PUSH(C++)
     ac_octave_save_CPPFLAGS="$CPPFLAGS"
-    CPPFLAGS="-I$QT_INCDIR -I$QT_INCDIR/Qt $CPPFLAGS"
+    CPPFLAGS="$QT_CPPFLAGS $CPPFLAGS"
     AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
         #include <Qsci/qsciglobal.h>
         ]], [[
@@ -231,7 +231,7 @@
     [octave_cv_func_setplaceholdertext],
     [AC_LANG_PUSH(C++)
     ac_octave_save_CPPFLAGS="$CPPFLAGS"
-    CPPFLAGS="-I$QT_INCDIR $CPPFLAGS"
+    CPPFLAGS="$QT_CPPFLAGS $CPPFLAGS"
     AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
         #include <Qt/qglobal.h>
         ]], [[
@@ -1766,202 +1766,4 @@
 dnl ------------------------------------------------------------
 dnl
 
-dnl
-dnl    The following macros were taken from other sources. 
-dnl ------------------------------------------------------------
-
-dnl
-dnl Configure paths for FreeType2
-dnl Marcelo Magallon 2001-10-26, based on gtk.m4 by Owen Taylor
-dnl
-dnl Copyright 2001, 2003 by
-dnl David Turner, Robert Wilhelm, and Werner Lemberg.
-dnl
-dnl This file is part of the FreeType project, and may only be used, modified,
-dnl and distributed under the terms of the FreeType project license,
-dnl LICENSE.TXT.  By continuing to use, modify, or distribute this file you
-dnl indicate that you have read the license and understand and accept it
-dnl fully.
-dnl
-dnl As a special exception to the FreeType project license, this file may be
-dnl distributed as part of a program that contains a configuration script
-dnl generated by Autoconf, under the same distribution terms as the rest of
-dnl that program.
-dnl
-dnl serial 2
-dnl
-dnl AC_CHECK_FT2([MINIMUM-VERSION [, ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]]])
-dnl Test for FreeType 2, and define FT2_CFLAGS and FT2_LIBS.
-dnl MINIMUM-VERSION is what libtool reports; the default is `7.0.1' (this is
-dnl FreeType 2.0.4).
-dnl
-AC_DEFUN([AC_CHECK_FT2], [
-  dnl
-  dnl Get the cflags and libraries from the freetype-config script
-  dnl
-  AC_ARG_WITH([ft-prefix],
-    [AS_HELP_STRING([--with-ft-prefix=PREFIX],
-                   [Prefix where FreeType is installed (optional)])],
-    [ft_config_prefix="$withval"],
-    [ft_config_prefix=""])
- 
-  AC_ARG_WITH([ft-exec-prefix],
-    [AS_HELP_STRING([--with-ft-exec-prefix=PREFIX],
-                   [Exec prefix where FreeType is installed (optional)])],
-    [ft_config_exec_prefix="$withval"],
-    [ft_config_exec_prefix=""])
-
-  AC_ARG_ENABLE([freetypetest],
-    [AS_HELP_STRING([--disable-freetypetest],
-                    [Do not try to compile and run a test FreeType program])],
-    [],
-    [enable_fttest=yes])
-
-  if test x$ft_config_exec_prefix != x ; then
-    ft_config_args="$ft_config_args --exec-prefix=$ft_config_exec_prefix"
-    if test x${FT2_CONFIG+set} != xset ; then
-      FT2_CONFIG=$ft_config_exec_prefix/bin/freetype-config
-    fi
-  fi
-
-  if test x$ft_config_prefix != x ; then
-    ft_config_args="$ft_config_args --prefix=$ft_config_prefix"
-    if test x${FT2_CONFIG+set} != xset ; then
-      FT2_CONFIG=$ft_config_prefix/bin/freetype-config
-    fi
-  fi
-
-  AC_PATH_PROG([FT2_CONFIG], [freetype-config], [no])
-
-  min_ft_version=m4_if([$1], [], [7.0.1], [$1])
-  AC_MSG_CHECKING([for FreeType -- version >= $min_ft_version])
-  no_ft=""
-  if test "$FT2_CONFIG" = "no" ; then
-    no_ft=yes
-  else
-    FT2_CFLAGS=`$FT2_CONFIG $ft_config_args --cflags`
-    FT2_LIBS=`$FT2_CONFIG $ft_config_args --libs`
-    ft_config_major_version=`$FT2_CONFIG $ft_config_args --version | \
-      sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\1/'`
-    ft_config_minor_version=`$FT2_CONFIG $ft_config_args --version | \
-      sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\2/'`
-    ft_config_micro_version=`$FT2_CONFIG $ft_config_args --version | \
-      sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\3/'`
-    ft_min_major_version=`echo $min_ft_version | \
-      sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\1/'`
-    ft_min_minor_version=`echo $min_ft_version | \
-      sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\2/'`
-    ft_min_micro_version=`echo $min_ft_version | \
-      sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\3/'`
-    if test x$enable_fttest = xyes ; then
-      ft_config_is_lt=""
-      if test $ft_config_major_version -lt $ft_min_major_version ; then
-        ft_config_is_lt=yes
-      else
-        if test $ft_config_major_version -eq $ft_min_major_version ; then
-          if test $ft_config_minor_version -lt $ft_min_minor_version ; then
-            ft_config_is_lt=yes
-          else
-            if test $ft_config_minor_version -eq $ft_min_minor_version ; then
-              if test $ft_config_micro_version -lt $ft_min_micro_version ; then
-                ft_config_is_lt=yes
-              fi
-            fi
-          fi
-        fi
-      fi
-      if test x$ft_config_is_lt = xyes ; then
-        no_ft=yes
-      else
-        ac_save_CFLAGS="$CFLAGS"
-        ac_save_LIBS="$LIBS"
-        CFLAGS="$CFLAGS $FT2_CFLAGS"
-        LIBS="$FT2_LIBS $LIBS"
-        dnl
-        dnl Sanity checks for the results of freetype-config to some extent.
-        dnl
-        AC_RUN_IFELSE([
-          AC_LANG_SOURCE([[
-
-#include <ft2build.h>
-#include FT_FREETYPE_H
-#include <stdio.h>
-#include <stdlib.h>
-
-int
-main()
-{
-  FT_Library library;
-  FT_Error  error;
-
-  error = FT_Init_FreeType(&library);
-
-  if (error)
-    return 1;
-  else
-  {
-    FT_Done_FreeType(library);
-    return 0;
-  }
-}
-
-              ]]
-            )],
-            [],
-            [no_ft=yes],
-            [echo $ECHO_N "cross compiling; assuming OK... $ECHO_C"])
-
-        CFLAGS="$ac_save_CFLAGS"
-        LIBS="$ac_save_LIBS"
-      fi             dnl test $ft_config_version -lt $ft_min_version
-    fi               dnl test x$enable_fttest = xyes
-  fi                 dnl test "$FT2_CONFIG" = "no"
-
-  if test x$no_ft = x ; then
-    AC_MSG_RESULT([yes])
-    m4_if([$2], [], [:], [$2])
-  else
-    AC_MSG_RESULT([no])
-    if test "$FT2_CONFIG" = "no" ; then
-      warn_ft2_config = "
-
-The freetype-config script installed by FreeType 2 could not be found.
-If FreeType 2 was installed in PREFIX, make sure PREFIX/bin is in your
-path, or set the FT2_CONFIG environment variable to the full path to
-freetype-config.
-"
-      OCTAVE_CONFIGURE_WARNING([warn_ft2_config])
-    else
-      if test x$ft_config_is_lt = xyes ; then
-        warn_ft2_too_old="
-
-Your installed version of the FreeType 2 library is too old. If you
-have different versions of FreeType 2, make sure that correct values
-for --with-ft-prefix or --with-ft-exec-prefix are used, or set the
-FT2_CONFIG environment variable to the full path to freetype-config.
-"
-        OCTAVE_CONFIGURE_WARNING([warn_ft2_too_old])
-      else
-        warn_ft2_failed="
-
-The FreeType test program failed to run. If your system uses shared
-libraries and they are installed outside the normal system library
-path, make sure the variable LD_LIBRARY_PATH (or whatever is
-appropiate for your system) is correctly set.
-"
-        OCTAVE_CONFIGURE_WARNING([warn_ft2_failed])
-      fi
-    fi
-
-    FT2_CFLAGS=""
-    FT2_LIBS=""
-    m4_if([$3], [], [:], [$3])
-  fi
-
-  AC_SUBST([FT2_CFLAGS])
-  AC_SUBST([FT2_LIBS])
-])
-dnl end of freetype2.m4
-
-
 ##############################################################################
--- a/run-octave.in	Thu Nov 01 15:01:20 2012 -0400
+++ b/run-octave.in	Sun Dec 23 13:00:02 2012 -0500
@@ -80,6 +80,7 @@
 
 OCTAVE_SITE_INITFILE="$top_srcdir/scripts/startup/main-rcfile" \
 OCTAVE_DEFAULT_QT_SETTINGS="$top_srcdir/libgui/default-qt-settings" \
+OCTAVE_JAVA_DIR="$builddir/scripts/java" \
   exec $builddir/libtool --mode=execute $driver \
     "$octave_executable" --no-init-path --path="$LOADPATH" \
     --image-path="$IMAGEPATH" --doc-cache-file="$DOCFILE" \
--- a/scripts/Makefile.am	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/Makefile.am	Sun Dec 23 13:00:02 2012 -0500
@@ -24,6 +24,10 @@
 
 EXTRA_DIST =
 
+CLEANFILES =
+
+DISTCLEANFILES =
+
 FCN_FILE_DIRS =
 
 FCN_FILES =
@@ -36,6 +40,8 @@
 
 IMAGES =
 
+JAR_FILES =
+
 ## Read subdirs to set all variables above
 include @ftp/module.mk
 include audio/module.mk
@@ -46,6 +52,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 +75,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 +125,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 +222,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 +272,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)
@@ -432,10 +447,15 @@
   mkdoc.pl \
   mk-pkg-add
 
-DISTCLEANFILES = \
+DISTCLEANFILES += \
   .DOCSTRINGS \
   DOCSTRINGS \
   $(PKG_ADD_FILES) \
   $(DIRSTAMP_FILES) \
   $(GEN_FCN_FILES)
 
+distclean-local:
+	if [ "x$(srcdir)" != "x." ]; then \
+	  rm $(java_JAVA_IMAGES); \
+	fi
+	
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/deprecated/java_convert_matrix.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,48 @@
+## Copyright (C) 2012 Rik Wehbring
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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  {Built-in Function} {@var{val} =} java_convert_matrix ()
+## @deftypefnx {Built-in Function} {@var{old_val} =} java_convert_matrix (@var{new_val})
+## @deftypefnx {Built-in Function} {} java_convert_matrix (@var{new_val}, \"local\")
+## Query or set the internal variable that controls whether Java arrays are
+## automatically converted to Octave matrices.  The default value is false.
+## 
+## When called from inside a function with the \"local\" option, the variable is
+## changed locally for the function and any subroutines it calls.  The original
+## variable value is restored when exiting the function.
+## @seealso{java_matrix_autoconversion, java_unsigned_conversion, java_debug}
+## @end deftypefn
+
+function old_val = java_convert_matrix (varargin)
+
+  persistent warned = false;
+  if (! warned)
+    warned = true;
+    warning ("Octave:deprecated-function",
+             "java_convert_matrix is obsolete and will be removed from a future version of Octave; use java_matrix_autoconversion instead");
+  endif
+
+  if (nargin > 2)
+    print_usage ();
+  endif
+
+  old_val = java_matrix_autoconversion (varargin{:});
+
+endfunction
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/deprecated/java_debug.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,49 @@
+## Copyright (C) 2012 Rik Wehbring
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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  {Built-in Function} {@var{val} =} java_debug ()
+## @deftypefnx {Built-in Function} {@var{old_val} =} java_debug (@var{new_val})
+## @deftypefnx {Built-in Function} {} java_debug (@var{new_val}, \"local\")
+## Query or set the internal variable that determines whether extra debugging
+## information regarding the initialization of the JVM and any Java exceptions
+## is printed.
+## 
+## When called from inside a function with the \"local\" option, the variable is
+## changed locally for the function and any subroutines it calls.  The original
+## variable value is restored when exiting the function.
+## @seealso{debug_java, java_convert_matrix, java_unsigned_conversion}
+## @end deftypefn
+
+function old_val = java_debug (varargin)
+
+  persistent warned = false;
+  if (! warned)
+    warned = true;
+    warning ("Octave:deprecated-function",
+             "java_debug is obsolete and will be removed from a future version of Octave; use debug_java instead");
+  endif
+
+  if (nargin > 2)
+    print_usage ();
+  endif
+
+  old_val = debug_java (varargin{:});
+
+endfunction
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/deprecated/java_get.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,63 @@
+## Copyright (C) 2012 Rik Wehbring
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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 {Loadable Function} {@var{val} =} java_get (@var{obj}, @var{name})
+## Get the value of the field @var{name} of the Java object @var{obj}.  For
+## static fields, @var{obj} can be a string representing the fully qualified
+## name of the corresponding class.
+## 
+## When @var{obj} is a regular Java object, structure-like indexing can be
+## used as a shortcut syntax.  For instance, the two following statements are
+## equivalent
+## 
+## @example
+## @group
+##   java_get (x, "field1")
+##   x.field1
+## @end group
+## @end example
+## 
+## @seealso{java_set, javaMethod, javaObject}
+## @end deftypefn
+
+function retval = java_get (obj, name)
+
+  persistent warned = false;
+  if (! warned)
+    warned = true;
+    warning ("Octave:deprecated-function",
+             "java_get is obsolete and will be removed from a future version of Octave; use structure-like indexing instead");
+  endif
+
+  if (nargin != 2)
+    print_usage ();
+  endif
+
+  if (isjava (obj))
+    retval = obj.(name);
+  elseif (ischar (obj))
+    ## FIXME: Need a solution for getting static fields of class
+    ##        which does not depend on __java_get__ which will be removed.
+    retval = __java_get__ (obj, name);
+  else
+    error ("java_get: OBJ must be a Java object");
+  endif
+
+endfunction
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/deprecated/java_invoke.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,57 @@
+## Copyright (C) 2007 Michael Goffioul
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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  {Built-in Function} {@var{ret} =} java_invoke (@var{obj}, @var{methodname})
+## @deftypefnx {Built-in Function} {@var{ret} =} java_invoke (@var{obj}, @var{methodname}, @var{arg1}, @dots{})
+## Invoke the method @var{methodname} on the Java object @var{obj} with the
+## arguments @var{arg1}, @dots{}  For static methods, @var{obj} can be a
+## string representing the fully qualified name of the corresponding class. 
+## The function returns the result of the method invocation.
+## 
+## When @var{obj} is a regular Java object, structure-like indexing can be
+## used as a shortcut syntax.  For instance, the two following statements are
+## equivalent
+## 
+## @example
+## @group
+##   ret = java_invoke (x, \"method1\", 1.0, \"a string\")
+##   ret = x.method1 (1.0, \"a string\")
+## @end group
+## @end example
+## 
+## @seealso{javaMethod, javaObject}
+## @end deftypefn
+
+function retval = java_invoke (obj, methodname, varargin)
+
+  persistent warned = false;
+  if (! warned)
+    warned = true;
+    warning ("Octave:deprecated-function",
+             "java_invoke is obsolete and will be removed from a future version of Octave, please use javaMethod instead");
+  endif
+  
+  if (nargin < 2)
+    print_usage ();
+  endif
+
+  retval = javaMethod (methodname, obj, varargin{:});
+
+endfunction
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/deprecated/java_new.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,51 @@
+## Copyright (C) 2012 Rik Wehbring
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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  {Loadable Function} {@var{obj} =} java_new (@var{name})
+## @deftypefnx {Loadable Function} {@var{obj} =} java_new (@var{name}, @var{arg1}, @dots{})
+## Create a Java object of class @var{name}, by calling the class constructor
+## with the arguments @var{arg1}, @dots{}
+## 
+## @example
+## @group
+##   x = java_new ("java.lang.StringBuffer")
+##   x = java_new ("java.lang.StringBuffer", "Initial string")
+## @end group
+## @end example
+## 
+## @seealso{javaObject, javaMethod}
+## @end deftypefn
+
+function retval = java_new (varargin)
+
+  persistent warned = false;
+  if (! warned)
+    warned = true;
+    warning ("Octave:deprecated-function",
+             "java_new is obsolete and will be removed from a future version of Octave; please use javaObject instead");
+  endif
+
+  if (nargin < 1)
+    print_usage ();
+  endif
+
+  retval = javaObject (varargin{:});
+
+endfunction
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/deprecated/java_set.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,63 @@
+## Copyright (C) 2012 Rik Wehbring
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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 {Loadable Function} {@var{obj} =} java_set (@var{obj}, @var{name}, @var{val})
+## Set the value of the field @var{name} of the Java object @var{obj} to
+## @var{val}.  For static fields, @var{obj} can be a string representing the
+## fully qualified named of the corresponding Java class.
+## 
+## When @var{obj} is a regular Java object, structure-like indexing can be
+## used as a shortcut syntax.  For instance, the two following statements are
+## equivalent
+## 
+## @example
+## @group
+##   java_set (x, "field1", val)
+##   x.field1 = val
+## @end group
+## @end example
+## 
+## @seealso{java_get, javaMethod, javaObject}
+## @end deftypefn
+
+function retval = java_set (obj, name, val)
+
+  persistent warned = false;
+  if (! warned)
+    warned = true;
+    warning ("Octave:deprecated-function",
+             "java_set is obsolete and will be removed from a future version of Octave; use structure-like indexing instead");
+  endif
+
+  if (nargin != 3)
+    print_usage ();
+  endif
+
+  if (isjava (obj))
+    obj.(name) = val;
+  elseif (ischar (obj))
+    ## FIXME: Need a solution for getting static fields of class
+    ##        which does not depend on __java_set__ which will be removed.
+    retval = __java_set__ (obj, name, val);
+  else
+    error ("java_set: OBJ must be a Java object");
+  endif
+
+endfunction
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/deprecated/java_unsigned_conversion.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,50 @@
+## Copyright (C) 2012 Rik Wehbring
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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  {Built-in Function} {@var{val} =} java_unsigned_conversion ()
+## @deftypefnx {Built-in Function} {@var{old_val} =} java_unsigned_conversion (@var{new_val})
+## @deftypefnx {Built-in Function} {} java_unsigned_conversion (@var{new_val}, \"local\")
+## Query or set the internal variable that controls how integer classes are
+## converted when Java matrix autoconversion is enabled.  When enabled, Java
+## arrays of class Byte or Integer are converted to matrices of class uint8 or
+## uint32 respectively.
+## 
+## When called from inside a function with the \"local\" option, the variable is
+## changed locally for the function and any subroutines it calls.  The original
+## variable value is restored when exiting the function.
+## @seealso{java_unsigned_autoconversion, java_convert_matrix, debug_java}
+## @end deftypefn
+
+function old_val = java_unsigned_conversion (varargin)
+
+  persistent warned = false;
+  if (! warned)
+    warned = true;
+    warning ("Octave:deprecated-function",
+             "java_unsigned_conversion is obsolete and will be removed from a future version of Octave; use java_unsigned_autoconversion instead");
+  endif
+
+  if (nargin > 2)
+    print_usage ();
+  endif
+
+  old_val = java_unsigned_autoconversion (varargin{:});
+
+endfunction
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/deprecated/javafields.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,54 @@
+## Copyright (C) 2007 Michael Goffioul
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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} {} javafields (@var{javaobj})
+## @deftypefnx {Function File} {} javafields ("@var{classname}")
+## @deftypefnx {Function File} {@var{fld_names} =} javafields (@dots{})
+## Return the fields of a Java object or Java class in the form of a cell 
+## array of strings.  If no output is requested, print the result
+## to the standard output.
+## @seealso{fieldnames, methods, javaObject}
+## @end deftypefn
+
+function fld_names = javafields (javaobj)
+
+  persistent warned = false;
+  if (! warned)
+    warned = true;
+    warning ("Octave:deprecated-function",
+             "javafields is obsolete and will be removed from a future version of Octave, please use fieldnames instead");
+  endif
+  
+  if (nargin != 1)
+    print_usage ();
+  endif
+  
+  c_methods = javaMethod ("getFields", "org.octave.ClassHelper", javaobj);
+  method_list = strsplit (c_methods, ';');
+
+  if (nargout == 0)
+    if (! isempty (method_list))
+      disp (method_list);
+    endif
+  else
+    fld_names = cellstr (method_list);
+  endif
+
+endfunction
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/deprecated/javamethods.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,54 @@
+## Copyright (C) 2007 Michael Goffioul
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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} {} javamethods (@var{javaobj})
+## @deftypefnx {Function File} {} javamethods ("@var{classname}")
+## @deftypefnx {Function File} {@var{mtd_names} =} javamethods (@dots{})
+## Return the methods of a Java object or Java class in the form of a cell 
+## array of strings.  If no output is requested, print the result to the
+## standard output.
+## @seealso{methods, fieldnames, javaMethod, javaObject}
+## @end deftypefn
+
+function mtd_names = javamethods (classname)
+
+  persistent warned = false;
+  if (! warned)
+    warned = true;
+    warning ("Octave:deprecated-function",
+             "javamethods is obsolete and will be removed from a future version of Octave, please use methods instead");
+  endif
+  
+  if (nargin != 1)
+    print_usage ();
+  endif
+
+  cls_methods = javaMethod ("getMethods", "org.octave.ClassHelper", classname);
+  method_list = strsplit (cls_methods, ';');
+
+  if (nargout == 0)
+    if (! isempty (method_list))
+      disp (method_list);
+    endif
+  else
+    mtd_names = cellstr (method_list);
+  endif
+
+endfunction
+
--- a/scripts/deprecated/module.mk	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/deprecated/module.mk	Sun Dec 23 13:00:02 2012 -0500
@@ -5,8 +5,17 @@
   deprecated/cor.m \
   deprecated/corrcoef.m \
   deprecated/cut.m \
+  deprecated/java_debug.m \
   deprecated/error_text.m \
   deprecated/isstr.m \
+  deprecated/java_convert_matrix.m \
+  deprecated/java_get.m \
+  deprecated/java_invoke.m \
+  deprecated/java_new.m \
+  deprecated/java_unsigned_conversion.m \
+  deprecated/java_set.m \
+  deprecated/javafields.m \
+  deprecated/javamethods.m \
   deprecated/polyderiv.m \
   deprecated/setstr.m \
   deprecated/shell_cmd.m \
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/general/fieldnames.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,78 @@
+## Copyright (C) 2012 Rik Wehbring
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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} {@var{names} =} fieldnames (@var{struct})
+## @deftypefnx {Function File} {@var{names} =} fieldnames (@var{obj})
+## @deftypefnx {Function File} {@var{names} =} fieldnames (@var{javaobj})
+## @deftypefnx {Function File} {@var{names} =} fieldnames ("@var{jclassname}")
+## Return a cell array of strings with the names of the fields in the
+## specified input.
+##
+## When the input is a structure @var{struct}, the names are the elements
+## of the structure.
+##
+## When the input is an Octave object @var{obj}, the names are the public
+## properties of the object.
+##
+## When the input is a Java object @var{javaobj} or Java classname
+## @var{jclassname}) the name are the public data elements of the object or
+## class.
+## @seealso{struct, methods}
+## @end deftypefn
+
+function names = fieldnames (obj)
+  
+  if (nargin != 1)
+    print_usage ();
+  endif
+  
+  if (isstruct (obj) || isobject (obj))
+    ## Call internal C++ function for structs or Octave objects
+    names = __fieldnames__ (obj);
+  elseif (isjava (obj) || ischar (obj))
+    ## FIXME: Function prototype that excepts java obj exists, but doesn't
+    ##        work if obj is java.lang.String.  Convert obj to classname.
+    if (! ischar (obj))
+      obj = class (obj);
+    endif
+    names_str = javaMethod ("getFields", "org.octave.ClassHelper", obj);
+    names = strsplit (names_str, ';');
+  else
+    error ("fieldnames: Invalid input argument"); 
+  endif
+
+endfunction
+
+
+## test preservation of fieldname order
+%!test
+%! x(3).d=1;  x(2).a=2;  x(1).b=3;  x(2).c=3;
+%! assert (fieldnames (x), {"d"; "a"; "b"; "c"});
+
+## test empty structure
+%!test
+%! s = struct ();
+%! assert (fieldnames (s), cell (0, 1));
+
+## test Java classname
+%!testif HAVE_JAVA 
+%! names = fieldnames ("java.lang.Double");
+%! search = strfind (names, "java.lang.Double.MAX_VALUE");
+%! assert (! isempty ([search{:}]));
+
--- a/scripts/general/isa.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/general/isa.m	Sun Dec 23 13:00:02 2012 -0500
@@ -17,35 +17,44 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {} isa (@var{obj}, @var{class})
-## Return true if @var{obj} is an object from the class @var{class}.
+## @deftypefn {Function File} {} isa (@var{obj}, @var{classname})
+## Return true if @var{obj} is an object from the class @var{classname}.
+##
+## @var{classname} may also be one of the following class categories: 
+##
+## @table @asis
+## @item "float"
+## Floating point value comprising classes "double" and "single".
+##
+## @item "integer"
+## Integer value comprising classes (u)int8, (u)int16, (u)int32, (u)int64.
+##
+## @item "numeric"
+## Numeric value comprising either a floating point or integer value.
+## @end table
 ## @seealso{class, typeinfo}
 ## @end deftypefn
 
 ## Author: Paul Kienzle <pkienzle@users.sf.net>
 ## Adapted-by: jwe
 
-function retval = isa (obj, cname)
+function retval = isa (obj, classname)
 
   if (nargin != 2)
     print_usage ();
   endif
 
-  persistent float_classes = {"double", "single"};
-
-  persistent fnum_classes = {"double", "single", ...
-                             "uint8", "uint16", "uint32", "uint64", ...
-                             "int8", "int16", "int32", "int64"};
-
-  if (strcmp (cname, "float"))
-    retval = any (strcmp (class (obj), float_classes));
-  elseif (strcmp (cname, "numeric"))
-    retval = any (strcmp (class (obj), fnum_classes));
+  if (strcmp (classname, "float"))
+    retval = isfloat (obj);
+  elseif (strcmp (classname, "integer"))
+    retval = isinteger (obj);
+  elseif (strcmp (classname, "numeric"))
+    retval = isnumeric (obj);
   else
-    class_of_x = class (obj);
-    retval = strcmp (class_of_x, cname);
+    class_of_obj = class (obj);
+    retval = strcmp (class_of_obj, classname);
     if (! retval && isobject (obj))
-      retval = __isa_parent__ (obj, cname);
+      retval = __isa_parent__ (obj, classname);
     endif
   endif
 
@@ -76,6 +85,9 @@
 %!assert (isa (uint16 (13), "numeric"), true)
 %!assert (isa (uint32 (13), "numeric"), true)
 %!assert (isa (uint64 (13), "numeric"), true)
+%!assert (isa (uint8 (13), "integer"), true)
+%!assert (isa (double (13), "integer"), false)
+%!assert (isa (single (13), "integer"), false)
 
 %!assert (isa (double (13), "double"))
 %!assert (isa (single (13), "single"))
--- a/scripts/general/logspace.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/general/logspace.m	Sun Dec 23 13:00:02 2012 -0500
@@ -85,10 +85,10 @@
 %! x2 = logspace (1, 2, 10.1);
 %! x3 = logspace (1, -2, 10);
 %! x4 = logspace (1, pi, 10);
-%! assert (size (x1) == [1, 50] && x1(1) == 10 && x1(50) == 100);
-%! assert (size (x2) == [1, 10] && x2(1) == 10 && x2(10) == 100);
-%! assert (size (x3) == [1, 10] && x3(1) == 10 && x3(10) == 0.01);
-%! assert (size (x4) == [1, 10] && x4(1) == 10 && abs (x4(10) - pi) < sqrt (eps));
+%! assert (size (x1) == [1, 50] && abs (x1(1) - 10) < eps && abs (x1(50) - 100) < eps);
+%! assert (size (x2) == [1, 10] && abs (x2(1) - 10) < eps && abs (x2(10) - 100) < eps);
+%! assert (size (x3) == [1, 10] && abs (x3(1) - 10) < eps && abs (x3(10) - 0.01) < eps);
+%! assert (size (x4) == [1, 10] && abs (x4(1) - 10) < eps && abs (x4(10) - pi) < sqrt (eps));
 
 %% Test input validation
 %!error logspace ()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/general/methods.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,79 @@
+## Copyright (C) 2012 Rik Wehbring
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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} {} methods (@var{obj})
+## @deftypefnx {Function File} {} methods ("@var{classname}")
+## @deftypefnx {Function File} {@var{mtds} =} methods (@dots{})
+##
+## Return a cell array containing the names of the methods for the
+## object @var{obj} or the named class @var{classname}.
+## @var{obj} may be an Octave class object or a Java object.
+##
+## @seealso{fieldnames}
+## @end deftypefn
+
+function mtds = methods (obj)
+  
+  if (nargin != 1)
+    print_usage ();
+  endif
+  
+  if (isobject (obj))
+    ## Call internal C++ function for Octave objects
+    mtds_list = __methods__ (obj);
+  elseif (ischar (obj))
+    ## Could be a classname for an Octave class or Java class.
+    ## Try Octave class first.
+    mtds_list = __methods__ (obj);
+    if (isempty (mtds_list))
+      mtds_str = javaMethod ("getMethods", "org.octave.ClassHelper", obj);
+      mtds_list = strsplit (mtds_str, ';');
+    endif
+  elseif (isjava (obj))
+    ## FIXME: Function prototype that excepts java obj exists, but doesn't
+    ##        work if obj is java.lang.String.  Convert obj to classname.
+    obj = class (obj);
+    mtds_str = javaMethod ("getMethods", "org.octave.ClassHelper", obj);
+    mtds_list = strsplit (mtds_str, ';');
+  else
+    error ("methods: Invalid input argument");
+  endif
+
+  if (nargout == 0)
+    classname = ifelse (ischar (obj), obj, class (obj));
+    printf ("Methods for class %s:\n", classname);
+    disp (list_in_columns (mtds_list));
+  else
+    mtds = mtds_list;
+  endif
+
+endfunction
+
+
+## test Octave classname
+%!test
+%! mtds = methods ("ftp");
+%! assert (mtds{1}, "ascii");
+
+## test Java classname
+%!testif HAVE_JAVA 
+%! mtds = methods ("java.lang.Double");
+%! search = strfind (mtds, "java.lang.Double valueOf");
+%! assert (! isempty ([search{:}]));
+
--- a/scripts/general/module.mk	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/general/module.mk	Sun Dec 23 13:00:02 2012 -0500
@@ -28,6 +28,7 @@
   general/del2.m \
   general/display.m \
   general/divergence.m \
+  general/fieldnames.m \
   general/flipdim.m \
   general/fliplr.m \
   general/flipud.m \
@@ -52,6 +53,7 @@
   general/isvector.m \
   general/loadobj.m \
   general/logspace.m \
+  general/methods.m \
   general/nargchk.m \
   general/narginchk.m \
   general/nargoutchk.m \
--- a/scripts/general/num2str.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/general/num2str.m	Sun Dec 23 13:00:02 2012 -0500
@@ -83,8 +83,14 @@
       endif
     else
       if (isnumeric (x))
-        ## Setup a suitable format string
-        dgt = floor (log10 (max (abs (x(:)))));
+        ## Setup a suitable format string, ignoring inf entries
+        dgt = floor (log10 (max (abs (x(!isinf (x(:)))))));
+
+        ## If the whole input array is inf...
+        if (isempty (dgt))
+          dgt = 0;
+        endif
+
         if (any (x(:) != fix (x(:))))
           ## Floating point input
           dgt = max (dgt + 4, 5);   # Keep 4 sig. figures after decimal point
@@ -169,6 +175,8 @@
 %!assert (num2str (-2^33), "-8589934592")
 %!assert (num2str (2^33+1i), "8589934592+1i")
 %!assert (num2str (-2^33+1i), "-8589934592+1i")
+%!assert (num2str (inf), "Inf")
+%!assert (num2str (nan), "NaN")
 
 ## FIXME: Integers greater than bitmax() should be masked to show just
 ##        16 digits of precision.
--- a/scripts/general/quadgk.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/general/quadgk.m	Sun Dec 23 13:00:02 2012 -0500
@@ -141,7 +141,7 @@
 
     if (nargin > 3)
       if (! ischar (varargin{1}))
-        if (!isempty (varargin{1}))
+        if (! isempty (varargin{1}))
           abstol = varargin{1};
           reltol = 0;
         endif
@@ -170,14 +170,14 @@
             elseif (strcmpi (str, "trace"))
               trace = varargin{idx++};
             else
-              error ("quadgk: unknown property %s", str);
+              error ("quadgk: unknown property '%s'", str);
             endif
           else
-            error ("quadgk: expecting property to be a string");
+            error ("quadgk: property PROP must be a string");
           endif
         endwhile
         if (idx != nargin - 2)
-          error ("quadgk: expecting properties in pairs");
+          error ("quadgk: property/value must occur in pairs");
         endif
       endif
     endif
@@ -188,8 +188,8 @@
     endif
 
     ## Use variable subsitution to weaken endpoint singularities and to
-    ## perform integration with endpoints at infinity. No transform for
-    ## contour integrals
+    ## perform integration with endpoints at infinity.  No transform for
+    ## contour integrals.
     if (iscomplex (a) || iscomplex (b) || iscomplex (waypoints))
       ## contour integral, no transform
       subs = [a; waypoints; b];
@@ -197,14 +197,14 @@
       h0 = h;
       trans = @(t) t;
     elseif (isinf (a) && isinf (b))
-      ## Standard Infinite to finite integral transformation.
+      ## Standard infinite to finite integral transformation.
       ##   \int_{-\infinity_^\infinity f(x) dx = \int_-1^1 f (g(t)) g'(t) dt
       ## where
       ##   g(t)  = t / (1 - t^2)
       ##   g'(t) =  (1 + t^2) / (1 - t^2) ^ 2
       ## waypoint transform is then
       ##   t =  (2 * g(t)) ./ (1 + sqrt(1 + 4 * g(t) .^ 2))
-      if (!isempty (waypoints))
+      if (! isempty (waypoints))
         trans = @(x) (2 * x) ./ (1 + sqrt (1 + 4 * x .^ 2));
         subs = [-1; trans(waypoints); 1];
       else
@@ -214,7 +214,7 @@
       h0 = b - a;
       trans = @(t) t ./ (1 - t.^2);
       f = @(t) f (t ./ (1 - t .^ 2)) .* (1 + t .^ 2) ./ ((1 - t .^ 2) .^ 2);
-    elseif (isinf(a))
+    elseif (isinf (a))
       ## Formula defined in Shampine paper as two separate steps. One to
       ## weaken singularity at finite end, then a second to transform to
       ## a finite interval. The singularity weakening transform is
@@ -229,7 +229,7 @@
       ## waypoint transform is then
       ##   t = sqrt (b - x)
       ##   s =  - t / (t + 1)
-      if (!isempty (waypoints))
+      if (! isempty (waypoints))
         tmp = sqrt (b - waypoints);
         trans = @(x)  - x ./ (x + 1);
         subs = [-1; trans(tmp); 0];
@@ -254,7 +254,7 @@
       ## waypoint transform is then
       ##   t = sqrt (x - a)
       ##   s = t / (t + 1)
-      if (!isempty (waypoints))
+      if (! isempty (waypoints))
         tmp = sqrt (waypoints - a);
         trans = @(x) x ./ (x + 1);
         subs = [0; trans(tmp); 1];
@@ -297,99 +297,96 @@
     endwhile
     subs = [subs(1:end-1), subs(2:end)];
 
-    warn_state = warning ("query", "Octave:divide-by-zero");
+    ## Singularity will cause divide by zero warnings.
+    ## Turn off warning locally for quadgk function only.
+    warning ("off", "Octave:divide-by-zero", "local");
+
+    warn_id = "Octave:quadgk:warning-termination";
 
-    unwind_protect
-      ## Singularity will cause divide by zero warnings
-      warning ("off", "Octave:divide-by-zero");
+    ## Initial evaluation of the integrand on the subintervals
+    [q_subs, q_errs] = __quadgk_eval__ (f, subs);
+    q0 = sum (q_subs);
+    err0 = sum (q_errs);
+
+    if (isa (a, "single") || isa (b, "single") || isa (waypoints, "single"))
+      myeps = eps ("single");
+    else
+      myeps = eps;
+    endif
 
-      ## Initial evaluation of the integrand on the subintervals
-      [q_subs, q_errs] = __quadgk_eval__ (f, subs);
-      q0 = sum (q_subs);
-      err0 = sum (q_errs);
+    first = true;
+    while (true)
+      ## Check for subintervals that are too small. Test must be
+      ## performed in untransformed subintervals. What is a good
+      ## value for this test. Shampine suggests 100*eps
+      if (any (abs (diff (trans (subs), [], 2) / h0) < 100 * myeps))
+        q = q0;
+        err = err0;
+        break;
+      endif
 
-      if (isa (a, "single") || isa (b, "single") || isa (waypoints, "single"))
-        myeps = eps ("single");
-      else
-        myeps = eps;
+      ## Quit if any evaluations are not finite (Inf or NaN)
+      if (any (! isfinite (q_subs)))
+        warning (warn_id, "quadgk: non finite integrand encountered");
+        q = q0;
+        err = err0;
+        break;
+      endif
+
+      tol = max (abstol, reltol .* abs (q0));
+
+      ## If the global error estimate is meet exit
+      if (err0 < tol)
+        q = q0;
+        err = err0;
+        break;
       endif
 
-      first = true;
-      while (true)
-        ## Check for subintervals that are too small. Test must be
-        ## performed in untransformed subintervals. What is a good
-        ## value for this test. Shampine suggests 100*eps
-        if (any (abs (diff (trans (subs), [], 2) / h0) < 100 * myeps))
-          q = q0;
-          err = err0;
-          break;
-        endif
+      ## Accept the subintervals that meet the convergence criteria
+      idx = find (abs (q_errs) < tol .* abs (diff (subs, [], 2)) ./ h);
+      if (first)
+        q = sum (q_subs (idx));
+        err = sum (q_errs(idx));
+        first = false;
+      else
+        q0 = q + sum (q_subs);
+        err0 = err + sum (q_errs);
+        q += sum (q_subs (idx));
+        err += sum (q_errs(idx));
+      endif
+      subs(idx,:) = [];
 
-        ## Quit if any evaluations are not finite (Inf or NaN)
-        if (any (! isfinite (q_subs)))
-          warning ("quadgk: non finite integrand encountered");
-          q = q0;
-          err = err0;
-          break;
-        endif
+      ## If no remaining subintervals exit
+      if (rows (subs) == 0)
+        break;
+      endif
 
-        tol = max (abstol, reltol .* abs (q0));
-
-        ## If the global error estimate is meet exit
-        if (err0 < tol)
-          q = q0;
-          err = err0;
-          break;
-        endif
+      if (trace)
+        disp ([rows(subs), err, q0]);
+      endif
 
-        ## Accept the subintervals that meet the convergence criteria
-        idx = find (abs (q_errs) < tol .* abs (diff (subs, [], 2)) ./ h);
-        if (first)
-          q = sum (q_subs (idx));
-          err = sum (q_errs(idx));
-          first = false;
-        else
-          q0 = q + sum (q_subs);
-          err0 = err + sum (q_errs);
-          q += sum (q_subs (idx));
-          err += sum (q_errs(idx));
-        endif
-        subs(idx,:) = [];
-
-        ## If no remaining subintervals exit
-        if (rows (subs) == 0)
-          break;
-        endif
-
-        if (trace)
-          disp ([rows(subs), err, q0]);
-        endif
+      ## Split remaining subintervals in two
+      mid = (subs(:,2) + subs(:,1)) ./ 2;
+      subs = [subs(:,1), mid; mid, subs(:,2)];
 
-        ## Split remaining subintervals in two
-        mid = (subs(:,2) + subs(:,1)) ./ 2;
-        subs = [subs(:,1), mid; mid, subs(:,2)];
-
-        ## If the maximum subinterval count is met accept remaining
-        ## subinterval and exit
-        if (rows (subs) > maxint)
-          warning ("quadgk: maximum interval count (%d) met", maxint);
-          q += sum (q_subs);
-          err += sum (q_errs);
-          break;
-        endif
+      ## If the maximum subinterval count is met accept remaining
+      ## subinterval and exit
+      if (rows (subs) > maxint)
+        warning (warn_id, "quadgk: maximum interval count (%d) met", maxint);
+        q += sum (q_subs);
+        err += sum (q_errs);
+        break;
+      endif
 
-        ## Evaluation of the integrand on the remaining subintervals
-        [q_subs, q_errs] = __quadgk_eval__ (f, subs);
-      endwhile
+      ## Evaluation of the integrand on the remaining subintervals
+      [q_subs, q_errs] = __quadgk_eval__ (f, subs);
+    endwhile
 
-      if (err > max (abstol, reltol * abs (q)))
-        warning ("quadgk: Error tolerance not met. Estimated error %g", err);
-      endif
-    unwind_protect_cleanup
-      if (strcmp (warn_state.state, "on"))
-        warning ("on", "Octave:divide-by-zero");
-      endif
-    end_unwind_protect
+    if (err > max (abstol, reltol * abs (q)))
+      warning (warn_id,
+               "quadgk: Error tolerance not met.  Estimated error %g", err);
+    endif
+
   endif
 endfunction
 
@@ -460,4 +457,3 @@
 %error (quadgk (@sin))
 %error (quadgk (@sin, -pi))
 %error (quadgk (@sin, -pi, pi, "DummyArg"))
-
--- a/scripts/help/__makeinfo__.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/help/__makeinfo__.m	Sun Dec 23 13:00:02 2012 -0500
@@ -116,7 +116,7 @@
   unwind_protect
     ## Write Texinfo to tmp file
     template = "octave-help-XXXXXX";
-    [fid, name] = mkstemp (fullfile (P_tmpdir, template), true);
+    [fid, name] = mkstemp (fullfile (tempdir, template), true);
     if (fid < 0)
       error ("__makeinfo__: could not create temporary file");
     endif
--- a/scripts/image/autumn.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/autumn.m	Sun Dec 23 13:00:02 2012 -0500
@@ -37,7 +37,7 @@
     n = rows (colormap);
   elseif (nargin == 1)
     if (! isscalar (n))
-      error ("autumn: argument must be a scalar");
+      error ("autumn: N must be a scalar");
     endif
   else
     print_usage ();
--- a/scripts/image/bone.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/bone.m	Sun Dec 23 13:00:02 2012 -0500
@@ -37,7 +37,7 @@
     n = rows (colormap);
   elseif (nargin == 1)
     if (! isscalar (n))
-      error ("bone: argument must be a scalar");
+      error ("bone: N must be a scalar");
     endif
   else
     print_usage ();
--- a/scripts/image/brighten.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/brighten.m	Sun Dec 23 13:00:02 2012 -0500
@@ -33,22 +33,25 @@
 ## @end deftypefn
 
 function rmap = brighten (arg1, beta)
+
+  if (nargin < 1 || nargin > 2)
+    print_usage ();
+  endif
+
   h = -1;
   if (nargin == 1)
     beta = arg1;
-    m = colormap;
+    m = colormap ();
     h = gcf ();
-  elseif (nargin == 2)
+  else
     if (ishandle (arg1))
       h = arg1;
       m = get (h, "colormap");
-    elseif (ismatrix (arg1) && columns (arg1) == 3)
+    elseif (iscolormap (arg1))
       m = arg1;
     else
-      error ("brighten: first argument must be an Nx3 matrix or a handle");
+      error ("brighten: first argument must be a colormap or a graphics handle");
     endif
-  else
-    print_usage ();
   endif
 
   if (! isscalar (beta) || beta <= -1 || beta >= 1)
@@ -72,3 +75,22 @@
   endif
 
 endfunction
+
+
+%!demo
+%! ## First figure uses default grayscale colormap
+%! figure;
+%! colormap (gray (64));
+%! image (1:64, linspace (0, 1, 64), repmat ((1:64)', 1, 64));
+%! axis ([1, 64, 0, 1], "ticy", "xy");
+%! title ("default grayscale colormap");
+%! pos = get (gcf, "position");
+%! pos(1) += pos(3) + 25;
+%! ## Second figure uses brightened grayscale colormap
+%! figure ("position", pos);
+%! colormap (gray (64));
+%! image (1:64, linspace (0, 1, 64), repmat ((1:64)', 1, 64));
+%! axis ([1, 64, 0, 1], "ticy", "xy");
+%! brighten (0.5);
+%! title ("grayscale colormap brightened by 0.5");
+
--- a/scripts/image/cmpermute.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/cmpermute.m	Sun Dec 23 13:00:02 2012 -0500
@@ -25,8 +25,7 @@
 ## When called with only two arguments, @code{cmpermute} randomly rearranges
 ## the colormap @var{map} and returns a new colormap @var{newmap}.  It also
 ## returns the indexed image @var{Y} which is the equivalent of the original
-## input image @var{X} when displayed using @var{newmap}.  The input image
-## @var{X} must be an indexed image of class uint8 or double.
+## input image @var{X} when displayed using @var{newmap}.  
 ##
 ## When called with an optional third argument the order of colors in the
 ## new colormap is defined by @var{index}.
@@ -44,9 +43,9 @@
     print_usage ();
   endif
 
-  ## FIXME: Matlab only accepts 2 types.  Expand to uint16 & single??
-  if (! (isa (X, "uint8") || isa (X, "double")))
-    error ("cmpermute: X must be of class uint8 or double");
+  cls = class (X);
+  if (! any (strcmp (cls, {"uint8", "uint16", "single", "double"})))
+    error ("cmpermute: invalid data type '%s'", cls);
   endif
 
   if (! isreal (X) || issparse (X)
@@ -71,13 +70,17 @@
   rindex = zeros (size (index));
   rindex(index) = 1:length (index);
  
-  ## adapt indices
-  if (isa (X, "uint8"))
-    rindex = uint8 (rindex-1);
+  ## preserve class of input image in output
+  if (strcmp (cls, "double")) 
+    Y = rindex(X);
+  elseif (strcmp (cls, "single")) 
+    rindex = single (rindex);
+    Y = rindex(X);
+  else
+    ## adapt indices
+    rindex = feval (cls, rindex - 1);
     ## 0-based indices
-    Y = rindex(double (X) + 1);
-  else
-    Y = rindex(X);
+    Y = rindex(single (X) + 1);
   endif
 
 endfunction
@@ -126,7 +129,7 @@
 ## Test input validation
 %!error cmpermute ()
 %!error cmpermute (1,2,3,4)
-%!error <X must be of class uint8> cmpermute (uint16 (magic (16)), jet (256))
+%!error <invalid data type 'uint32'> cmpermute (uint32 (magic (16)), jet (256))
 %!error <X must be an indexed image> cmpermute (1+i, jet (256))
 %!error <X must be an indexed image> cmpermute (sparse (1), jet (256))
 %!error <X must be an indexed image> cmpermute (0, jet (256))
--- a/scripts/image/cmunique.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/cmunique.m	Sun Dec 23 13:00:02 2012 -0500
@@ -61,8 +61,7 @@
   endif
 
   cls = class (X);
-  ## FIXME: Documentation accepts only 3 classes.  Could easily add 'single'.
-  if (! any (isa (X, {"uint8", "uint16", "double"})))
+  if (! any (strcmp (cls, {"uint8", "uint16", "single", "double"})))
     error ("cmunique: X is of invalid data type '%s'", cls);
   endif
 
@@ -72,10 +71,10 @@
       error ("cmunique: MAP must be a valid colormap");
     endif
     [newmap,i,j] = unique (map, "rows");  # calculate unique colormap
-    if (isa (X, "double"))
+    if (isfloat (X))
       Y = j(X);               # find new indices
     else
-      Y = j(double (X) + 1);  # find new indices
+      Y = j(double (X) + 1);  # find new indices, switch to 1-based index
     endif
   else
     switch (size (X,3))
@@ -95,13 +94,13 @@
     endswitch
     
     ## if image was uint8 or uint16 we have to convert newmap to [0,1] range
-    if (! isa (X, "double"))
-      newmap = double (newmap) / double (intmax (class (X)));
+    if (isinteger (X))
+      newmap = double (newmap) / double (intmax (cls));
     endif
   endif
 
   if (rows (newmap) <= 256)
-    ## convert Y to uint8 (0-based indices then)
+    ## convert Y to uint8 and 0-based indexing
     Y = uint8 (Y-1);
   endif
 
@@ -184,15 +183,15 @@
 %!test
 %! I = uint16 (rand (10,10)*65535);
 %! Id = double (I) / 65535;
-%! [Y,newmap] = cmunique (I);
-%! assert (Id,newmap (:,1)(Y+1));
-%! assert (Id,newmap (:,2)(Y+1));
-%! assert (Id,newmap (:,3)(Y+1));
+%! [Y, newmap] = cmunique (I);
+%! assert (Id, newmap(:,1)(Y+1));
+%! assert (Id, newmap(:,2)(Y+1));
+%! assert (Id, newmap(:,3)(Y+1));
 
 ## Test input validation
 %!error cmpermute ()
 %!error cmpermute (1,2,3)
-%!error <X is of invalid data type> cmunique (single (magic (16)))
+%!error <X is of invalid data type> cmunique (uint32 (magic (16)))
 %!error <MAP must be a valid colormap> cmunique (1, "a")
 %!error <MAP must be a valid colormap> cmunique (1, i)
 %!error <MAP must be a valid colormap> cmunique (1, ones (3,3,3))
--- a/scripts/image/colorcube.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/colorcube.m	Sun Dec 23 13:00:02 2012 -0500
@@ -35,7 +35,7 @@
     n = rows (colormap);
   elseif (nargin == 1)
     if (! isscalar (n))
-      error ("colorcube: argument must be a scalar");
+      error ("colorcube: N must be a scalar");
     endif
   else
     print_usage ();
--- a/scripts/image/colormap.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/colormap.m	Sun Dec 23 13:00:02 2012 -0500
@@ -22,8 +22,8 @@
 ## @deftypefnx {Function File} {@var{cmap} =} colormap (@var{map})
 ## @deftypefnx {Function File} {@var{cmap} =} colormap ("default")
 ## @deftypefnx {Function File} {@var{cmap} =} colormap ("list")
-## @deftypefnx {Function File} {@var{cmap} =} colormap ("register", "name")
-## @deftypefnx {Function File} {@var{cmap} =} colormap ("unregister", "name")
+## @deftypefnx {Function File} {@var{cmap} =} colormap ("register", "@var{name}")
+## @deftypefnx {Function File} {@var{cmap} =} colormap ("unregister", "@var{name}")
 ## Query or set the current colormap.
 ##
 ## @code{colormap (@var{map})} sets the current colormap to @var{map}.  The
@@ -68,11 +68,12 @@
     endif
 
     if (! isempty (map))
-      if (columns (map) != 3)
-        error ("colormap: MAP must have 3 columns: [R,G,B]");
+      if (! (isnumeric (map) && isreal (map)
+             && ndims (map) == 2 && columns (map) == 3))
+        error ("colormap: MAP must be a real-valued N x 3 ([R,G,B]) matrix");
       endif
-      if (min (min (map)) < 0 || max (max (map)) > 1)
-        error ("colormap: MAP must have values in [0,1]");
+      if (any (map(:) < 0) || any (map(:) > 1))
+        error ("colormap: all MAP values must be in the range [0,1]");
       endif
       ## Set the new color map
       set (gcf (), "colormap", map);
@@ -96,3 +97,6 @@
   endif
 
 endfunction
+
+
+%% FIXME: Need some demos/tests
--- a/scripts/image/contrast.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/contrast.m	Sun Dec 23 13:00:02 2012 -0500
@@ -17,18 +17,18 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn  {Function File} {@var{map} =} contrast (@var{x})
-## @deftypefnx {Function File} {@var{map} =} contrast (@var{x}, @var{n})
+## @deftypefn  {Function File} {@var{cmap} =} contrast (@var{x})
+## @deftypefnx {Function File} {@var{cmap} =} contrast (@var{x}, @var{n})
 ## Return a gray colormap that maximizes the contrast in an image.  The
 ## returned colormap will have @var{n} rows.  If @var{n} is not defined
 ## then the size of the current colormap is used.
 ## @seealso{colormap, brighten}
 ## @end deftypefn
 
-function map = contrast (x, n)
+function cmap = contrast (x, n)
 
   if (nargin == 1)
-    n = rows (colormap);
+    n = rows (colormap ());
   elseif (nargin == 2)
     if (! isscalar (n))
       error ("contrast: N must be a scalar");
@@ -39,22 +39,22 @@
 
   x = x(:);
   minx = min (x);
-  map = find (diff (sort ([round(n * ((x - minx) ./ (max(x) - minx))); [0:n]'])));
-  minm = min (map);
-  map = (map - minm) ./ (max (map) - minm);
-  map = [map, map, map];
+  cmap = find (diff (sort ([round(n * ((x - minx) ./ (max(x) - minx))); [0:n]'])));
+  minm = min (cmap);
+  cmap = (cmap - minm) ./ (max (cmap) - minm);
+  cmap = [cmap, cmap, cmap];
 
 endfunction
 
 
 %!demo
-%! clf;
+%! figure;
 %! img = reshape (1:100, 10, 10);
 %! imagesc (img);
 %! colormap (gray (64));
 %! title ("Image with default 64 gray levels");
 %! pos = get (gcf, "position");
-%! pos(1) += pos(3) + 15;
+%! pos(1) += pos(3) + 25;
 %! figure ("position", pos); 
 %! colormap (contrast (img, 10));
 %! imagesc (img);
--- a/scripts/image/cool.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/cool.m	Sun Dec 23 13:00:02 2012 -0500
@@ -36,7 +36,7 @@
     n = rows (colormap);
   elseif (nargin == 1)
     if (! isscalar (n))
-      error ("cool: argument must be a scalar");
+      error ("cool: N must be a scalar");
     endif
   else
     print_usage ();
--- a/scripts/image/copper.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/copper.m	Sun Dec 23 13:00:02 2012 -0500
@@ -37,7 +37,7 @@
     n = rows (colormap);
   elseif (nargin == 1)
     if (! isscalar (n))
-      error ("copper: argument must be a scalar");
+      error ("copper: N must be a scalar");
     endif
   else
     print_usage ();
--- a/scripts/image/flag.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/flag.m	Sun Dec 23 13:00:02 2012 -0500
@@ -37,7 +37,7 @@
     n = rows (colormap);
   elseif (nargin == 1)
     if (! isscalar (n))
-      error ("flag: argument must be a scalar");
+      error ("flag: N must be a scalar");
     endif
   else
     print_usage ();
--- a/scripts/image/gmap40.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/gmap40.m	Sun Dec 23 13:00:02 2012 -0500
@@ -37,7 +37,7 @@
     n = 6;
   elseif (nargin == 1)
     if (! isscalar (n))
-      error ("gmap40: argument must be a scalar");
+      error ("gmap40: N must be a scalar");
     endif
   else
     print_usage ();
--- a/scripts/image/gray.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/gray.m	Sun Dec 23 13:00:02 2012 -0500
@@ -39,7 +39,7 @@
     n = rows (colormap);
   elseif (nargin == 1)
     if (! isscalar (n))
-      error ("gray: argument must be a scalar");
+      error ("gray: N must be a scalar");
     endif
   else
     print_usage ();
--- a/scripts/image/gray2ind.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/gray2ind.m	Sun Dec 23 13:00:02 2012 -0500
@@ -17,48 +17,93 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn  {Function File} {[@var{img} =} gray2ind (@var{I})
-## @deftypefnx {Function File} {[@var{img} =} gray2ind (@var{I}, @var{n})
-## @deftypefnx {Function File} {[@var{img}, @var{map} =} gray2ind (@dots{})
-## Convert a gray scale intensity image to an Octave indexed image.
+## @deftypefn  {Function File} {@var{img} =} gray2ind (@var{I})
+## @deftypefnx {Function File} {@var{img} =} gray2ind (@var{I}, @var{n})
+## @deftypefnx {Function File} {@var{img} =} gray2ind (@var{BW})
+## @deftypefnx {Function File} {@var{img} =} gray2ind (@var{BW}, @var{n})
+## @deftypefnx {Function File} {[@var{img}, @var{map}] =} gray2ind (@dots{})
+## Convert a grayscale or binary intensity image to an indexed image.
+## 
 ## The indexed image will consist of @var{n} different intensity values.
-## If not given @var{n} defaults to 64.
-## @seealso{ind2gray, rgb2ind} 
+## If not given @var{n} defaults to 64 for grayscale images or 2 for
+## binary black and white images.
+##
+## The output @var{img} is of class uint8 if @var{n} is less than or
+## equal to 256; Otherwise the return class is uint16.
+## @seealso{ind2gray, rgb2ind}
 ## @end deftypefn
 
 ## Author: Tony Richardson <arichard@stark.cc.oh.us>
 ## Created: July 1994
 ## Adapted-By: jwe
 
-function [X, map] = gray2ind (I, n = 64)
-  ## Check input
+function [I, map] = gray2ind (I, n = 64)
+
   if (nargin < 1 || nargin > 2)
     print_usage ();
-  endif
-  C = class (I);
-  if (! ismatrix (I) || ndims (I) != 2)
-    error ("gray2ind: first input argument must be a gray scale image");
+  elseif (! isreal (I) || issparse (I))
+    error ("gray2ind: I must be a grayscale or binary image");
+  elseif (! isscalar (n) || n < 1 || n > 65536)
+    error ("gray2ind: N must be a positive integer in the range [1, 65536]");
+  elseif (! ismatrix (I) || ndims (I) != 2)
+    error ("gray2ind: I must be a grayscale or binary image");
   endif
-  if (! isscalar (n) || n < 0)
-    error ("gray2ind: second input argument must be a positive integer");
+
+  ## default n is different if image is logical
+  if (nargin == 1 && islogical (I))
+    n = 2;
   endif
-  ints = {"uint8", "uint16", "int8", "int16"};
-  floats = {"double", "single"};
-  if (! ismember (C, {ints{:}, floats{:}}))
-    error ("gray2ind: invalid data type '%s'", C);
-  endif
-  if (ismember (C, floats) && (min (I(:)) < 0 || max (I(:)) > 1))
+
+  cls = class (I);
+  if (! any (strcmp (cls, {"logical", "uint8", "uint16", "int16", "single", "double"})))
+    error ("gray2ind: invalid data type '%s'", cls);
+  elseif (isfloat (I) && (min (I(:) < 0) || max (I(:) > 1)))
     error ("gray2ind: floating point images may only contain values between 0 and 1");
   endif
 
-  ## Convert data
   map = gray (n);
-  ## If @var{I} is an integer matrix convert it to a double matrix with values in [0, 1]
-  if (ismember (C, ints))
-    low = double (intmin (C));
-    high = double (intmax (C));
-    I = (double (I) - low) / (high - low);
+
+  ## Set up scale factor
+  if (isinteger (I))
+    low   = double (intmin (cls));
+    scale = double (intmax (cls)) - low;
+    I = double (I) - low;
+  else
+    scale = 1;
   endif
-  X = round (I*(n-1)) + 1;
+  I *= (n-1)/scale;
+
+  ## Note: no separate call to round () necessary because
+  ##       type conversion does that automatically.
+  if (n < 256)
+    I = uint8 (I);
+  else
+    I = uint16 (I);
+  endif
 
 endfunction
+
+
+%!assert (gray2ind ([0 0.25 0.5 1]), uint8 ([0 16 32 63]))
+%!assert (gray2ind ([0 0.25 0.5 1], 400), uint16 ([0 100 200 399]))
+%!assert (gray2ind (logical ([1 0 0 1])), uint8 ([1 0 0 1]))
+%!assert (gray2ind (uint8 ([0 64 128 192 255])), uint8 ([0 16 32 47 63]))
+
+%!test
+%! i2g = ind2gray (1:100, gray (100));
+%! g2i = gray2ind (i2g, 100);
+%! assert (g2i, uint8 (0:99));
+
+%% Test input validation
+%!error gray2ind ()
+%!error gray2ind (1,2,3)
+%!error <I must be a grayscale or binary image> gray2ind ({1})
+%!error <I must be a grayscale or binary image> gray2ind ([1+i])
+%!error <I must be a grayscale or binary image> gray2ind (sparse ([1]))
+%!error <N must be a positive integer> gray2ind (1, ones (2,2))
+%!error <N must be a positive integer> gray2ind (1, 0)
+%!error <N must be a positive integer> gray2ind (1, 65537)
+%!error <invalid data type> gray2ind (uint32 (1))
+%!error <values between 0 and 1> gray2ind (-1)
+%!error <values between 0 and 1> gray2ind (2)
+
--- a/scripts/image/hot.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/hot.m	Sun Dec 23 13:00:02 2012 -0500
@@ -37,7 +37,7 @@
     n = rows (colormap);
   elseif (nargin == 1)
     if (! isscalar (n))
-      error ("hot: argument must be a scalar");
+      error ("hot: N must be a scalar");
     endif
   else
     print_usage ();
--- a/scripts/image/hsv.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/hsv.m	Sun Dec 23 13:00:02 2012 -0500
@@ -41,7 +41,7 @@
     n = rows (colormap);
   elseif (nargin == 1)
     if (! isscalar (n))
-      error ("hsv: argument must be a scalar");
+      error ("hsv: N must be a scalar");
     endif
   else
     print_usage ();
--- a/scripts/image/hsv2rgb.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/hsv2rgb.m	Sun Dec 23 13:00:02 2012 -0500
@@ -21,6 +21,13 @@
 ## @deftypefnx {Function File} {@var{rgb_img} =} hsv2rgb (@var{hsv_img})
 ## Transform a colormap or image from hue-saturation-value (HSV) space to
 ## red-green-blue (RGB) space.
+##
+## A color in HSV space is represented by hue, saturation and value
+## (brightness) levels.  Value gives the amount of light in the color.  Hue
+## describes the dominant wavelength.  Saturation is the amount of hue mixed
+## into the color.
+##
+## A color in the RGB space consists of red, green, and blue intensities.
 ## @seealso{rgb2hsv, ind2rgb, ntsc2rgb}
 ## @end deftypefn
 
@@ -38,52 +45,85 @@
     print_usage ();
   endif
 
+  cls = class (hsv_map);
+  if (! any (strcmp (cls, {"uint8", "uint16", "single", "double"})))
+    error ("hsv2rgb: invalid data type '%s'", cls);
+  elseif (isfloat (hsv_map) && (any (hsv_map(:) < 0) || any (hsv_map(:) > 1)))
+    error ("hsv2rgb: floating point images may only contain values between 0 and 1");
+  endif
+
   ## If we have an image convert it into a color map.
-  if (ismatrix (hsv_map) && ndims (hsv_map) == 3)
+  if (isreal (hsv_map) && ndims (hsv_map) == 3)
     is_image = true;
-    Sz = size (hsv_map);
+    sz = size (hsv_map);
     hsv_map = [hsv_map(:,:,1)(:), hsv_map(:,:,2)(:), hsv_map(:,:,3)(:)];
     ## Convert to a double image.
     if (isinteger (hsv_map))
-      C = class (hsv_map);
-      low = double (intmin (C));
-      high = double (intmax (C));
+      low = double (intmin (cls));
+      high = double (intmax (cls));
       hsv_map = (double (hsv_map) - low) / (high - low);
     endif
   else
     is_image = false;
   endif
 
-  if (! ismatrix (hsv_map) || columns (hsv_map) != 3)
-    error ("hsv2rgb: argument must be a matrix of size nx3");
+  if (! isreal (hsv_map) || columns (hsv_map) != 3 || issparse (hsv_map))
+    error ("hsv2rgb: input must be a matrix of size Nx3 or MxNx3");
   endif
 
-  ## set values <0 to 0 and >1 to 1
-  hsv_map = (hsv_map >= 0 & hsv_map <= 1) .* hsv_map ...
-      + (hsv_map < 0) .* 0 + (hsv_map > 1);
-
-  ## fill rgb map with v*(1-s)
-  rgb_map = kron ([1, 1, 1], hsv_map(:,3) .* (1 - hsv_map(:,2)));
+  ## FIXME: Currently input is validated and an error results if values
+  ##        are outside range [0, 1].  We could also simply allow those values
+  ##        and re-instate this code to produce saturating semantics.
+  ## Trim map to range [0, 1]
+  #hsv_map(hsv_map < 0) = 0;
+  #hsv_map(hsv_map > 1) = 1;
 
-  ## red(hue-2/3)=green(hue)=blue(hue-1/3)
-  ## apply modulo 1 for red and blue
-  t = hsv_map(:,1);
-  tp = t';
-  hue = [(tp - 2/3 - floor (t - 2/3)');
-         tp;
-         (tp - 1/3 - floor (t - 1/3)')]';
+  h = hsv_map(:,1);
+  s = hsv_map(:,2);
+  v = hsv_map(:,3);
+  ## Prefill rgb map with v*(1-s)
+  rgb_map = repmat (v .* (1 - s), 1, 3);
+
+  ## red = hue-2/3 : green = hue : blue = hue-1/3
+  ## Apply modulo 1 for red and blue to keep within range [0, 1]
+  hue = [mod(h - 2/3, 1), h , mod(h - 1/3, 1)];
 
   ## factor s*v -> f
-  f = kron ([1, 1, 1], hsv_map(:,2)) .* kron ([1, 1, 1], hsv_map(:,3));
+  f = repmat (s .* v, 1, 3);
 
-  ## add s*v* hue-function to rgb map
-  rgb_map = rgb_map +  f .* (6 * (hue < 1/6) .* hue
-                    + (hue >= 1/6 & hue < 1/2)
-                    + (hue >= 1/2 & hue < 2/3) .* (4 - 6 * hue));
+  ## add s*v*hue-function to rgb map
+  rgb_map += f .* (6 * (hue < 1/6) .* hue
+             + (hue >= 1/6 & hue < 1/2)
+             + (hue >= 1/2 & hue < 2/3) .* (4 - 6 * hue));
 
+  ## FIXME: hsv2rgb does not preserve class of image.
+  ##        Should it also convert back to uint8, uint16 for integer images?
   ## If input was an image, convert it back into one.
   if (is_image)
-    rgb_map = reshape (rgb_map, Sz);
+    rgb_map = reshape (rgb_map, sz);
   endif
 
 endfunction
+
+
+%% Test pure colors
+%!assert (hsv2rgb ([0 1 1]), [1 0 0])
+%!assert (hsv2rgb ([1 1 1]), [1 0 0])
+%!assert (hsv2rgb ([1/3 1 1]), [0 1 0])
+%!assert (hsv2rgb ([2/3 1 1]), [0 0 1])
+
+%!test
+%! hsv_map = rand (64, 3);
+%! assert (rgb2hsv (hsv2rgb (hsv_map)), hsv_map, 1e-6);
+
+%!test
+%! hsv_img = rand (64, 64, 3);
+%! assert (rgb2hsv (hsv2rgb (hsv_img)), hsv_img, 1e-6);
+
+%% Test input validation
+%!error hsv2rgb ()
+%!error hsv2rgb (1,2)
+%!error <invalid data type> hsv2rgb ({1})
+%!error <must be a matrix of size Nx3> hsv2rgb (ones (2,2))
+%!error <must be a matrix of size Nx3> hsv2rgb (sparse (ones(1,3)))
+
--- a/scripts/image/image.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/image.m	Sun Dec 23 13:00:02 2012 -0500
@@ -19,13 +19,19 @@
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {} image (@var{img})
 ## @deftypefnx {Function File} {} image (@var{x}, @var{y}, @var{img})
+## @deftypefnx {Function File} {} image (@dots{}, "@var{property}", @var{value}, @dots{})
 ## @deftypefnx {Function File} {@var{h} =} image (@dots{})
-## Display a matrix as a color image.
+## Display a matrix as an indexed color image.
 ##
 ## The elements of @var{img} are indices into the current colormap.
-## The axis values corresponding to the matrix elements are specified in
-## @var{x} and @var{y}.  If you are using gnuplot 4.1 or earlier, these
-## variables are ignored.
+## @var{x} and @var{y} are optional 2-element vectors, @w{@code{[min, max]}},
+## which specify the range for the axis labels.  If a range is specified as
+## @w{@code{[max, min]}} then the image will be reversed along that axis.  For
+## convenience, @var{x} and @var{y} may be specified as N-element vectors
+## matching the length of the data in @var{img}.  However, only the first and
+## last elements will be used to determine the axis limits.
+## @strong{Warning:} @var{x} and @var{y} are ignored when using gnuplot 4.0
+## or earlier.
 ##
 ## The optional return value @var{h} is a graphics handle to the image.
 ##
@@ -36,7 +42,7 @@
 ## @code{ydir} property to "reverse".  This has implications whenever
 ## an image and an ordinary plot need to be overlaid.  The recommended
 ## solution is to display the image and then plot the reversed ydata
-## using, for example, @code{flipud (ydata,1)}.
+## using, for example, @code{flipud (ydata)}.
 ##
 ## @seealso{imshow, imagesc, colormap}
 ## @end deftypefn
@@ -45,49 +51,38 @@
 ## Created: July 1994
 ## Adapted-By: jwe
 
-function retval = image (varargin)
+function h = image (varargin)
 
   [ax, varargin, nargin] = __plt_get_axis_arg__ ("image", varargin{:});
 
-  firstnonnumeric = Inf;
-  for i = 1 : nargin
-    if (! isnumeric (varargin{i}))
-      firstnonnumeric = i;
-      break;
-    endif
-  endfor
-
-  if (nargin == 0 || firstnonnumeric == 1)
+  chararg = find (cellfun ("isclass", varargin, "char"), 1, "first");
+  
+  if (nargin == 0 || chararg == 1)
     img = imread ("default.img");
     x = y = [];
-  elseif (nargin == 1 || firstnonnumeric == 2)
+  elseif (nargin == 1 || chararg == 2)
     img = varargin{1};
     x = y = [];
-  elseif (nargin == 2 || firstnonnumeric == 3)
+  elseif (nargin == 2 || chararg == 3)
     print_usage ();
   else
     x = varargin{1};
     y = varargin{2};
     img = varargin{3};
-    firstnonnumeric = 4;
-  endif
-
-  if (iscomplex (img))
-    warning ("image: only showing real part of complex image");
-    img = real (img);
+    chararg = 4;
   endif
 
   oldax = gca ();
   unwind_protect
     axes (ax);
-    h = __img__ (x, y, img, varargin {firstnonnumeric:end});
+    htmp = __img__ (x, y, img, varargin{chararg:end});
     set (ax, "layer", "top");
   unwind_protect_cleanup
     axes (oldax);
   end_unwind_protect
 
   if (nargout > 0)
-    retval = h;
+    h = htmp;
   endif
 
 endfunction
@@ -110,6 +105,13 @@
     error ("__img__: matrix is empty");
   endif
 
+  ## FIXME: Hack for integer formats which use zero-based indexing
+  ##        Hack favors correctness of display over size of image in memory.
+  ##        True fix will be done in C++ code. 
+  if (ndims (img) == 2 && (isinteger (img) || islogical (img)))
+    img = single (img) + 1;
+  endif
+
   if (isempty (x))
     x = [1, columns(img)];
   endif
@@ -118,32 +120,36 @@
     y = [1, rows(img)];
   endif
 
-  xdata = [x(1), x(end)];
-  ydata = [y(1), y(end)];
+  xdata = x([1, end]);
+  ydata = y([1, end]);
 
-  dx = diff (x);
-  dy = diff (y);
-  dx = std (dx) / mean (abs (dx));
-  dy = std (dy) / mean (abs (dy));
-  tol = 100*eps;
-  if (any (dx > tol) || any (dy > tol))
-    warning ("Image does not map to non-linearly spaced coordinates");
+  if (numel (x) > 2 && numel (y) > 2)
+    ## Test data for non-linear spacing which is unsupported
+    ## FIXME: Need a better check on linearity
+    tol = 100*eps;
+    dx = diff (x);
+    dy = diff (y);
+    dx = std (dx) / mean (abs (dx));
+    dy = std (dy) / mean (abs (dy));
+    if (any (dx > tol) || any (dy > tol))
+      warning ("image: non-linear X, Y data is ignored.  IMG will be shown with linear mapping");
+    endif
   endif
 
   ca = gca ();
 
-  tmp = __go_image__ (ca, "cdata", img, "xdata", xdata, "ydata", ydata,
-                    "cdatamapping", "direct", varargin {:});
+  htmp = __go_image__ (ca, "cdata", img, "xdata", xdata, "ydata", ydata,
+                       "cdatamapping", "direct", varargin {:});
 
-  px = __image_pixel_size__ (tmp);
+  px = __image_pixel_size__ (htmp);
 
   if (xdata(2) < xdata(1))
-    xdata = xdata(2:-1:1);
+    xdata = fliplr (xdata);
   elseif (xdata(2) == xdata(1))
     xdata = xdata(1) + [0, columns(img)-1];
   endif
   if (ydata(2) < ydata(1))
-    ydata = ydata(2:-1:1);
+    ydata = fliplr (ydata);
   elseif (ydata(2) == ydata(1))
     ydata = ydata(1) + [0, rows(img)-1];
   endif
@@ -160,9 +166,9 @@
 
   if (ndims (img) == 3)
     if (isinteger (img))
-      c = class (img);
-      mn = intmin (c);
-      mx = intmax (c);
+      cls = class (img);
+      mn = intmin (cls);
+      mx = intmax (cls);
       set (ca, "clim", double ([mn, mx]));
     endif
   endif
@@ -175,7 +181,7 @@
   endif
 
   if (nargout > 0)
-    h = tmp;
+    h = htmp;
   endif
 
 endfunction
@@ -183,66 +189,21 @@
 
 %!demo
 %! clf;
-%! colormap ("default");
+%! colormap (jet (21));
 %! img = 1 ./ hilb (11);
-%! x = -5:5;
-%! y = x;
+%! x = y = -5:5;
 %! subplot (2,2,1);
-%!  h = image (abs(x), abs(y), img);
-%!  set (h, "cdatamapping", "scaled");
-%!  ylabel ("limits = [4.5, 15.5]");
-%!  title ("image (abs(x), abs(y), img)");
+%!  h = image (x, y, img);
+%!  ylabel ("limits = [-5.5, 5.5]");
+%!  title ("image (x, y, img)");
 %! subplot (2,2,2);
 %!  h = image (-x, y, img);
-%!  set (h, "cdatamapping", "scaled");
 %!  title ("image (-x, y, img)");
 %! subplot (2,2,3);
 %!  h = image (x, -y, img);
-%!  set (h, "cdatamapping", "scaled");
 %!  title ("image (x, -y, img)");
 %!  ylabel ("limits = [-5.5, 5.5]");
 %! subplot (2,2,4);
 %!  h = image (-x, -y, img);
-%!  set (h, "cdatamapping", "scaled");
 %!  title ("image (-x, -y, img)");
 
-%!demo
-%! clf;
-%! colormap ("default");
-%! g = 0.1:0.1:10;
-%! h = g'*g;
-%! imagesc (g, g, sin (h));
-%! hold on;
-%! imagesc (g, g+12, cos (h/2));
-%! axis ([0 10 0 22]);
-%! hold off;
-%! title ("two consecutive images");
-
-%!demo
-%! clf;
-%! colormap ("default");
-%! g = 0.1:0.1:10;
-%! h = g'*g;
-%! imagesc (g, g, sin (h));
-%! hold all;
-%! plot (g, 11.0 * ones (size (g)));
-%! imagesc (g, g+12, cos (h/2));
-%! axis ([0 10 0 22]);
-%! hold off;
-%! title ("image, line, image");
-
-%!demo
-%! clf;
-%! colormap ("default");
-%! g = 0.1:0.1:10;
-%! h = g'*g;
-%! plot (g, 10.5 * ones (size (g)));
-%! hold all;
-%! imagesc (g, g, sin (h));
-%! plot (g, 11.0 * ones (size (g)));
-%! imagesc (g, g+12, cos (h/2));
-%! plot (g, 11.5 * ones (size (g)));
-%! axis ([0 10 0 22]);
-%! hold off;
-%! title ("line, image, line, image, line");
-
--- a/scripts/image/imagesc.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/imagesc.m	Sun Dec 23 13:00:02 2012 -0500
@@ -17,20 +17,20 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn  {Function File} {} imagesc (@var{A})
-## @deftypefnx {Function File} {} imagesc (@var{x}, @var{y}, @var{A})
-## @deftypefnx {Function File} {} imagesc (@dots{}, @var{limits})
+## @deftypefn  {Function File} {} imagesc (@var{img})
+## @deftypefnx {Function File} {} imagesc (@var{x}, @var{y}, @var{img})
+## @deftypefnx {Function File} {} imagesc (@dots{}, @var{climits})
 ## @deftypefnx {Function File} {} imagesc (@var{h}, @dots{})
 ## @deftypefnx {Function File} {@var{h} =} imagesc (@dots{})
-## Display a scaled version of the matrix @var{A} as a color image.  The
+## Display a scaled version of the matrix @var{img} as a color image.  The
 ## colormap is scaled so that the entries of the matrix occupy the entire
-## colormap.  If @var{limits} = [@var{lo}, @var{hi}] are given, then that
+## colormap.  If @code{@var{climits} = [@var{lo}, @var{hi}]} is given, then that
 ## range is set to the "clim" of the current axes.
 ##
 ## The axis values corresponding to the matrix elements are specified in
 ## @var{x} and @var{y}, either as pairs giving the minimum and maximum
 ## values for the respective axes, or as values for each row and column
-## of the matrix @var{A}.
+## of the matrix @var{img}.
 ##
 ## The optional return value @var{h} is a graphics handle to the image.
 ## @seealso{image, imshow, caxis}
@@ -40,82 +40,115 @@
 ## Created: July 1994
 ## Adapted-By: jwe
 
-function retval = imagesc (varargin)
+function h = imagesc (varargin)
 
-  if (nargin < 1)
+  if (nargin < 1 || nargin > 4)
     print_usage ();
   elseif (isscalar (varargin{1}) && ishandle (varargin{1}))
-    h = varargin{1};
-    if (! strcmp (get (h, "type"), "axes"))
+    harg = varargin{1};
+    if (! strcmp (get (harg, "type"), "axes"))
       error ("imagesc: expecting first argument to be an axes object");
     endif
     oldh = gca ();
     unwind_protect
       axes (h);
-      tmp = __imagesc__ (h, varargin{2:end});
+      htmp = __imagesc__ (harg, varargin{2:end});
     unwind_protect_cleanup
       axes (oldh);
     end_unwind_protect
   else
-    tmp = __imagesc__ (gca (), varargin{:});
+    htmp = __imagesc__ (gca (), varargin{:});
   endif
 
   if (nargout > 0)
-    retval = tmp;
+    h = htmp;
+  endif
+
+endfunction
+
+function h = __imagesc__ (ax, x, y, img, climits)
+
+  if (nargin == 2)
+    img = x;
+    x = y = climits = [];
+  elseif (nargin == 3)
+    img = x;
+    climits = y;
+    x = y = [];
+  elseif (nargin == 4 && ! isscalar (x) && ! isscalar (y) && ! isscalar (img))
+    climits = [];
+  endif
+
+  h = image (ax, x, y, img);
+  set (h, "cdatamapping", "scaled");
+
+  ## use given climits or guess them from the matrix
+  if (numel (climits) == 2 && climits(1) <= climits(2))
+    set (ax, "clim", climits);
+  elseif (! isempty (climits))
+    error ("imagesc: CLIMITS must be in form [lo, hi]");
   endif
 
 endfunction
 
-function ret = __imagesc__ (ax, x, y, A, limits, DEPRECATEDZOOM)
+
+%!demo
+%! clf;
+%! colormap ("default");
+%! img = 1 ./ hilb (11);
+%! x = y = -5:5;
+%! subplot (2,2,1);
+%!  h = imagesc (x, y, img);
+%!  ylabel ("limits = [-5.5, 5.5]");
+%!  title ("imagesc (x, y, img)");
+%! subplot (2,2,2);
+%!  h = imagesc (-x, y, img);
+%!  title ("imagesc (-x, y, img)");
+%! subplot (2,2,3);
+%!  h = imagesc (x, -y, img);
+%!  title ("imagesc (x, -y, img)");
+%!  ylabel ("limits = [-5.5, 5.5]");
+%! subplot (2,2,4);
+%!  h = imagesc (-x, -y, img);
+%!  title ("imagesc (-x, -y, img)");
 
-  ## Deprecated zoom.  Remove this hunk of code if old zoom argument
-  ## is outmoded.
-  if ((nargin == 3 && isscalar (y))
-      || (nargin == 4 && (isscalar (y) || isscalar (A)))
-      || (nargin == 5 && isscalar (limits))
-      || nargin == 6)
-    warning ("image: zoom argument ignored -- use GUI features");
-  endif
-  if (nargin == 6)
-    if (isscalar (limits))
-      limits = DEPRECATEDZOOM;
-    endif
-    nargin = 5;
-  endif
-  if (nargin == 5 && isscalar (limits))
-    nargin = 4;
-  endif
-  if (nargin == 4 && (isscalar (y) || isscalar (A)))
-    if (isscalar (y))
-      y = A;
-    endif
-    nargin = 3;
-  endif
-  if (nargin == 3 && isscalar (y))
-    nargin = 2;
-  endif
+%!demo
+%! clf;
+%! colormap ("default");
+%! g = 0.1:0.1:10;
+%! h = g'*g;
+%! imagesc (g, g, sin (h));
+%! hold on;
+%! imagesc (g, g+12, cos (h/2));
+%! axis ([0 10 0 22]);
+%! hold off;
+%! title ("two consecutive images");
 
-  if (nargin < 2 || nargin > 5)
-    print_usage ();
-  elseif (nargin == 2)
-    A = x;
-    x = y = limits = [];
-  elseif (nargin == 3)
-    A = x;
-    limits = y;
-    x = y = [];
-  elseif (nargin == 4 && ! isscalar (x) && ! isscalar (y) && ! isscalar (A))
-    limits = [];
-  endif
+%!demo
+%! clf;
+%! colormap ("default");
+%! g = 0.1:0.1:10;
+%! h = g'*g;
+%! imagesc (g, g, sin (h));
+%! hold all;
+%! plot (g, 11.0 * ones (size (g)));
+%! imagesc (g, g+12, cos (h/2));
+%! axis ([0 10 0 22]);
+%! hold off;
+%! title ("image, line, image");
 
-  ret = image (ax, x, y, A);
-  set (ret, "cdatamapping", "scaled");
+%!demo
+%! clf;
+%! colormap ("default");
+%! g = 0.1:0.1:10;
+%! h = g'*g;
+%! plot (g, 10.5 * ones (size (g)));
+%! hold all;
+%! imagesc (g, g, sin (h));
+%! plot (g, 11.0 * ones (size (g)));
+%! imagesc (g, g+12, cos (h/2));
+%! plot (g, 11.5 * ones (size (g)));
+%! axis ([0 10 0 22]);
+%! hold off;
+%! title ("line, image, line, image, line");
 
-  ## use given limits or guess them from the matrix
-  if (length (limits) == 2 && limits(2) >= limits(1))
-    set (ax, "clim", limits);
-  elseif (! isempty (limits))
-    error ("imagesc: expected data LIMITS to be [lo, hi]");
-  endif
-
-endfunction
--- a/scripts/image/imfinfo.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/imfinfo.m	Sun Dec 23 13:00:02 2012 -0500
@@ -71,7 +71,7 @@
 ## for.
 ##
 ## @item ByteOrder
-## Endian option for formats that support it.  Is either @code{"little-endian"},
+## Endian option for formats that support it.  Value is @code{"little-endian"},
 ## @code{"big-endian"}, or @code{"undefined"}.
 ##
 ## @item Gamma
@@ -83,8 +83,7 @@
 ##
 ## @item ModulusDepth
 ## Image modulus depth (minimum number of bits required to support
-## red/green/blue
-## components without loss of accuracy).
+## red/green/blue components without loss of accuracy).
 ##
 ## @item Quality
 ## JPEG/MIFF/PNG compression level.
@@ -93,19 +92,18 @@
 ## Preferred number of colors in the image.
 ##
 ## @item ResolutionUnits
-## Units of image resolution.  Is either @code{"pixels per inch"},
+## Units of image resolution.  Value is @code{"pixels per inch"},
 ## @code{"pixels per centimeter"}, or @code{"undefined"}.
 ##
 ## @item ColorType
-## Image type.  Is either @code{"grayscale"}, @code{"indexed"},
-## @code{"truecolor"},
-## or @code{"undefined"}.
+## Image type.  Value is @code{"grayscale"}, @code{"indexed"},
+## @code{"truecolor"}, or @code{"undefined"}.
 ##
 ## @item View
 ## FlashPix viewing parameters.
 ## @end table
 ##
-## @seealso{imread, imwrite}
+## @seealso{imread, imwrite, imshow}
 ## @end deftypefn
 
 function info = imfinfo (filename)
@@ -114,7 +112,7 @@
     print_usage ();
   endif
 
-  if (!ischar (filename))
+  if (! ischar (filename))
     error ("imfinfo: FILENAME must be a string");
   endif
 
--- a/scripts/image/imwrite.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/imwrite.m	Sun Dec 23 13:00:02 2012 -0500
@@ -135,7 +135,7 @@
       if ((nd == 2 || nd == 3) && strcmp (img_class, "double"))
         img = uint8 (img * 255);
       endif
-      ## FIXME -- should we handle color images w/ alpha channel here?
+      ## FIXME: should we handle color images with alpha channel here?
       if (nd == 3 && size (img, 3) < 3)
         error ("imwrite: invalid dimensions for truecolor image");
       endif
@@ -165,8 +165,8 @@
       error ("imwrite: invalid indexed image colormap");
     endif
 
-    ## FIXME -- we should really be writing indexed images here but
-    ## __magick_write__ needs to be fixed to handle them.
+    ## FIXME: we should really be writing indexed images here but
+    ##        __magick_write__ needs to be fixed to handle them.
 
     [r, g, b] = ind2rgb (img, map);
     tmp = uint8 (cat (3, r, g, b) * 255);
--- a/scripts/image/ind2gray.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/ind2gray.m	Sun Dec 23 13:00:02 2012 -0500
@@ -17,11 +17,22 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn  {Function File} {} ind2gray (@var{x})
-## @deftypefnx {Function File} {} ind2gray (@var{x}, @var{map})
-## Convert a color indexed image to a gray scale intensity image.
-## If @var{map} is omitted, the current colormap is used to determine the
-## intensities.
+## @deftypefn {Function File} {@var{I} =} ind2gray (@var{x}, @var{map})
+## Convert a color indexed image to a grayscale intensity image.
+##
+## The image @var{x} must be an indexed image which will be converted using the
+## colormap @var{cmap}.  If @var{cmap} does not contain enough colors for the
+## image, pixels in @var{x} outside the range are mapped to the last color in
+## the map before conversion to grayscale.
+##
+## The output @var{I} is of the same class as the input @var{x} and may be
+## one of @code{uint8}, @code{uint16}, @code{single}, or @code{double}.
+##
+## Implementation Note: There are several ways of converting colors to
+## grayscale intensities.  This functions uses the luminance value obtained
+## from @code{rgb2ntsc} which is @code{I = 0.299*R + 0.587*G + 0.114*B}.  
+## Other possibilities include the value component from @code{rgb2hsv} or
+## using a single color channel from @code{ind2rgb}.
 ## @seealso{gray2ind, ind2rgb}
 ## @end deftypefn
 
@@ -29,22 +40,51 @@
 ## Created: July 1994
 ## Adapted-By: jwe
 
-function y = ind2gray (x, map)
+function I = ind2gray (x, map)
+
+  if (nargin != 2)
+    print_usage ();
+  endif
+  [x, map] = ind2x ("ind2gray", x, map);
+
+  ## Convert colormap to luminance intensity values 
+  map *= [0.29894; 0.58704; 0.11402];
 
-  if (nargin < 1 || nargin > 2)
-    print_usage ();
-  elseif (nargin == 1)
-    map = colormap ();
+  ## Convert colormap to same class as that of input so that reshape
+  ## will produce output of the same type as the input.
+  cls = class (x);
+  if (isinteger (x))
+    ## if we later add support for int16 images, this will not work. Look into
+    ## im2int16 from image package for such case
+    map *= intmax (cls);
+  elseif (strcmp (cls, "single"))
+    map = single (map);
   endif
 
-  [rows, cols] = size (x);
-
-  ## Convert colormap to intensity values (the first column of the
-  ## result of the call to rgb2ntsc) and then replace indices in
-  ## the input matrix with indexed values in the output matrix (indexed
-  ## values are the result of indexing the intensity values by the
-  ## elements of x(:)).
-
-  y = reshape (((rgb2ntsc (map))(:,1))(x(:)), rows, cols);
+  ## Replace indices in the input matrix with the indexed luminance value.
+  I = reshape (map(x(:)), size (x));
 
 endfunction
+
+
+%!shared i2g
+%! i2g = ind2gray (1:100, gray (100));
+%!assert (i2g, 0:1/99:1, eps);
+%!assert (gray2ind (i2g, 100), uint8 (0:99));
+
+%% Test input validation
+%!error ind2gray ()
+%!error ind2gray (1)
+%!error ind2gray (1,2,3)
+%!error <X must be an indexed image> ind2gray ({1}, jet (64))
+%!error <X must be an indexed image> ind2gray (1+i, jet (64))
+%!error <X must be an indexed image> ind2gray (sparse (1), jet (64))
+%!error <X must be an indexed image> ind2gray (0, jet (64))
+%!error <X must be an indexed image> ind2gray (1.1, jet (64))
+%!error <MAP must be a valid colormap> ind2gray (1, {1})
+%!error <MAP must be a valid colormap> ind2gray (1, 1+i)
+%!error <MAP must be a valid colormap> ind2gray (1, ones (2,2,2))
+%!error <MAP must be a valid colormap> ind2gray (1, ones (2,4))
+%!error <MAP must be a valid colormap> ind2gray (1, [-1])
+%!error <MAP must be a valid colormap> ind2gray (1, [2])
+
--- a/scripts/image/ind2rgb.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/ind2rgb.m	Sun Dec 23 13:00:02 2012 -0500
@@ -17,13 +17,20 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn  {Function File} {@var{rgb} =} ind2rgb (@var{x})
-## @deftypefnx {Function File} {@var{rgb} =} ind2rgb (@var{x}, @var{map})
-## @deftypefnx {Function File} {[@var{R}, @var{G}, @var{B}] =} ind2rgb (@dots{})
+## @deftypefn  {Function File} {@var{rgb} =} ind2rgb (@var{x}, @var{map})
+## @deftypefnx {Function File} {[@var{R}, @var{G}, @var{B}] =} ind2rgb (@var{x}, @var{map})
 ## Convert an indexed image to red, green, and blue color components.
-## If the colormap doesn't contain enough colors, pad it with the
-## last color in the map.
-## If @var{map} is omitted, the current colormap is used for the conversion.
+##
+## The image @var{x} must be an indexed image which will be converted using the
+## colormap @var{map}.  If @var{map} does not contain enough colors for the
+## image, pixels in @var{x} outside the range are mapped to the last color in
+## the map.
+##
+## The output may be a single RGB image (MxNx3 matrix where M and N are the
+## original image @var{x} dimensions, one for each of the red, green and blue
+## channels).  Alternatively, the individual red, green, and blue color matrices
+## of size MxN may be returned.
+##
 ## @seealso{rgb2ind, ind2gray, hsv2rgb, ntsc2rgb}
 ## @end deftypefn
 
@@ -33,41 +40,60 @@
 
 function [R, G, B] = ind2rgb (x, map)
 
-  ## Do we have the right number of inputs?
-  if (nargin < 1 || nargin > 2)
+  if (nargin != 2)
     print_usage ();
-  elseif (nargin == 1)
-    map = colormap ();
-  endif
-
-  ## Check if X is an indexed image.
-  if (ndims (x) != 2 || any (x(:) != fix (x(:))) || min (x(:)) < 1)
-    error ("ind2rgb: X must be an indexed image");
   endif
-
-  ## Check the color map.
-  if (! iscolormap (map))
-    error ("ind2rgb: MAP must be a valid colormap");
-  endif
-
-  ## Do we have enough colors in the color map?
-  maxidx = max (x(:));
-  rm = rows (map);
-  if (rm < maxidx)
-    ## Pad with the last color in the map.
-    pad = repmat (map(end,:), maxidx-rm, 1);
-    map(end+1:maxidx, :) = pad;
-  endif
+  [x, map] = ind2x ("ind2rgb", x, map);
 
   ## Compute result
-  [hi, wi] = size (x);
-  R = reshape (map (x(:), 1), hi, wi);
-  G = reshape (map (x(:), 2), hi, wi);
-  B = reshape (map (x(:), 3), hi, wi);
+  [row, col] = size (x);
+  R = reshape (map(x(:), 1), row, col);
+  G = reshape (map(x(:), 2), row, col);
+  B = reshape (map(x(:), 3), row, col);
 
   ## Use 3D array if only one output is requested.
   if (nargout <= 1)
+    R(:,:,2) = G;
     R(:,:,3) = B;
-    R(:,:,2) = G;
   endif
+
 endfunction
+
+
+%!shared img, map, ergb, rgb, r, g, b
+%! img = [2 4 5; 3 2 5; 1 2 4];
+%! map = [0.0  0.0  0.0
+%!        0.2  0.4  0.6
+%!        0.4  0.4  0.5
+%!        0.3  0.7  1.0
+%!        0.1  0.5  0.8];
+%! ergb(:,:,1) = [0.2 0.3 0.1; 0.4 0.2 0.1; 0.0 0.2 0.3];
+%! ergb(:,:,2) = [0.4 0.7 0.5; 0.4 0.4 0.5; 0.0 0.4 0.7];
+%! ergb(:,:,3) = [0.6 1.0 0.8; 0.5 0.6 0.8; 0.0 0.6 1.0];
+%! ## test basic usage with 1 and 3 outputs
+%! [rgb] = ind2rgb (img, map);
+%! [r, g, b] = ind2rgb (img, map);
+%!assert (ergb, rgb);
+%!assert (ergb, reshape ([r(:) g(:) b(:)], [size(img) 3]));
+%! ## test correction for integers
+%! img = uint8 (img -1);
+%! [rgb] = ind2rgb (img, map);
+%!assert (ergb, rgb);
+%! ## check it fails when image is a float with an index value of 0
+%!fail ("[rgb] = ind2rgb (double(img), map)")
+
+%% Test input validation
+%!error ind2rgb ()
+%!error ind2rgb (1,2,3)
+%!error <X must be an indexed image> ind2rgb ({1}, jet (64))
+%!error <X must be an indexed image> ind2rgb (1+i, jet (64))
+%!error <X must be an indexed image> ind2rgb (sparse (1), jet (64))
+%!error <X must be an indexed image> ind2rgb (0, jet (64))
+%!error <X must be an indexed image> ind2rgb (1.1, jet (64))
+%!error <MAP must be a valid colormap> ind2rgb (1, {1})
+%!error <MAP must be a valid colormap> ind2rgb (1, 1+i)
+%!error <MAP must be a valid colormap> ind2rgb (1, ones (2,2,2))
+%!error <MAP must be a valid colormap> ind2rgb (1, ones (2,4))
+%!error <MAP must be a valid colormap> ind2rgb (1, [-1])
+%!error <MAP must be a valid colormap> ind2rgb (1, [2])
+
--- a/scripts/image/iscolormap.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/iscolormap.m	Sun Dec 23 13:00:02 2012 -0500
@@ -20,10 +20,10 @@
 ## @deftypefn {Function File} {} iscolormap (@var{cmap})
 ## Return true if @var{cmap} is a colormap.
 ##
-## A colormap is an @var{n} row by 3 column matrix.  The columns contain red,
-## green, and blue intensities respectively.  All entries must be between 0
-## and 1 inclusive.
-##
+## A colormap is a real matrix with @var{n} rows and 3 columns.
+## Each row represents a single color.  The columns contain red, green,
+## and blue intensities respectively.  All entries must be between 0 and 1
+## inclusive.
 ## @seealso{colormap, rgbplot}
 ## @end deftypefn
 
@@ -36,7 +36,7 @@
   endif
 
   retval = (isnumeric (cmap) && isreal (cmap) &&
-            columns (cmap) == 3 && ndims (cmap) == 2 && isa (cmap, "double") &&
+            ndims (cmap) == 2 && columns (cmap) == 3 && isa (cmap, "double") &&
             min (cmap(:)) >= 0 && max (cmap(:)) <= 1);
 
 endfunction
@@ -45,8 +45,9 @@
 %!assert (iscolormap (jet (64)))
 %!assert (iscolormap ({0 1 0}), false)
 %!assert (iscolormap ([0 1i 0]), false)
+%!assert (iscolormap (ones (3,3,3)), false)
 %!assert (iscolormap (ones (3,4)), false)
-%!assert (iscolormap (ones (3,3,3)), false)
 %!assert (iscolormap (single (jet (64))), false)
 %!assert (iscolormap ([0 0 -2]), false)
 %!assert (iscolormap ([0 0 2]), false)
+
--- a/scripts/image/jet.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/jet.m	Sun Dec 23 13:00:02 2012 -0500
@@ -37,7 +37,7 @@
     n = rows (colormap);
   elseif (nargin == 1)
     if (! isscalar (n))
-      error ("jet: argument must be a scalar");
+      error ("jet: N must be a scalar");
     endif
   else
     print_usage ();
--- a/scripts/image/lines.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/lines.m	Sun Dec 23 13:00:02 2012 -0500
@@ -36,7 +36,7 @@
     n = rows (colormap);
   elseif (nargin == 1)
     if (! isscalar (n))
-      error ("lines: argument must be a scalar");
+      error ("lines: N must be a scalar");
     endif
   else
     print_usage ();
--- a/scripts/image/module.mk	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/module.mk	Sun Dec 23 13:00:02 2012 -0500
@@ -1,5 +1,8 @@
 FCN_FILE_DIRS += image
 
+image_PRIVATE_FCN_FILES = \
+  image/private/ind2x.m
+
 image_FCN_FILES = \
   image/autumn.m \
   image/bone.m \
@@ -42,7 +45,8 @@
   image/spring.m \
   image/summer.m \
   image/white.m \
-  image/winter.m
+  image/winter.m \
+  $(image_PRIVATE_FCN_FILES)
 
 IMAGES += \
   image/default.img
--- a/scripts/image/ntsc2rgb.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/ntsc2rgb.m	Sun Dec 23 13:00:02 2012 -0500
@@ -20,7 +20,18 @@
 ## @deftypefn  {Function File} {@var{rgb_map} =} ntsc2rgb (@var{yiq_map})
 ## @deftypefnx {Function File} {@var{rgb_img} =} ntsc2rgb (@var{yiq_img})
 ## Transform a colormap or image from luminance-chrominance (NTSC) space to
-## red-green-blue (RGB) space.
+## red-green-blue (RGB) color space.
+##
+## Implementation Note:
+## The conversion matrix is chosen to be the inverse of the
+## matrix used for rgb2ntsc such that
+##
+## @example
+## x == ntsc2rgb (rgb2ntsc (x))
+## @end example
+##
+## @sc{matlab} uses a slightly different matrix where rounding
+## means the equality above does not hold.
 ## @seealso{rgb2ntsc, hsv2rgb, ind2rgb}
 ## @end deftypefn
 
@@ -34,36 +45,58 @@
     print_usage ();
   endif
 
+  if (! isa (yiq, "double"))
+    error ("ntsc2rgb: YIQ must be of type double");
+  endif
+
   ## If we have an image convert it into a color map.
   if (ismatrix (yiq) && ndims (yiq) == 3)
     is_image = true;
-    Sz = size (yiq);
+    sz = size (yiq);
     yiq = [yiq(:,:,1)(:), yiq(:,:,2)(:), yiq(:,:,3)(:)];
-    ## Convert to a double image.
-    if (isinteger (yiq))
-      C = class (yiq);
-      low = double (intmin (C));
-      high = double (intmax (C));
-      yiq = (double (yiq) - low) / (high - low);
-    endif
   else
     is_image = false;
   endif
 
-  if (! ismatrix (yiq) || columns (yiq) != 3)
-    error ("ntsc2rgb: argument must be a matrix of size Nx3 or NxMx3");
+  if (! isreal (yiq) || columns (yiq) != 3 || issparse (yiq))
+    error ("ntsc2rgb: input must be a matrix of size Nx3 or NxMx3");
   endif
 
-  ## Convert data
+  ## Conversion matrix constructed from 'inv (rgb2ntsc matrix)'.
+  ## See programming notes in rgb2ntsc.m.  Note: Matlab matrix for inverse
+  ## is slightly different.  We prefer this matrix so that
+  ## x == ntsc2rgb (rgb2ntsc (x)) rather than maintaining strict compatibility
+  ## with Matlab.
   trans = [ 1.0,      1.0,      1.0;
             0.95617, -0.27269, -1.10374;
-            0.62143, -0.64681, 1.70062 ];
+            0.62143, -0.64681,  1.70062 ];
 
   rgb = yiq * trans;
 
   ## If input was an image, convert it back into one.
   if (is_image)
-    rgb = reshape (rgb, Sz);
+    rgb = reshape (rgb, sz);
   endif
 
 endfunction
+
+
+%% Test pure R, G, B colors
+%!assert (ntsc2rgb ([.299  .596  .211]), [1 0 0], 1e-5)
+%!assert (ntsc2rgb ([.587 -.274 -.523]), [0 1 0], 1e-5)
+%!assert (ntsc2rgb ([.114 -.322  .312]), [0 0 1], 1e-5)
+
+%!test
+%! rgb_map = rand (64, 3);
+%! assert (ntsc2rgb (rgb2ntsc (rgb_map)), rgb_map, 1e-3);
+
+%!test
+%! rgb_img = rand (64, 64, 3);
+%! assert (ntsc2rgb (rgb2ntsc (rgb_img)), rgb_img, 1e-3);
+
+%% Test input validation
+%!error ntsc2rgb ()
+%!error ntsc2rgb (1,2)
+%!error <YIQ must be of type double> ntsc2rgb (uint8 (1))
+%!error <must be a matrix of size Nx3 or NxMx3> ntsc2rgb (ones (2,2))
+
--- a/scripts/image/ocean.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/ocean.m	Sun Dec 23 13:00:02 2012 -0500
@@ -39,7 +39,7 @@
     n = rows (colormap);
   elseif (nargin == 1)
     if (! isscalar (n))
-      error ("ocean: argument must be a scalar");
+      error ("ocean: N must be a scalar");
     endif
   else
     print_usage ();
--- a/scripts/image/pink.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/pink.m	Sun Dec 23 13:00:02 2012 -0500
@@ -37,7 +37,7 @@
     n = rows (colormap);
   elseif (nargin == 1)
     if (! isscalar (n))
-      error ("pink: argument must be a scalar");
+      error ("pink: N must be a scalar");
     endif
   else
     print_usage ();
--- a/scripts/image/prism.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/prism.m	Sun Dec 23 13:00:02 2012 -0500
@@ -37,7 +37,7 @@
     n = rows (colormap);
   elseif (nargin == 1)
     if (! isscalar (n))
-      error ("prism: argument must be a scalar");
+      error ("prism: N must be a scalar");
     endif
   else
     print_usage ();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/image/private/ind2x.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,55 @@
+## Copyright (C) 1994-2012 John W. Eaton
+## Copyright (C) 2012 Carnë Draug
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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/>.
+
+## private function for the ind2XXX functions which have a lot of code in common
+
+function [x, map] = ind2x (caller, x, map)
+
+  ## Check if X is an indexed image.
+  if (ndims (x) != 2 || issparse (x) || (isfloat (x) && ! isindex (x)) ||
+      ! any (strcmp (class (x), {"uint8", "uint16", "single", "double"})))
+    error ("%s: X must be an indexed image", caller);
+  endif
+
+  ## Check if map is a valid colormap.
+  if (! iscolormap (map))
+    error ("%s: MAP must be a valid colormap", caller);
+  endif
+
+  ## Do we have enough colors in the color map?
+  ## there's an offset of 1 when the indexed image is an integer class so we fix
+  ## it now and convert it to float only if really necessary and even then only
+  ## to single precision since that is enough for both uint8 and uint16.
+  maxidx = max (x(:));
+  if (isinteger (x))
+    if (maxidx == intmax (class (x)))
+      x = single (x);
+    endif
+    x      += 1;
+    maxidx += 1;
+  endif
+
+  num_colors = rows (map);
+  if (num_colors < maxidx)
+    ## Pad with the last color in the map for matlab compatibility
+    pad = repmat (map(end,:), maxidx - num_colors, 1);
+    map(end+1:maxidx, :) = pad;
+  endif
+
+endfunction
--- a/scripts/image/rainbow.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/rainbow.m	Sun Dec 23 13:00:02 2012 -0500
@@ -40,7 +40,7 @@
     n = rows (colormap);
   elseif (nargin == 1)
     if (! isscalar (n))
-      error ("rainbow: argument must be a scalar");
+      error ("rainbow: N must be a scalar");
     endif
   else
     print_usage ();
--- a/scripts/image/rgb2hsv.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/rgb2hsv.m	Sun Dec 23 13:00:02 2012 -0500
@@ -24,7 +24,7 @@
 ##
 ## A color in the RGB space consists of red, green, and blue intensities.
 ##
-## A color in HSV space is represented by hue, saturation and value
+## A color in HSV space is represented by hue, saturation, and value
 ## (brightness) levels.  Value gives the amount of light in the color.  Hue
 ## describes the dominant wavelength.  Saturation is the amount of hue mixed
 ## into the color.
@@ -40,32 +40,38 @@
     print_usage ();
   endif
 
+  cls = class (rgb);
+  if (! any (strcmp (cls, {"uint8", "uint16", "single", "double"})))
+    error ("rgb2hsv: invalid data type '%s'", cls);
+  elseif (isfloat (rgb) && (any (rgb(:) < 0) || any (rgb(:) > 1)))
+    error ("rgb2hsv: floating point images may only contain values between 0 and 1");
+  endif
+
   ## If we have an image convert it into a color map.
-  if (ismatrix (rgb) && ndims (rgb) == 3)
+  if (isreal (rgb) && ndims (rgb) == 3)
     is_image = true;
-    Sz = size (rgb);
+    sz = size (rgb);
     rgb = [rgb(:,:,1)(:), rgb(:,:,2)(:), rgb(:,:,3)(:)];
     ## Convert to a double image.
     if (isinteger (rgb))
-      C = class (rgb);
-      low = double (intmin (C));
-      high = double (intmax (C));
+      low = double (intmin (cls));
+      high = double (intmax (cls));
       rgb = (double (rgb) - low) / (high - low);
     endif
   else
     is_image = false;
   endif
 
-  if (! ismatrix (rgb) || columns (rgb) != 3)
-    error ("rgb2hsv: RGB_MAP must be a matrix of size n x 3");
+  if (! ismatrix (rgb) || columns (rgb) != 3 || issparse (rgb))
+    error ("rgb2hsv: input must be a matrix of size Nx3 or MxNx3");
   endif
 
-  ## get the max and min
-  s = min (rgb')';
-  v = max (rgb')';
+  ## get the max and min for each row
+  s = min (rgb, [], 2);
+  v = max (rgb, [], 2);
 
   ## set hue to zero for undefined values (gray has no hue)
-  h = zeros (size (v));
+  h = zeros (rows (rgb), 1);
   notgray = (s != v);
 
   ## blue hue
@@ -85,10 +91,7 @@
   if (any (idx))
     h(idx) =       1/6 * (rgb(idx,2) - rgb(idx,3)) ./ (v(idx) - s(idx));
   endif
-
-  ## correct for negative red
-  idx = (h < 0);
-  h(idx) = 1+h(idx);
+  h(h < 0) += 1;   # correct for negative red
 
   ## set the saturation
   s(! notgray) = 0;
@@ -96,9 +99,33 @@
 
   hsv_map = [h, s, v];
 
+  ## FIXME: rgb2hsv does not preserve class of image.
+  ##        Should it also convert back to uint8, uint16 for integer images?
   ## If input was an image, convert it back into one.
   if (is_image)
-    hsv_map = reshape (hsv_map, Sz);
+    hsv_map = reshape (hsv_map, sz);
   endif
 
 endfunction
+
+
+%% Test pure colors and gray
+%!assert (rgb2hsv ([1 0 0]), [0 1 1])
+%!assert (rgb2hsv ([0 1 0]), [1/3 1 1])
+%!assert (rgb2hsv ([0 0 1]), [2/3 1 1])
+%!assert (rgb2hsv ([0.5 0.5 0.5]), [0 0 0.5])
+
+%!test
+%! rgb_map = rand (64, 3);
+%! assert (hsv2rgb (rgb2hsv (rgb_map)), rgb_map, 1e-6);
+
+%!test
+%! rgb_img = rand (64, 64, 3);
+%! assert (hsv2rgb (rgb2hsv (rgb_img)), rgb_img, 1e-6);
+
+%% Test input validation
+%!error rgb2hsv ()
+%!error rgb2hsv (1,2)
+%!error <invalid data type 'cell'> rgb2hsv ({1})
+%!error <must be a matrix of size Nx3> rgb2hsv (ones (2,2))
+
--- a/scripts/image/rgb2ind.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/rgb2ind.m	Sun Dec 23 13:00:02 2012 -0500
@@ -1,4 +1,5 @@
 ## Copyright (C) 1994-2012 John W. Eaton
+## Copyright (C) 2012 Carnë Draug
 ##
 ## This file is part of Octave.
 ##
@@ -19,11 +20,13 @@
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {[@var{x}, @var{map}] =} rgb2ind (@var{rgb})
 ## @deftypefnx {Function File} {[@var{x}, @var{map}] =} rgb2ind (@var{R}, @var{G}, @var{B})
-## Convert an image in red-green-blue (RGB) space to an indexed image.
+## Convert an image in red-green-blue (RGB) color space to an indexed image.
 ## @seealso{ind2rgb, rgb2hsv, rgb2ntsc}
 ## @end deftypefn
 
-## Bugs: The color map may have duplicate entries.
+## FIXME: This function has a very different syntax than the Matlab
+##        one of the same name.
+##        Octave function does not support N, MAP, DITHER, or TOL arguments.
 
 ## Author: Tony Richardson <arichard@stark.cc.oh.us>
 ## Created: July 1994
@@ -37,29 +40,54 @@
 
   if (nargin == 1)
     rgb = R;
-    if (length (size (rgb)) == 3 && size (rgb, 3) == 3)
+    if (ndims (rgb) != 3 || size (rgb, 3) != 3)
+      error ("rgb2ind: argument is not an RGB image");
+    else
       R = rgb(:,:,1);
       G = rgb(:,:,2);
       B = rgb(:,:,3);
-    else
-      error ("rgb2ind: argument is not an RGB image");
     endif
-  endif
-
-  if (! size_equal (R, G) || ! size_equal (R, B))
-    error ("rgb2ind: arguments must all have the same size");
+  elseif (! size_equal (R, G, B))
+    error ("rgb2ind: R, G, and B must have the same size");
   endif
 
-  [hi, wi] = size (R);
+  x = reshape (1:numel (R), size (R));
 
-  x = zeros (hi, wi);
-
-  map = zeros (hi*wi, 3);
+  map    = unique ([R(:) G(:) B(:)], "rows");
+  [~, x] = ismember ([R(:) G(:) B(:)], map, "rows");
+  x      = reshape (x, size (R));
 
-  map(:,1) = R(:);
-  map(:,2) = G(:);
-  map(:,3) = B(:);
+  ## a colormap is of class double and values between 0 and 1
+  switch (class (R))
+    case {"single", "double", "logical"}
+      ## do nothing, return the same
+    case {"uint8", "uint16"}
+      map = double (map) / double (intmax (class (R)));
+    case "int16"
+      map = (double (im) + 32768) / 65535;
+    otherwise
+      error ("unsupported image class %s", im_class);
+  endswitch
 
-  x(:) = 1:(hi*wi);
+  ## we convert to the smallest class necessary to encode the image. Matlab
+  ## documentation does not mention what it does when uint16 is not enough...
+  ## When an indexed image is of integer class, there's a -1 offset to the
+  ## colormap, hence the adjustment
+  if (rows (map) < 256)
+    x = uint8 (x - 1);
+  elseif (rows (map) < 65536)
+    x = uint16 (x - 1);
+  else
+    ## leave it as double
+  endif
 
 endfunction
+
+
+%% FIXME: Need some functional tests or %!demo blocks
+
+%% Test input validation
+%!error rgb2ind ()
+%!error rgb2ind (1,2)
+%!error rgb2ind (1,2,3,4)
+
--- a/scripts/image/rgb2ntsc.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/rgb2ntsc.m	Sun Dec 23 13:00:02 2012 -0500
@@ -19,8 +19,25 @@
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {@var{yiq_map} =} rgb2ntsc (@var{rgb_map})
 ## @deftypefnx {Function File} {@var{yiq_img} =} rgb2ntsc (@var{rgb_img})
-## Transform a colormap or image from red-green-blue (RGB) space to
-## luminance-chrominance (NTSC) space.
+## Transform a colormap or image from red-green-blue (RGB) color space to
+## luminance-chrominance (NTSC) space.  The input may be of class uint8,
+## uint16, single, or double.  The output is of class double.
+##
+## Implementation Note:
+## The reference matrix for the transformation is
+##
+## @example
+## @group
+## /Y\     0.299  0.587  0.114  /R\ 
+## |I|  =  0.596 -0.274 -0.322  |G| 
+## \Q/     0.211 -0.523  0.312  \B/ 
+## @end group
+## @end example
+##
+## @noindent
+## as documented in @url{http://en.wikipedia.org/wiki/YIQ} and truncated to 3
+## significant figures.  Note: The FCC version of NTSC uses only 2
+## significant digits and is slightly different.
 ## @seealso{ntsc2rgb, rgb2hsv, rgb2ind}
 ## @end deftypefn
 
@@ -34,36 +51,68 @@
     print_usage ();
   endif
 
+  cls = class (rgb);
+  if (! any (strcmp (cls, {"uint8", "uint16", "single", "double"})))
+    error ("rgb2ntsc: invalid data type '%s'", cls);
+  elseif (isfloat (rgb) && (any (rgb(:) < 0) || any (rgb(:) > 1)))
+    error ("rgb2ntsc: floating point images may only contain values between 0 and 1");
+  endif
+
   ## If we have an image convert it into a color map.
-  if (ismatrix (rgb) && ndims (rgb) == 3)
+  if (isreal (rgb) && ndims (rgb) == 3)
     is_image = true;
-    Sz = size (rgb);
+    sz = size (rgb);
     rgb = [rgb(:,:,1)(:), rgb(:,:,2)(:), rgb(:,:,3)(:)];
     ## Convert to a double image.
     if (isinteger (rgb))
-      C = class (rgb);
-      low = double (intmin (C));
-      high = double (intmax (C));
+      low = double (intmin (cls));
+      high = double (intmax (cls));
       rgb = (double (rgb) - low) / (high - low);
+    elseif (isa (rgb, "single"))
+      rgb = double (rgb);
     endif
   else
     is_image = false;
   endif
 
-  if (! ismatrix (rgb) || columns (rgb) != 3)
-    error ("rgb2ntsc: argument must be a matrix of size Nx3 or NxMx3");
+  if (! isreal (rgb) || columns (rgb) != 3 || issparse (rgb))
+    error ("rgb2ntsc: input must be a matrix of size Nx3 or NxMx3");
   endif
 
-  ## Convert data
+  ## Reference matrix for transformation from http://en.wikipedia.org/wiki/YIQ
+  ## and truncated to 3 significant figures.  Matlab uses this matrix for their
+  ## conversion.
   trans = [ 0.299,  0.596,  0.211;
             0.587, -0.274, -0.523;
             0.114, -0.322,  0.312 ];
 
+  ## Convert data. 
   yiq = rgb * trans;
 
   ## If input was an image, convert it back into one.
   if (is_image)
-    yiq = reshape (yiq, Sz);
+    yiq = reshape (yiq, sz);
   endif
 
 endfunction
+
+
+%% Test pure RED, GREEN, BLUE colors
+%assert (rgb2ntsc ([1 0 0]), [.299  .587  .114])
+%assert (rgb2ntsc ([0 1 0]), [.596 -.274 -.322])
+%assert (rgb2ntsc ([1 0 1]), [.211 -.523  .312])
+
+%!test
+%! rgb_map = rand (64, 3);
+%! assert (ntsc2rgb (rgb2ntsc (rgb_map)), rgb_map, 1e-3);
+
+%!test
+%! rgb_img = rand (64, 64, 3);
+%! assert (ntsc2rgb (rgb2ntsc (rgb_img)), rgb_img, 1e-3);
+
+%% Test input validation
+%!error rgb2ntsc ()
+%!error rgb2ntsc (1,2)
+%!error <invalid data type 'cell'> rgb2ntsc ({1})
+%!error <must be a matrix of size Nx3 or NxMx3> rgb2ntsc (ones (2,2))
+
--- a/scripts/image/rgbplot.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/rgbplot.m	Sun Dec 23 13:00:02 2012 -0500
@@ -1,4 +1,5 @@
 ## Copyright (C) 2012 Rik Wehbring
+## Copyright (C) 2012 Carnë Draug
 ##
 ## This file is part of Octave.
 ##
@@ -18,34 +19,58 @@
 
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {} rgbplot (@var{cmap})
-## @deftypefnx {Function File} {@var{h} =} rgbplot (@var{cmap})
+## @deftypefnx {Function File} {} rgbplot (@var{cmap}, @var{style})
+## @deftypefnx {Function File} {@var{h} =} rgbplot (@dots{})
 ## Plot the components of a colormap.
 ##
-## The first column is plotted in red, the second column in green, and
-## the third column in blue.  The values are between 0 and 1 and represent
-## the intensity of the RGB components in the given indexed color.
+## Two different @var{style}s are available for displaying the @var{cmap}:
+##
+## @table @asis
+## @item profile (default)
+## Plot the RGB line profile of the colormap for each of the channels (red,
+## green and blue) with the plot lines colored appropriately.  Each line
+## represents the intensity of each RGB components across the colormap.
+##
+## @item composite
+## Draw the colormap across the X-axis so that the actual index colors are
+## visible rather than the individual color components.
+##
+## @end table
 ##
 ## The optional return value @var{h} is a graphics handle to the created plot.
 ##
+## Run @code{demo rgbplot} to see an example of @code{rgbplot} and each style
+## option.
 ## @seealso{colormap}
 ## @end deftypefn
 
-function retval = rgbplot (cmap)
+function h = rgbplot (cmap, style)
 
-  if (nargin != 1)
+  if (nargin < 1 || nargin > 2)
     print_usage ();
   endif
 
   if (! iscolormap (cmap))
-    error ("rgbplot: CMAP must be a colormap");
+    error ("rgbplot: CMAP must be a valid colormap");
+  elseif (! ischar (style))
+    error ("rgbplot: STYLE must be a string");
   endif
 
-  h = plot (cmap(:,1),"r", cmap(:,2),"g", cmap(:,3),"b");
-  set (gca, 'ytick', 0:0.1:1);
+  switch (tolower (style))
+    case "profile"
+      htmp = plot (cmap(:,1),"r", cmap(:,2),"g", cmap(:,3),"b");
+      set (gca, 'ytick', 0:0.1:1);
+    case "composite"
+      htmp = image (1:rows(cmap));
+      set (gca, 'ytick', []);
+      colormap (cmap);
+    otherwise
+      error ("rgbplot: unknown style `%s'", style);
+  endswitch
   xlabel ("color index");
 
   if (nargout > 0)
-    retval = h;
+    h = htmp;
   endif
 
 endfunction
@@ -53,9 +78,13 @@
 
 %!demo
 %! clf;
-%! rgbplot (ocean);
+%! subplot (1, 2, 1);
+%! rgbplot (ocean, "profile");
+%! subplot (1, 2, 2);
+%! rgbplot (ocean, "composite");
 
-%%test input validation
+%% Test input validation
 %!error rgbplot ()
 %!error rgbplot (1,2)
-%!error <CMAP must be a colormap> rgbplot ({0 1 0})
+%!error <CMAP must be a valid colormap> rgbplot ({0 1 0})
+
--- a/scripts/image/spring.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/spring.m	Sun Dec 23 13:00:02 2012 -0500
@@ -36,7 +36,7 @@
     n = rows (colormap);
   elseif (nargin == 1)
     if (! isscalar (n))
-      error ("spring: argument must be a scalar");
+      error ("spring: N must be a scalar");
     endif
   else
     print_usage ();
--- a/scripts/image/summer.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/summer.m	Sun Dec 23 13:00:02 2012 -0500
@@ -37,7 +37,7 @@
     n = rows (colormap);
   elseif (nargin == 1)
     if (! isscalar (n))
-      error ("summer: argument must be a scalar");
+      error ("summer: N must be a scalar");
     endif
   else
     print_usage ();
--- a/scripts/image/white.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/white.m	Sun Dec 23 13:00:02 2012 -0500
@@ -36,7 +36,7 @@
     n = rows (colormap);
   elseif (nargin == 1)
     if (! isscalar (n))
-      error ("white: argument must be a scalar");
+      error ("white: N must be a scalar");
     endif
   else
     print_usage ();
--- a/scripts/image/winter.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/image/winter.m	Sun Dec 23 13:00:02 2012 -0500
@@ -36,7 +36,7 @@
     n = rows (colormap);
   elseif (nargin == 1)
     if (! isscalar (n))
-      error ("winter: argument must be a scalar");
+      error ("winter: N must be a scalar");
     endif
   else
     print_usage ();
--- a/scripts/io/importdata.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/io/importdata.m	Sun Dec 23 13:00:02 2012 -0500
@@ -259,6 +259,15 @@
                                         delimiter_pattern, "split")));
   endfor
 
+  ## FIXME: Make it behave like Matlab when importing a table where a whole
+  ## column is text only. E.g.
+  ##    abc  12  34
+  ##    def  56  78
+  ## This would give a 3x2 data matrix with the left column = nan(2,1), and 
+  ## the text would end up in textdata.
+  ## In Matlab the data matrix would only be a 2x2 matrix, see example at:
+  ## http://www.mathworks.se/help/matlab/import_export/import-numeric-data-and-header-text-from-a-text-file.html
+
   ## Go through the data and put it in either output.data or
   ## output.textdata depending on if it is numeric or not.
   output.data = NaN (length (file_content_rows) - header_rows, data_columns);
@@ -273,7 +282,7 @@
         ## output.data, otherwise in output.textdata
         if (!isempty (row_data{j}))
           data_numeric = str2double (row_data{j});
-          if (!isempty (data_numeric))
+          if (!isnan (data_numeric))
             output.data(i-header_rows, j) = data_numeric;
           else
             output.textdata{i,j} = row_data{j};
@@ -387,6 +396,19 @@
 %! assert (h, 0);
 
 %!test
+%! # Complex numbers
+%! A = [3.1 -7.2 0-3.4i; 0.012 -6.5+7.2i 128];
+%! fn  = tmpnam ();
+%! fid = fopen (fn, "w");
+%! fputs (fid, "3.1\t-7.2\t0-3.4i\n0.012\t-6.5+7.2i\t128");
+%! fclose (fid);
+%! [a,d,h] = importdata (fn, "\\t");
+%! unlink (fn);
+%! assert (a, A);
+%! assert (d, "\t");
+%! assert (h, 0);
+
+%!test
 %! # Missing values
 %! A = [3.1 NaN 0; 0.012 6.5 128];
 %! fn  = tmpnam ();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/dlgtest.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,205 @@
+%
+% Test the dlg... functions of the Octave-Java bridge
+%
+% Once the Java bridge works OK this function should be dropped from core octave
+%
+% Author: Martin Hepperle
+% Version August 2010
+% Adapted for core Octave Philip Nienhuis 2012
+%
+function dlgtest
+
+  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 = numel (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 = numel (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	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,55 @@
+## Copyright (C) 2010 Martin Hepperle
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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} {@var{h} =} errordlg (@var{msg})
+## @deftypefnx {Function File} {@var{h} =} errordlg (@var{msg}, @var{title})
+## Display @var{msg} using an error dialog box.
+##
+## The message may have multiple lines separated by newline characters
+## ("\n"), or it may be a cellstr array with one element for each
+## line.  The optional input @var{title} (character string) can be used to
+## set the dialog caption.  The default title is "Error Dialog".
+##
+## The return value is always 1.
+## @seealso{helpdlg, inputdlg, listdlg, msgbox, questdlg, warndlg}
+## @end deftypefn
+
+function h = errordlg (msg, title = "Error Dialog")
+
+  if (nargin < 1 || nargin > 2)
+    print_usage ();
+  endif
+
+  if (! ischar (msg))
+    if (iscell (msg))
+      msg = sprintf ("%s\n", msg{:});
+      msg(end) = "";
+    else
+      error ("errordlg: MSG must be a string or cellstr array");
+    endif
+  endif
+
+  if (! ischar (title))
+    error ("errordlg: TITLE must be a character string");
+  endif
+
+  h = javaMethod ("errordlg", "org.octave.JDialogBox", msg, title);
+
+endfunction
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/helpdlg.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,55 @@
+## Copyright (C) 2010 Martin Hepperle
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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} {@var{h} =} helpdlg (@var{msg})
+## @deftypefnx {Function File} {@var{h} =} helpdlg (@var{msg}, @var{title})
+## Display @var{msg} in a help dialog box.
+##
+## The message may have multiple lines separated by newline characters
+## ("\n"), or it may be a cellstr array with one element for each
+## line.  The optional input @var{title} (character string) can be used to
+## set the dialog caption.  The default title is "Help Dialog".
+##
+## The return value is always 1.
+## @seealso{errordlg, inputdlg, listdlg, msgbox, questdlg, warndlg}
+## @end deftypefn
+
+function h = helpdlg (msg, title = "Help Dialog")
+
+  if (nargin < 1 || nargin > 2)
+    print_usage ();
+  endif
+
+  if (! ischar (msg))
+    if (iscell (msg))
+      msg = sprintf ("%s\n", msg{:});
+      msg(end) = "";
+    else
+      error ("helpdlg: MSG must be a string or cellstr array");
+    endif
+  endif
+
+  if (! ischar (title))
+    error ("helpdlg: TITLE must be a character string");
+  endif
+
+  h = javaMethod ("helpdlg", "org.octave.JDialogBox", msg, title);
+
+endfunction
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/inputdlg.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,138 @@
+## Copyright (C) 2010 Martin Hepperle
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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} {@var{cstr} =} inputdlg (@var{prompt})
+## @deftypefnx {Function File} {@var{cstr} =} inputdlg (@var{prompt}, @var{title})
+## @deftypefnx {Function File} {@var{cstr} =} inputdlg (@var{prompt}, @var{title}, @var{rowscols})
+## @deftypefnx {Function File} {@var{cstr} =} inputdlg (@var{prompt}, @var{title}, @var{rowscols}, @var{defaults})
+## Return user input from a multi-textfield dialog box in a cell array
+## of strings, or an empty cell array if the dialog is closed by the
+## Cancel button.
+##
+## Inputs:
+##
+## @table @var
+## @item prompt
+## A cell array with strings labeling each text field.  This input is required. 
+##
+## @item title
+## String to use for the caption of the dialog.  The default is "Input Dialog".
+##
+## @item rowscols
+## Specifies the size of the text fields and can take three forms:
+##
+## @enumerate
+## @item a scalar value which defines the number of rows used for each
+## text field.
+##
+## @item a vector which defines the individual number of rows
+## used for each text field. 
+##
+## @item a matrix which defines the individual number of rows and
+## columns used for each text field.  In the matrix each row describes
+## a single text field.  The first column specifies the number of input
+## rows to use and the second column specifies the text field width.
+## @end enumerate
+##
+## @item defaults
+## A list of default values to place in each text fields.  It must be
+## a cell array of strings with the same size as @var{prompt}.
+## @end table
+## @seealso{errordlg, helpdlg, listdlg, msgbox, questdlg, warndlg}
+## @end deftypefn
+
+function cstr = inputdlg (prompt, title = "Input Dialog", varargin)
+
+  if (nargin < 1 || nargin > 4)
+    print_usage ();
+  endif
+
+  if (iscell (prompt))
+    ## Silently extract only char elements
+    prompt = prompt(cellfun ("ischar", prompt));
+  elseif (ischar (prompt))
+    prompt = {prompt};
+  else
+    error ("inputdlg: PROMPT must be a character string or cellstr array");
+  endif
+
+  if (! ischar (title))
+    error ("inputdlg: TITLE must be a character string");
+  endif
+
+  switch (numel (varargin))
+    case 0
+      linespec = 1;
+      defaults = cellstr (cell (size (prompt)));
+
+    case 1
+      linespec = varargin{1};
+      defaults = cellstr (cell (size (prompt)));
+
+    case 2
+      linespec = varargin{1};
+      defaults = varargin{2};
+  endswitch
+
+  ## specification of text field sizes as in Matlab 
+  ## Matlab requires a matrix for linespec, 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 (linespec))
+    ## only scalar value in lineTo, copy from linespec and add defaults
+    rowscols = zeros (columns (prompt), 2);
+    ## cols
+    rowscols(:,2) = 25;
+    rowscols(:,1) = linespec;
+  elseif (isvector (linespec))
+      ## only one column in lineTo, copy from vector linespec and add defaults
+      rowscols = zeros (columns (prompt), 2);
+      ## rows from colum vector linespec, columns are set to default
+      rowscols(:,2) = 25;
+      rowscols(:,1) = linespec(:);
+  elseif (ismatrix (linespec))
+    if (rows (linespec) == columns (prompt) && columns (linespec) == 2)
+      ## (rows x columns) match, copy array linespec
+      rowscols = linespec;
+    else
+      error ("inputdlg: ROWSCOLS matrix does not match size of PROMPT");
+    endif
+
+  else
+    ## dunno
+    error ("inputdlg: unknown form of ROWSCOLS argument");
+  endif
+  
+  ## convert numeric values in defaults cell array to strings
+  defs = cellfun (@num2str, defaults, "UniformOutput", false);
+  rc = arrayfun (@num2str, rowscols, "UniformOutput", false);
+
+  user_inputs = javaMethod ("inputdlg", "org.octave.JDialogBox",
+                             prompt, title, rc, defs);
+  
+   if (isempty (user_inputs))
+     cstr = {};
+   else
+     cstr = cellstr (user_inputs);
+   endif
+
+endfunction
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/javaArray.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,54 @@
+## Copyright (C) 2007 Michael Goffioul
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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} {@var{jary} =} javaArray (@var{classname}, @var{sz})
+## @deftypefnx {Function File} {@var{jary} =} javaArray (@var{classname}, @var{m}, @var{n}, @dots{})
+##
+## Create a Java array of size @var{sz} with elements of class
+## @var{classname}.  @var{classname} may be a Java object representing a class
+## or a string containing the fully qualified class name.  The size of
+## the object may also be specified with individual integer arguments
+## @var{m}, @var{n}, etc.
+##
+## The generated array is uninitialized.  All elements are set to null
+## if @var{classname} is a reference type, or to a default value (usually 0)
+## if @var{classname} is a primitive type.
+##
+## Sample code:
+##
+## @example
+## @group
+## jary = javaArray ("java.lang.String", 2, 2);
+## jary(1,1) = "Hello";
+## @end group
+## @end example
+## @seealso{javaObject}
+## @end deftypefn
+
+function retval = javaArray (classname, varargin)
+
+  if (nargin < 2)
+    print_usage ();
+  endif
+
+  retval = javaMethod ("createArray", "org.octave.ClassHelper",
+                        classname, [varargin{:}]);
+
+endfunction
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/javaaddpath.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,59 @@
+## Copyright (C) 2007 Michael Goffioul
+## Copyright (C) 2010 Martin Hepperle
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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} {} javaaddpath (@var{clspath})
+## @deftypefnx {Function File} {} javaaddpath (@var{clspath1}, @dots{})
+## Add @var{clspath} to the dynamic class path of the Java virtual
+## machine.  @var{clspath} may either be a directory where @file{.class}
+## files are found, or a @file{.jar} file containing Java classes.
+## Multiple paths may be added at once by specifying additional arguments.
+## @seealso{javarmpath, javaclasspath}
+## @end deftypefn
+
+function javaaddpath (varargin)
+
+  if (nargin < 1)
+    print_usage ();
+  endif
+
+  for i = 1:numel (varargin)
+    clspath = varargin{i};
+    if (! ischar (clspath))
+      error ("javaaddpath: CLSPATH must be a string");
+    endif
+
+    new_path = canonicalize_file_name (tilde_expand (clspath));
+    if (exist (new_path, "dir"))
+      if (new_path(end) != filesep ())
+        new_path = [new_path, filesep()];
+      endif
+    elseif (! exist (new_path, "file"))
+      error ("javaaddpath: CLSPATH does not exist: %s", clspath);
+    endif
+
+    success = javaMethod ("addClassPath", "org.octave.ClassHelper", new_path);
+
+    if (! success)
+      warning ("javaaddpath: failed to add '%s' to Java classpath", new_path);
+    endif
+  endfor 
+   
+endfunction
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/javaclasspath.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,125 @@
+## Copyright (C) 2007 Michael Goffioul
+## Copyright (C) 2010 Martin Hepperle
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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} {} javaclasspath ()
+## @deftypefnx {Function File} {@var{dpath} =} javaclasspath ()
+## @deftypefnx {Function File} {[@var{dpath}, @var{spath}] =} javaclasspath ()
+## @deftypefnx {Function File} {@var{clspath} =} javaclasspath (@var{what})
+## Return the class path of the Java virtual machine in the form of a cell
+## array of strings. 
+##
+## If called with no inputs:
+##
+## @itemize
+## @item If no output is requested, the dynamic and static classpaths are printed 
+## to the standard output.
+##
+## @item If one output value @var{dpath} is requested, the result is
+## the dynamic classpath.
+##
+## @item If two output values@var{dpath} and @var{spath} are 
+## requested, the first variable will contain the dynamic classpath and
+## the second will be contain the static classpath.
+## @end itemize
+## 
+## If called with a single input parameter @var{what}:
+##
+## @table @asis
+## @item "-dynamic"
+## Return the dynamic classpath.
+##
+## @item "-static"
+## Return the static classpath.
+##
+## @item "-all"
+## Return both the static and dynamic classpath in a single cellstr.
+## @end table
+## @seealso{javaaddpath, javarmpath}
+## @end deftypefn
+
+function varargout = javaclasspath (which)
+
+  ## dynamic classpath
+  dynamic_path = javaMethod ("getClassPath", "org.octave.ClassHelper");
+  dynamic_path_list = strsplit (dynamic_path, pathsep ());
+
+  ## static classpath
+  static_path = javaMethod ("getProperty", "java.lang.System", "java.class.path");
+  static_path_list = strsplit (static_path, pathsep ());
+  if (numel (static_path_list) > 1)
+    ## remove first element (which is .../octave.jar)
+    static_path_list(1) = [];
+  else
+    static_path_list = {};
+  endif
+
+  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"))
+            disp_path_list ("STATIC", static_path_list)
+          elseif (strcmp (which, "-dynamic"))
+            disp_path_list ("DYNAMIC", dynamic_path_list)
+          elseif (strcmp (which, "-all") == 1)
+            disp_path_list ("STATIC", static_path_list)
+            disp ("");
+            disp_path_list ("DYNAMIC", dynamic_path_list)
+          endif
+
+        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]);
+          endif
+      endswitch
+  endswitch
+  
+endfunction
+
+## Display cell array of paths
+
+function disp_path_list (which, path_list)
+  printf ("   %s JAVA PATH\n\n", which);
+  if (numel (path_list) > 0)
+    printf ("      %s\n", path_list{:});
+  else
+    printf ("      - empty -\n");
+  endif
+endfunction
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/javamem.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,93 @@
+## Copyright (C) 2010 Philip Nienhuis
+## 
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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 the current memory usage of the Java virtual machine (JVM)
+## and run the garbage collector.
+##
+## When no return argument is given the info is printed to the screen.
+## Otherwise, the 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 allowable memory usage can be set using the file java.opts
+## (in the same subdirectory where javaaddpath.m lives, see 
+## "which javaaddpath".  Usually that is:
+##
+## @file{OCTAVE_HOME/share/octave/OCTAVE_VERSION/m/java/}
+##
+## java.opts is a plain text file with one option per line.  The
+## default initial memory size and default maximum memory size (which
+## are both system dependent) can be overridden like so:
+##
+## @nospell{-Xms64m}
+##
+## @nospell{-Xmx512m}
+##
+## (in megabytes in this example.)
+## You can adapt these values to your own requirements if your system
+## has limited available physical memory or if 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 amount 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 jmem = javamem ()
+
+  rt = javaMethod ("getRuntime", "java.lang.Runtime");
+  rt.gc;
+  jvmem = cell (3, 1);
+  jvmem{1} = rt.maxMemory ();
+  jvmem{2} = rt.totalMemory ();
+  jvmem{3} = rt.freeMemory ();
+
+  if (nargout == 0)
+    printf ("\nJava virtual machine (JVM) memory info:\n");
+    printf ("Maximum available memory:        %5d MiB;\n",
+            jvmem{1} / 1024 / 1024);
+    printf ("   (...running garbage collector...)\n");
+    printf ("OK, current status:\n");
+    printf ("Total memory in virtual machine: %5d MiB;\n",
+            jvmem{2} / 1024 / 1024);
+    printf ("Free memory in virtual machine:  %5d MiB;\n",
+            jvmem{3} / 1024 / 1024);
+    printf ("%d CPUs available.\n", rt.availableProcessors ());
+  else
+    jmem = jvmem;
+  endif
+
+endfunction
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/javarmpath.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,58 @@
+## Copyright (C) 2007 Michael Goffioul
+## Copyright (C) 2010 Martin Hepperle
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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} {} javarmpath (@var{clspath})
+## @deftypefnx {Function File} {} javarmpath (@var{clspath1}, @dots{})
+## Remove @var{clspath} from the dynamic class path of the Java virtual
+## machine.  @var{clspath} may either be a directory where @file{.class}
+## files are found, or a @file{.jar} file containing Java classes.
+## Multiple paths may be removed at once by specifying additional arguments.
+## @seealso{javaaddpath, javaclasspath}
+## @end deftypefn
+
+function javarmpath (varargin)
+
+  if (nargin < 1)
+    print_usage ();
+  endif
+
+  for i = 1:numel (varargin)
+    clspath = varargin{i};
+    if (! ischar (clspath))
+      error ("javarmpath: CLSPATH must be a string");
+    endif
+
+    old_path = canonicalize_file_name (tilde_expand (clspath));
+    if (exist (old_path, "dir"))
+      if (old_path(end) != filesep ())
+        old_path = [old_path, filesep()];
+      endif
+    endif
+
+    success = javaMethod ("removeClassPath", "org.octave.ClassHelper",
+                           old_path);
+
+    if (! success)
+      warning ("javarmpath: %s: not found in Java classpath", old_path);
+    endif
+  endfor
+
+endfunction
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/listdlg.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,142 @@
+## Copyright (C) 2010 Martin Hepperle
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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} {[@var{sel}, @var{ok}] =} listdlg (@var{key}, @var{value}, @dots{})
+## Return user inputs from a list dialog box in a vector of 
+## selection indices @var{sel} and a flag @var{ok} indicating how the
+## user closed the dialog box.  The value of @var{ok} is 1 if the user
+## closed the box with the OK button, otherwise it is 0 and @var{sel} is
+## empty.
+##
+## The indices in @var{sel} are 1 based.
+##
+## The arguments are specified in form of @var{key}, @var{value} pairs. 
+## The @code{"ListString"} argument pair must be specified.
+##
+## Valid @var{key} and @var{value} pairs are:
+##
+## @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"} (default).
+##
+## @item "ListSize"
+##    a vector with two elements @var{width} and @var{height} defining
+##    the size of the list field in pixels.  Default is [160 300].
+##
+## @item "InitialValue"
+##    a vector containing 1-based indices of preselected elements.  Default
+##    is 1 (first item).
+##
+## @item "Name"
+##    a string to be used as the dialog caption.  Default is "".
+##
+## @item "PromptString"
+##    a cell array of strings to be displayed above the list field.  Default
+##    is @{@}.
+##
+## @item "OKString"
+##    a string used to label the OK button.  Default is "OK".
+##
+## @item "CancelString"
+##    a string used to label the Cancel button.  Default is "Cancel".
+## @end table
+##
+## Example:
+##
+## @example
+## @group
+## [sel, ok] = listdlg ("ListString", @{"An item", "another", "yet another"@},
+##                      "SelectionMode", "Multiple");
+## if (ok == 1)
+##   for i = 1:numel (sel)
+##     disp (sel(i));
+##   endfor
+## endif
+## @end group
+## @end example
+##
+## @seealso{errordlg, helpdlg, inputdlg, msgbox, questdlg, warndlg}
+## @end deftypefn
+
+function varargout = listdlg (varargin)
+
+   if (nargin < 2)
+     print_usage ();
+   endif
+   
+   listcell = {""};
+   selmode = "multiple";
+   listsize = [160, 300];
+   initialvalue = 1;
+   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};
+     endif
+   endfor
+
+   ## make sure prompt strings are a cell array
+   if (! iscell (prompt))
+     prompt = {prompt};
+   endif
+
+   ## make sure listcell strings are a cell array
+   if (! iscell (listcell))
+     listcell = {listcell};
+   endif
+   
+   ## transform matrices to cell arrays of strings
+   ## swap width and height to correct calling format for JDialogBox
+   listsize = {num2str(listsize(2)), num2str(listsize(1))};
+   initialvalue = arrayfun (@num2str, initialvalue, "UniformOutput", false);
+   
+   ret = javaMethod ("listdlg", "org.octave.JDialogBox", listcell,
+                      selmode, listsize, initialvalue, name, prompt,
+                      okstring, cancelstring);
+
+   if (numel (ret) > 0)
+     varargout = {ret, 1};
+   else
+     varargout = {{}, 0};
+   endif
+
+endfunction
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/module.mk	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,83 @@
+FCN_FILE_DIRS += java
+
+java_FCN_FILES = \
+  java/dlgtest.m \
+  java/errordlg.m \
+  java/helpdlg.m \
+  java/inputdlg.m \
+  java/javaArray.m \
+  java/javaaddpath.m \
+  java/javaclasspath.m \
+  java/javamem.m \
+  java/javarmpath.m \
+  java/listdlg.m \
+  java/msgbox.m \
+  java/questdlg.m \
+  java/usejava.m \
+  java/warndlg.m
+
+FCN_FILES += $(java_FCN_FILES)
+
+PKG_ADD_FILES += java/PKG_ADD
+
+DIRSTAMP_FILES += java/$(octave_dirstamp)
+
+if AMCOND_HAVE_JAVA
+JAR_FILES += java/octave.jar
+endif
+
+org_octave_dir = org/octave
+
+if AMCOND_HAVE_JAVA
+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
+endif
+
+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))
+
+srcdir_java_JAVA_IMAGES = $(addprefix $(srcdir)/java/, $(JAVA_IMAGES))
+
+%.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: $(srcdir_java_JAVA_IMAGES)
+	if [ "x$(srcdir)" != "x." ]; then \
+	  $(MKDIR_P) java/$(org_octave_dir)/images; \
+	  cp $(srcdir_java_JAVA_IMAGES) java/$(org_octave_dir)/images; \
+	fi
+	touch $@
+
+if AMCOND_HAVE_JAVA
+java/octave.jar: java/images.stamp $(java_JAVA_CLASSES)
+	( cd java; "$(JAR)" cf octave.jar.t $(JAVA_CLASSES) $(JAVA_IMAGES) )
+	mv $@.t $@
+endif
+
+EXTRA_DIST += $(JAR_FILES) $(java_JAVA_SRC) $(java_JAVA_IMAGES)
+
+CLEANFILES += $(JAR_FILES) $(java_JAVA_CLASSES)
+
+DISTCLEANFILES += java/images.stamp
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/msgbox.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,76 @@
+## Copyright (C) 2010 Martin Hepperle
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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} {@var{h} =} msgbox (@var{msg})
+## @deftypefnx {Function File} {@var{h} =} msgbox (@var{msg}, @var{title})
+## @deftypefnx {Function File} {@var{h} =} msgbox (@var{msg}, @var{title}, @var{icon})
+## Display @var{msg} using a message dialog box. 
+##
+## The message may have multiple lines separated by newline characters
+## (@code{"\n"}), or it may be a cellstr array with one element for each
+## line.  The optional input @var{title} (character string) can be used to
+## decorate the dialog caption.
+##
+## The optional argument @var{icon} selects a dialog icon. 
+## It can be one of @code{"none"} (default), @code{"error"}, @code{"help"} or
+## @code{"warn"}.
+##
+## The return value is always 1.
+## @seealso{errordlg, helpdlg, inputdlg, listdlg, questdlg, warndlg}
+## @end deftypefn
+
+function h = msgbox (msg, title = "", icon)
+
+  if (nargin < 1 || nargin > 3)
+    print_usage ();
+  endif
+
+  if (! ischar (msg))
+    if (iscell (msg))
+      msg = sprintf ("%s\n", msg{:});
+      msg(end) = "";
+    else
+      error ("msgbox: MSG must be a character string or cellstr array");
+    endif
+  endif
+
+  if (! ischar (title))
+    error ("msgbox: TITLE must be a character string");
+  endif
+  
+  dlg = "emptydlg";
+  if (nargin == 3)
+    switch (icon)
+      case "error"
+        dlg = "errordlg";
+      case "help"
+        dlg = "helpdlg";
+      case "warn"
+        dlg = "warndlg";
+      case "none"
+        dlg = "emptydlg";
+      otherwise
+        error ("msgbox: ICON is not a valid type");
+    endswitch
+  endif
+
+  h = javaMethod (dlg, "org.octave.JDialogBox", msg, title);
+
+endfunction
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/org/octave/ClassHelper.java	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,946 @@
+/*
+
+Copyright (C) 2007 Michael Goffioul
+
+This file is part of Octave.
+
+Octave is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or (at
+your option) any later version.
+
+Octave 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/>.
+
+*/
+
+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	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,164 @@
+/*
+
+Copyright (C) 2010 Martin Hepperle
+
+This file is part of Octave.
+
+Octave is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or (at
+your option) any later version.
+
+Octave 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/>.
+
+*/
+
+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	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,991 @@
+/*
+
+Copyright (C) 2010 Martin Hepperle
+
+This file is part of Octave.
+
+Octave is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or (at
+your option) any later version.
+
+Octave 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/>.
+
+*/
+
+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	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,361 @@
+/*
+
+Copyright (C) 2007 Michael Goffioul
+
+This file is part of Octave.
+
+Octave is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or (at
+your option) any later version.
+
+Octave 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/>.
+
+*/
+
+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	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,74 @@
+/*
+
+Copyright (C) 2007 Michael Goffioul
+
+This file is part of Octave.
+
+Octave is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or (at
+your option) any later version.
+
+Octave 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/>.
+
+*/
+
+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	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,220 @@
+/*
+
+Copyright (C) 2007 Michael Goffioul
+
+This file is part of Octave.
+
+Octave is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or (at
+your option) any later version.
+
+Octave 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/>.
+
+*/
+
+package org.octave;
+
+import java.util.*;
+
+public class Octave
+{
+  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	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,64 @@
+/*
+
+Copyright (C) 2007 Michael Goffioul
+
+This file is part of Octave.
+
+Octave is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or (at
+your option) any later version.
+
+Octave 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/>.
+
+*/
+
+package org.octave;
+
+public class OctaveReference
+{
+  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	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,37 @@
+/*
+
+Copyright (C) 2010 Martin Hepperle
+
+This file is part of Octave.
+
+Octave is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or (at
+your option) any later version.
+
+Octave 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/>.
+
+*/
+
+// A class to hold a TeX character code -> Unicode translation pair.
+
+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	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,262 @@
+/*
+
+Copyright (C) 2010 Martin Hepperle
+
+This file is part of Octave.
+
+Octave is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or (at
+your option) any later version.
+
+Octave 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/>.
+
+*/
+
+// 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.:
+//   - Lucida Sans Unicode
+//   - Arial Unicode MS
+//   - MS Mincho
+
+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	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,101 @@
+## Copyright (C) 2010 Martin Hepperle
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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} {@var{btn} =} questdlg (@var{msg})
+## @deftypefnx {Function File} {@var{btn} =} questdlg (@var{msg}, @var{title})
+## @deftypefnx {Function File} {@var{btn} =} questdlg (@var{msg}, @var{title}, @var{default})
+## @deftypefnx {Function File} {@var{btn} =} questdlg (@var{msg}, @var{title}, @var{btn1}, @var{btn2}, @var{default})
+## @deftypefnx {Function File} {@var{btn} =} questdlg (@var{msg}, @var{title}, @var{btn1}, @var{btn2}, @var{btn3}, @var{default})
+## Display @var{msg} using a question dialog box and return the caption
+## of the activated button.
+##
+## The dialog may contain two or three buttons which will all close the dialog.
+##
+## The message may have multiple lines separated by newline characters
+## (@code{"\n"}), or it may be a cellstr array with one element for each
+## line.  The optional @var{title} (character string) can be used to
+## decorate the dialog caption.
+##
+## The string @var{default} identifies the default button, 
+## which is activated by pressing the @kbd{ENTER} key.
+## It must match one of the strings given in @var{btn1}, @var{btn2} or
+## @var{btn3}.
+##
+## If only @var{msg} and @var{title} are specified, three buttons with
+## the default captions "Yes", "No", and "Cancel" are used.
+##
+## If only two button captions, @var{btn1} and @var{btn2}, are specified 
+## the dialog will have only these two buttons.
+##
+## @seealso{errordlg, helpdlg, inputdlg, listdlg, warndlg}
+## @end deftypefn
+
+function btn = questdlg (msg, title = "Question Dialog", varargin)
+
+  if (nargin < 1 || nargin > 6)
+    print_usage ();
+  endif
+  
+  if (! ischar (msg))
+    if (iscell (msg))
+      msg = sprintf ("%s\n", msg{:});
+      msg(end) = "";
+    else
+      error ("questdlg: MSG must be a character string or cellstr array");
+    endif
+  endif
+
+  if (! ischar (title))
+    error ("questdlg: TITLES must be a character string");
+  endif
+
+  options{1} = "Yes";      # button1
+  options{2} = "No";       # button2
+  options{3} = "Cancel";   # button3
+  options{4} = "Yes";      # default
+
+  switch (numel (varargin))
+    case 1
+      ## default button string
+      options{4} = varargin{1};  # default
+
+    case 3
+      ## two buttons and default button string
+      options{1} = varargin{1};  # button1
+      options{2} = "";           # not used, no middle button
+      options{3} = varargin{2};  # button3
+      options{4} = varargin{3};  # default
+
+    case 4
+      ## three buttons and default button string
+      options{1} = varargin{1};  # button1
+      options{2} = varargin{2};  # button2
+      options{3} = varargin{3};  # button3
+      options{4} = varargin{4};  # default
+
+    otherwise
+      print_usage ();
+
+  endswitch
+
+  btn = javaMethod ("questdlg", "org.octave.JDialogBox", msg,
+                     title, options);
+
+endfunction
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/usejava.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,92 @@
+## Copyright (C) 2012 Rik Wehbring
+## Parts Copyright (C) 2012 Philip Nienhuis <prnienhuis@users.sf.net>
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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} {} usejava (@var{feature})
+## Return true if the Java element @var{feature} is available.
+##
+## Possible features are:
+##
+## @table @asis
+## @item "awt"
+## Abstract Window Toolkit for GUIs.
+##
+## @item "desktop"
+## Interactive desktop is running.
+##
+## @item "jvm"
+## Java Virtual Machine.
+##
+## @item "swing"
+## Swing components for lightweight GUIs.
+## @end table
+##
+## @code{usejava} determines if specific Java features are available in an
+## Octave session.  This function is provided for scripts which may alter
+## their behavior based on the availability of Java.  The feature "desktop"
+## always returns @code{false} as Octave has no Java-based desktop.  Other
+## features may be available if Octave was compiled with the Java Interface
+## and Java is installed.
+## @end deftypefn
+
+function retval = usejava (feature)
+
+  if (nargin != 1 || ! ischar (feature))
+    print_usage ();
+  endif
+
+  retval = false;
+
+  switch feature
+    ## For each feature, try methods() on a Java class of a feature
+    case "awt"
+      try
+        dum = methods ("java.awt.Frame");
+        retval = true;
+      end_try_catch
+    case "desktop"
+      ## Octave has no Java based GUI/desktop, leave retval = false
+    case "jvm"
+      try
+        dum = methods ("java.lang.Runtime");
+        retval = true;
+      end_try_catch
+    case "swing"
+      try
+        dum = methods ("javax.swing.Popup");
+        retval = true;
+      end_try_catch
+    otherwise
+      error ("usejava: unrecognized feature '%s'", feature);
+  endswitch
+
+endfunction
+
+
+%!assert (usejava ("desktop"), false)
+
+%!testif HAVE_JAVA
+%! assert (usejava ("jvm"), true);
+
+%% Test input validation
+%!error usejava ()
+%!error usejava (1, 2)
+%!error usejava (1)
+%!error <unrecognized feature> usejava ("abc")
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/java/warndlg.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,54 @@
+## Copyright (C) 2010 Martin Hepperle
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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} {@var{h} =} warndlg (@var{msg})
+## @deftypefnx {Function File} {@var{h} =} warndlg (@var{msg}, @var{title})
+## Display @var{msg} using a warning dialog box. 
+##
+## The message may have multiple lines separated by newline characters
+## ("\n"), or it may be a cellstr array with one element for each
+## line.  The optional input @var{title} (character string) can be used to
+## set the dialog caption.  The default title is "Warning Dialog".
+##
+## @seealso{helpdlg, inputdlg, listdlg, questdlg}
+## @end deftypefn
+
+function retval = warndlg (msg, title = "Warning Dialog")
+
+  if (nargin < 1 || nargin > 2)
+    print_usage ();
+  endif
+
+  if (! ischar (msg))
+    if (iscell (msg))
+      msg = sprintf ("%s\n", msg{:});
+      msg(end) = "";
+    else
+      error ("warndlg: MSG must be a string or cellstr array");
+    endif
+  endif
+
+  if (! ischar (title))
+    error ("warndlg: TITLE must be a character string");
+  endif
+
+  retval = javaMethod ("warndlg", "org.octave.JDialogBox", msg, title);
+
+endfunction
+
--- a/scripts/miscellaneous/bzip2.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/miscellaneous/bzip2.m	Sun Dec 23 13:00:02 2012 -0500
@@ -49,9 +49,9 @@
 %!   filename = tmpnam;
 %!   dummy    = 1;
 %!   save (filename, "dummy");
-%!   n_tmpfiles_before = length (find (strncmp ("oct-", cellstr (ls (P_tmpdir)), 4)));
+%!   n_tmpfiles_before = length (find (strncmp ("oct-", cellstr (ls (tempdir)), 4)));
 %!   entry = bzip2 (filename);
-%!   n_tmpfiles_after = length (find (strncmp ("oct-", cellstr (ls (P_tmpdir)), 4)));
+%!   n_tmpfiles_after = length (find (strncmp ("oct-", cellstr (ls (tempdir)), 4)));
 %!   if (n_tmpfiles_before != n_tmpfiles_after)
 %!     error ("bzip2 has not cleaned up temporary files correctly!");
 %!   endif
--- a/scripts/miscellaneous/edit.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/miscellaneous/edit.m	Sun Dec 23 13:00:02 2012 -0500
@@ -486,14 +486,18 @@
         if (any (exists == [2, 103]))
           body = type (name){1};
         else
-          body = cstrcat ("function [ ret ] = ", name, " ()\n\nendfunction\n");
+          body = cstrcat ("function [ret] = ", name, " ()\n\nendfunction\n");
         endif
         if (isempty (head))
-          comment = cstrcat ("## ", name, "\n\n",
+          comment = cstrcat ("## -*- texinfo -*- \n## @deftypefn {Function File}", 
+                             "{@var{ret} =}", name, "(@var{x}, @var{y})\n##\n",
+                             "## @seealso{}\n## @end deftypefn\n\n",
                              "## ", strrep (tail, "\n", "\n## "), "\n\n");
         else
           comment = cstrcat ("## ", strrep (head,"\n","\n## "), "\n\n", ...
-                             "## ", name, "\n\n", ...
+                             "## -*- texinfo -*- \n## @deftypefn {Function File}", 
+                             "{@var{ret} =}", name, "(@var{x}, @var{y})\n##\n",
+                             "## @seealso{}\n## @end deftypefn\n\n",
                              "## ", strrep (tail, "\n", "\n## "), "\n\n");
         endif
         text = cstrcat (comment, body);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/miscellaneous/error_ids.m	Sun Dec 23 13:00:02 2012 -0500
@@ -0,0 +1,55 @@
+## Copyright (C) 2012 Juan Pablo Carbajal
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## Octave 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 -*-
+## @cindex error ids
+##
+## @table @code
+## @item Octave:invalid-context
+## Indicates the error was generated by an operation that cannot be executed in
+## the scope from which it was called.  For example, the function
+## @code{print_usage ()} when called from the Octave prompt raises this error.
+##
+## @item Octave:invalid-input-arg
+## Indicates that a function was called with invalid input arguments.
+##
+## @item Octave:invalid-fun-call
+## Indicates that a function was called in an incorrect way, e.g., wrong number
+## of input arguments.
+##
+## @item Octave:invalid-indexing
+## Indicates that a data-type was indexed incorrectly, e.g., real-value index
+## for arrays, non-existent field of a structure.
+##
+## @item Octave:bad-alloc
+## Indicates that memory couldn't be allocated.
+##
+## @item Octave:undefined-function
+## Indicates a call to a function that is not defined. The function may
+## exist but Octave is unable to find it in the search path.
+##
+## @end table
+
+
+function error_ids ()
+  help ("error_ids");
+endfunction
+
+
+## Remove from test statistics.  No real tests possible
+%!assert (1)
--- a/scripts/miscellaneous/getfield.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/miscellaneous/getfield.m	Sun Dec 23 13:00:02 2012 -0500
@@ -18,28 +18,12 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {[@var{v1}, @dots{}] =} getfield (@var{s}, @var{key}, @dots{})
-## Extract a field from a structure (or a nested structure).  For example:
-##
-## @example
-## @group
-## ss(1,2).fd(3).b = 5;
-## getfield (ss, @{1,2@}, "fd", @{3@}, "b")
-##    @result{} 5
-## @end group
-## @end example
+## @deftypefn {Function File} {[@var{val}] =} getfield (@var{s}, @var{field})
+## @deftypefnx {Function File} {[@var{val}] =} getfield (@var{s}, @var{idx1}, @var{field1}, @var{idx2}, @var{field2}, @dots{})
+## Extract a field from a structure (or a nested structure). The syntax
+## is the same as @code{setfield}, except it omits the final @var{val}
+## argument, returning this value instead of setting it.
 ##
-## Note that the function call in the previous example is equivalent to
-## the expression
-##
-## @example
-## @group
-## i1 = @{1,2@}; i2 = "fd"; i3 = @{3@}; i4= "b";
-## ss(i1@{:@}).(i2)(i3@{:@}).(i4)
-##    @result{} 5
-##
-## @end group
-## @end example
 ## @seealso{setfield, rmfield, isfield, isstruct, fieldnames, struct}
 ## @end deftypefn
 
--- a/scripts/miscellaneous/ls.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/miscellaneous/ls.m	Sun Dec 23 13:00:02 2012 -0500
@@ -56,7 +56,7 @@
       ## shell (cmd.exe) on MinGW uses '^' as escape character
       args = regexprep (args, '([^\w.*? -])', '^$1');
     else
-      args = regexprep (args, '([^\w.*? -])', '\$1');
+      args = regexprep (args, '([^\w.*? -])', '\\$1');
     endif
     args = sprintf ("%s ", args{:});
   else
--- a/scripts/miscellaneous/module.mk	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/miscellaneous/module.mk	Sun Dec 23 13:00:02 2012 -0500
@@ -20,6 +20,7 @@
   miscellaneous/dos.m \
   miscellaneous/dump_prefs.m \
   miscellaneous/edit.m \
+  miscellaneous/error_ids.m \
 	miscellaneous/fact.m \
   miscellaneous/fileattrib.m \
   miscellaneous/fileparts.m \
@@ -68,7 +69,6 @@
   miscellaneous/unpack.m \
   miscellaneous/untar.m \
   miscellaneous/unzip.m \
-  miscellaneous/usejava.m \
   miscellaneous/ver.m \
   miscellaneous/version.m \
   miscellaneous/warning_ids.m \
--- a/scripts/miscellaneous/recycle.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/miscellaneous/recycle.m	Sun Dec 23 13:00:02 2012 -0500
@@ -17,13 +17,13 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn  {Function File} {@var{current_state}} recycle ()
-## @deftypefnx {Function File} {@var{old_state}} recycle (@var{new_state})
+## @deftypefn  {Function File} {@var{current_state} =} recycle ()
+## @deftypefnx {Function File} {@var{old_state} =} recycle (@var{new_state})
 ## Query or set the preference for recycling deleted files.
 ##
-## Recycling files instead of permanently deleting them is currently not
-## implemented in Octave.  To help avoid accidental data loss it
-## is an error to attempt enable file recycling.
+## Recycling files, instead of permanently deleting them, is not currently
+## implemented in Octave.  To help avoid accidental data loss an error
+## will be raised if an attempt is made to enable file recycling.
 ## @seealso{delete}
 ## @end deftypefn
 
--- a/scripts/miscellaneous/setfield.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/miscellaneous/setfield.m	Sun Dec 23 13:00:02 2012 -0500
@@ -18,25 +18,80 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {[@var{k1}, @dots{}, @var{v1}] =} setfield (@var{s}, @var{k1}, @var{v1}, @dots{})
-## Set a field member in a (nested) structure array.  For example:
+## @deftypefn {Function File} {@var{s} =} setfield (@var{s}, @var{field}, @var{val})
+## @deftypefnx {Function File} {@var{s} =} setfield (@var{s}, @var{idx1}, @var{field1}, @var{idx2}, @var{field2}, @dots{}, @var{val})
+##
+## Set a field member @var{field} in a structure @var{s} equal to @var{val}.  For example:
 ##
 ## @example
 ## @group
-## oo(1,1).f0 = 1;
-## oo = setfield (oo, @{1,2@}, "fd", @{3@}, "b", 6);
-## oo(1,2).fd(3).b == 6
-##      @result{} ans = 1
+## @var{s} = struct ();
+## @var{s} = setfield (@var{s}, "foo bar", 42);
 ## @end group
 ## @end example
 ##
+## @noindent
+## This is equivalent to
+##
+## @example
+## @var{s}.("foo bar") = 42;
+## @end example
+##
+## @noindent
+## Note that ordinary structure syntax @code{@var{s}.foo bar = 42} cannot be
+## used here, as the field name is not a valid Octave identifier. Using
+## arbitrary strings for field name is incompatible with @sc{Matlab}, so
+## this usage will warn if the @code{Octave:matlab-incompatible} warning
+## is set. @xref{doc-warning_ids}.
+##
+## With the second calling form, set a field on a structure array,
+## possibly nested, with successive nested indices @var{idx1},
+## @var{idx2}, @dots{} and fields @var{field1}, @var{field2}, @dots{}
+## The indices must be cells containing the desired index at this
+## nesting depth.
+##
+## Thus consider instead,
+##
+## @example
+## @group
+## @var{s} = struct ("baz", 42);
+## setfield (@var{s}, @{1@}, "foo", @{1@}, "bar", 5)
+##     @result{} ans =
+##     scalar structure containing the fields:
+##       baz =  42
+##       foo =
+##         scalar structure containing the fields:
+##           bar =  54
+## @end group
+## @end example
+##
+## Here we first have an ordinary structure array with one field
+## @code{baz} set to 42. Then we set another field in a nested scalar structure
+## indexing with two single cells containing the unique desired indices.
+##
+## Finally an example with nested structure arrays,
+##
+## @example
+## @group
+## @var{sa}.foo = 1;
+## @var{sa} = setfield (@var{sa}, @{2@}, "bar", @{3@}, "baz", 6);
+## @var{sa}(2).bar(3)
+##      @result{} ans =
+##      scalar structure containing the fields:
+##        baz =  6
+## @end group
+## @end example
+##
+## Here @var{sa} is a structure array whose field @code{fd} at elements
+## 1 and 2 field is in turn
+## another structure array whose third element is a structure
+##
 ## Note that the same result as in the above example could be achieved by:
 ##
 ## @example
 ## @group
-## i1 = @{1,2@}; i2 = "fd"; i3 = @{3@}; i4 = "b";
-## oo(i1@{:@}).(i2)(i3@{:@}).(i4) == 6
-##      @result{} ans = 1
+## @var{SA}.foo = 1;
+## @var{SA}(2).bar(3).baz = 6
 ## @end group
 ## @end example
 ## @seealso{getfield, rmfield, isfield, isstruct, fieldnames, struct}
--- a/scripts/miscellaneous/usejava.m	Thu Nov 01 15:01:20 2012 -0400
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,89 +0,0 @@
-## Copyright (C) 2012 Rik Wehbring
-## Parts Copyright (C) 2012 Philip Nienhuis <prnienhuis@users.sf.net>
-##
-## This file is part of Octave.
-##
-## Octave is free software; you can redistribute it and/or modify it
-## under the terms of the GNU General Public License as published by
-## the Free Software Foundation; either version 3 of the License, or (at
-## your option) any later version.
-##
-## Octave 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} {} usejava (@var{feature})
-## Return true if the Java element @var{feature} is available.
-##
-## Possible features are:
-##
-## @table @asis
-## @item "awt"
-## Abstract Window Toolkit for GUIs.
-##
-## @item "desktop"
-## Interactive desktop is running.
-##
-## @item "jvm"
-## Java Virtual Machine.
-##
-## @item "swing"
-## Swing components for lightweight GUIs.
-## @end table
-##
-## @code{usejava} determines if specific Java features are available in an
-## Octave session.  This function is provided for compatibility with scripts
-## which may alter their behavior based on the availability of Java.  The
-## feature "desktop" always returns @code{false} as Octave has no Java-based
-## desktop.  Other features may be available if the Octave-Forge Java package
-## has been installed.
-## @end deftypefn
-
-function retval = usejava (feature)
-
-  if (nargin != 1 || ! ischar (feature))
-    print_usage ();
-  endif
-
-  retval = false;
-
-  switch feature
-    ## For each feature, try javamethods() on a Java class of a feature
-    case "awt"
-      try
-        dum = javamethods ("java.awt.Frame");
-        retval = true;
-      end_try_catch
-    case "desktop"
-      ## Octave has no Java based GUI/desktop, leave retval = false
-    case "jvm"
-      try
-        dum = javamethods ("java.lang.Runtime");
-        retval = true;
-      end_try_catch
-    case "swing"
-      try
-        dum = javamethods ("javax.swing.Popup");
-        retval = true;
-      end_try_catch
-    otherwise
-      error ("usejava: unrecognized feature '%s'", feature);
-  endswitch
-
-endfunction
-
-
-%!assert (usejava ("desktop"), false)
-
-%% Test input validation
-%!error usejava ()
-%!error usejava (1, 2)
-%!error usejava (1)
-%!error <unrecognized feature> usejava ("abc")
-
--- a/scripts/miscellaneous/warning_ids.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/miscellaneous/warning_ids.m	Sun Dec 23 13:00:02 2012 -0500
@@ -131,6 +131,12 @@
 ## By default, the @code{Octave:built-in-variable-assignment} warning is
 ## enabled.
 ##
+## @item Octave:deprecated-keyword
+## If the @code{Octave:deprecated-keyword} warning is enabled, a
+## warning is issued when Octave encounters a keyword that is obsolete and
+## scheduled for removal from Octave.
+## By default, the @code{Octave:deprecated-keyword} warning is enabled.
+##
 ## @item Octave:divide-by-zero
 ## If the @code{Octave:divide-by-zero} warning is enabled, a
 ## warning is issued when Octave encounters a division by zero.
@@ -170,6 +176,8 @@
 ## Print warnings for Octave language features that may cause
 ## compatibility problems with @sc{matlab}.
 ## By default, the @code{Octave:matlab-incompatible} warning is disabled.
+## The --traditional or --braindead startup options for Octave may also
+## be of use, @xref{Command Line Options}.
 ##
 ## @item Octave:md5sum-file-in-path
 ## By default, the @code{Octave:md5sum-file-in-path} warning is enabled.
@@ -240,7 +248,7 @@
 ## if you would like to enable this short-circuit evaluation in
 ## Octave.  Note that the @code{&&} and @code{||} operators always short
 ## circuit in both Octave and @sc{matlab}, so it's only necessary to
-## enable @sc{matlab}-style short-circuiting it's too arduous to modify
+## enable @sc{matlab}-style short-circuiting if it's too arduous to modify
 ## existing code that relies on this behavior.
 ## By default, the @code{Octave:possible-matlab-short-circuit-operator} warning
 ## is enabled.
@@ -255,6 +263,15 @@
 ## @item Octave:recursive-path-search
 ## By default, the @code{Octave:recursive-path-search} warning is enabled.
 ##
+## @item Octave:remove-init-dir
+## The @code{path} function changes the search path that Octave uses
+## to find functions.  It is possible to set the path to a value which
+## excludes Octave's own built-in functions.  If the
+## @code{Octave:remove-init-dir} warning is enabled then Octave will warn
+## when the @code{path} function has been used in a way that may render
+## Octave unworkable.
+## By default, the @code{Octave:remove-init-dir} warning is enabled.
+##
 ## @item Octave:reload-forces-clear
 ## If several functions have been loaded from the same file, Octave must
 ## clear all the functions before any one of them can be reloaded.  If
--- a/scripts/optimization/fminbnd.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/optimization/fminbnd.m	Sun Dec 23 13:00:02 2012 -0500
@@ -21,7 +21,7 @@
 ## -*- texinfo -*-
 ## @deftypefn {Function File} {[@var{x}, @var{fval}, @var{info}, @var{output}] =} fminbnd (@var{fun}, @var{a}, @var{b}, @var{options})
 ## Find a minimum point of a univariate function.
-## 
+##
 ## @var{fun} should be a function handle or name.  @var{a}, @var{b} specify a
 ## starting interval.  @var{options} is a structure specifying additional
 ## options.  Currently, @code{fminbnd} recognizes these options:
@@ -74,8 +74,7 @@
     fun = str2func (fun, "global");
   endif
 
-  ## TODO
-  ## displev = optimget (options, "Display", "notify");
+  displ = optimget (options, "Display", "notify");
   funvalchk = strcmpi (optimget (options, "FunValCheck", "off"), "on");
   outfcn = optimget (options, "OutputFcn");
   tolx = optimget (options, "TolX", 1e-8);
@@ -101,6 +100,11 @@
   fv = fw = fval = fun (x);
   nfev++;
 
+  ## Only for display purposes.
+  iter(1).funccount = nfev;
+  iter(1).x = x;
+  iter(1).fx = fval;
+
   while (niter < maxiter && nfev < maxfev)
     xm = 0.5*(a+b);
     ## FIXME: the golden section search can actually get closer than sqrt(eps)
@@ -115,6 +119,8 @@
     if (abs (e) > tol)
       dogs = false;
       ## Try inverse parabolic step.
+      iter(niter+1).procedure = "parabolic";
+
       r = (x - w)*(fval - fv);
       q = (x - v)*(fval - fw);
       p = (x - v)*q - (x - w)*r;
@@ -141,43 +147,52 @@
     endif
     if (dogs)
       ## Default to golden section step.
+
+      ## WARNING: This is also the "initial" procedure following
+      ## MATLAB nomenclature. After the loop we'll fix the string
+      ## for the first step.
+      iter(niter+1).procedure = "golden";
+
       e = ifelse (x >= xm, a - x, b - x);
       d = c * e;
     endif
 
-     ## f must not be evaluated too close to x.
-     u = x + max (abs (d), tol) * (sign (d) + (d == 0));
+    ## f must not be evaluated too close to x.
+    u = x + max (abs (d), tol) * (sign (d) + (d == 0));
+    fu = fun (u);
+
+    niter++;
 
-     fu = fun (u);
-     nfev++;
-     niter++;
+    iter(niter).funccount = nfev++;
+    iter(niter).x = u;
+    iter(niter).fx = fu;
 
-     ## update  a, b, v, w, and x
+    ## update  a, b, v, w, and x
 
-     if (fu <= fval)
-       if (u < x)
-         b = x;
-       else
-         a = x;
-       endif
-       v = w; fv = fw;
-       w = x; fw = fval;
-       x = u; fval = fu;
-     else
-       ## The following if-statement was originally executed even if fu == fval.
-       if (u < x)
-         a = u;
-       else
-         b = u;
-       endif
-       if (fu <= fw || w == x)
-         v = w; fv = fw;
-         w = u; fw = fu;
-       elseif (fu <= fv || v == x || v == w)
-         v = u;
-         fv = fu;
-       endif
-     endif
+    if (fu <= fval)
+      if (u < x)
+        b = x;
+      else
+        a = x;
+      endif
+      v = w; fv = fw;
+      w = x; fw = fval;
+      x = u; fval = fu;
+    else
+      ## The following if-statement was originally executed even if fu == fval.
+      if (u < x)
+        a = u;
+      else
+        b = u;
+      endif
+      if (fu <= fw || w == x)
+        v = w; fv = fw;
+        w = u; fw = fu;
+      elseif (fu <= fv || v == x || v == w)
+        v = u;
+        fv = fu;
+      endif
+    endif
 
     ## If there's an output function, use it now.
     if (outfcn)
@@ -191,6 +206,26 @@
     endif
   endwhile
 
+  ## Fix the first step procedure.
+  iter(1).procedure = "initial";
+
+  ## Handle the "Display" option
+  switch displ
+    case "iter"
+      print_formatted_table (iter);
+      print_exit_msg (info, struct("TolX", tolx, "fx", fval));
+    case "notify"
+      if (info == 0)
+        print_exit_msg (info, struct("fx",fval));
+      endif
+    case "final"
+      print_exit_msg (info, struct("TolX", tolx, "fx", fval));
+    case "off"
+      "skip";
+    otherwise
+      warning ("unknown option for Display: '%s'", displ);
+  endswitch
+
   output.iterations = niter;
   output.funcCount = nfev;
   output.bracket = [a, b];
@@ -210,6 +245,36 @@
   endif
 endfunction
 
+## A hack for printing a formatted table
+function print_formatted_table (table)
+  printf ("\n Func-count     x          f(x)         Procedure\n");
+  for row=table
+    printf("%5.5s        %7.7s    %8.8s\t%s\n",
+           int2str (row.funccount), num2str (row.x,"%.5f"),
+           num2str (row.fx,"%.6f"), row.procedure);
+  endfor
+  printf ("\n");
+endfunction
+
+## Print either a success termination message or bad news
+function print_exit_msg (info, opt=struct())
+  printf ("");
+  switch info
+    case 1
+      printf ("Optimization terminated:\n");
+      printf (" the current x satisfies the termination criteria using OPTIONS.TolX of %e\n", opt.TolX);
+    case 0
+      printf ("Exiting: Maximum number of iterations has been exceeded\n");
+      printf ("         - increase MaxIter option.\n");
+      printf ("         Current function value: %.6f\n", opt.fx);
+    case -1
+      "FIXME"; ## FIXME: what's the message MATLAB prints for this case?
+    otherwise
+      error ("internal error - fminbnd() is bug, sorry!");
+  endswitch
+  printf ("\n");
+endfunction
+
 
 %!shared opt0
 %! opt0 = optimset ("tolx", 0);
--- a/scripts/optimization/sqp.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/optimization/sqp.m	Sun Dec 23 13:00:02 2012 -0500
@@ -748,7 +748,7 @@
 %!
 %! obj_opt = 0.0539498477702739;
 %!
-%! assert (x, x_opt, 5*sqrt (eps));
+%! assert (x, x_opt, 8*sqrt (eps));
 %! assert (obj, obj_opt, sqrt (eps));
 
 %% Test input validation
--- a/scripts/plot/__gnuplot_drawnow__.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/plot/__gnuplot_drawnow__.m	Sun Dec 23 13:00:02 2012 -0500
@@ -333,7 +333,9 @@
   term = getenv ("GNUTERM");
   ## If not specified, guess the terminal type.
   if (isempty (term) || ! __gnuplot_has_terminal__ (term, plot_stream))
-    if (ismac ())
+    if (isguirunning () && __gnuplot_has_terminal__ ("qt", plot_stream))
+      term = "qt";
+    elseif (ismac ())
       term = "aqua";
     elseif (! isunix ())
       term = "windows";
--- a/scripts/plot/copyobj.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/plot/copyobj.m	Sun Dec 23 13:00:02 2012 -0500
@@ -41,6 +41,10 @@
     print_usage ();
   endif
 
+  ## current figure and axes
+  cf = gcf ();
+  ca = gca ();
+  
   ## compatibility of input handles
   kididx = find (strcmp (alltypes, get (horig).type));
   paridx = find (strcmp (alltypes, get (hparent).type));
@@ -56,6 +60,12 @@
     hnew = struct2hdl (str, hparent);
   endif
 
+  ## reset current figure (and eventually axes) to original
+  set (0, "currentfigure", cf);
+  if (get (hnew, "parent") == cf)
+    set (cf, "currentaxes", ca)
+  endif
+  
 endfunction
 
 
--- a/scripts/plot/private/__go_draw_axes__.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/plot/private/__go_draw_axes__.m	Sun Dec 23 13:00:02 2012 -0500
@@ -2148,12 +2148,12 @@
         k = 1;
         ntics = numel (tics);
         nlabels = numel (labels);
-        fprintf (plot_stream, "set format %s \"%%s\";\n", ax);
+        fprintf (plot_stream, "set format %s \"%%g\";\n", ax);
         if (mirror)
-          fprintf (plot_stream, "set %stics %s %s %s mirror (", ax,
+          fprintf (plot_stream, "set %stics add %s %s %s mirror (", ax,
                    tickdir, ticklength, axispos);
         else
-          fprintf (plot_stream, "set %stics %s %s %s nomirror (", ax,
+          fprintf (plot_stream, "set %stics add %s %s %s nomirror (", ax,
                    tickdir, ticklength, axispos);
         endif
 
@@ -2173,7 +2173,7 @@
         else
           fprintf (plot_stream, "unset m%stics;\n", ax);
         endif
-     else
+      else
         error ("__go_draw_axes__: unsupported type of ticklabel");
       endif
     else
--- a/scripts/plot/private/__print_parse_opts__.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/plot/private/__print_parse_opts__.m	Sun Dec 23 13:00:02 2012 -0500
@@ -140,7 +140,7 @@
           error ("print: Ghostscript binary ""%s"" could not be located",
                  arg(3:end));
         else
-          arg_st.ghostscript_binary = __quote_path__ (arg_st.ghostscript_binary);
+          arg_st.ghostscript.binary = __quote_path__ (arg_st.ghostscript.binary);
         endif
       elseif (length (arg) > 2 && arg(1:2) == "-F")
         idx = rindex (arg, ":");
@@ -477,7 +477,7 @@
       gs_binaries = horzcat (gs_binaries, {"gs", "gs.exe"});
     else
       ## pc - Includes Win32 and mingw.
-      gs_binaries = horzcat (gs_binaries, {"gs.exe", "gswin32c.exe", "mgs.exe"});
+      gs_binaries = horzcat (gs_binaries, {"gs.exe", "gswin32c.exe", "gswin64c.exe", "mgs.exe"});
     endif
     n = 0;
     while (n < numel (gs_binaries) && isempty (ghostscript_binary))
--- a/scripts/plot/private/__quiver__.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/plot/private/__quiver__.m	Sun Dec 23 13:00:02 2012 -0500
@@ -211,12 +211,19 @@
 
     xtmp = x + uu(:) .* (1 - arrowsize);
     ytmp = y + vv(:) .* (1 - arrowsize);
-    xarrw1 = xtmp + (y - yend) * arrowsize / 3;
-    xarrw2 = xtmp - (y - yend) * arrowsize / 3;
-    yarrw1 = ytmp - (x - xend) * arrowsize / 3;
-    yarrw2 = ytmp + (x - xend) * arrowsize / 3;
+
     if (is3d)
+      xarrw1 = xtmp + sqrt((y - yend).^2 + (z - zend).^2) * arrowsize / 3;
+      xarrw2 = xtmp - sqrt((y - yend).^2 + (z - zend).^2) * arrowsize / 3;
+      yarrw1 = ytmp - sqrt((x - xend).^2 + (z - zend).^2) * arrowsize / 3;
+      yarrw2 = ytmp + sqrt((x - xend).^2 + (z - zend).^2) * arrowsize / 3;
+
       zarrw1 = zarrw2 = zend - ww(:) * arrowsize;
+    else
+      xarrw1 = xtmp + (y - yend) * arrowsize / 3;
+      xarrw2 = xtmp - (y - yend) * arrowsize / 3;
+      yarrw1 = ytmp - (x - xend) * arrowsize / 3;
+      yarrw2 = ytmp + (x - xend) * arrowsize / 3;
     endif
 
     if (have_line_spec)
--- a/scripts/plot/struct2hdl.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/plot/struct2hdl.m	Sun Dec 23 13:00:02 2012 -0500
@@ -92,6 +92,25 @@
     p = p(1:2, 1:(tst(end)-1));
   endif
 
+  ## Place the "*mode" properties as the end to avoid having the updaters
+  ## change the mode to "manual" when the value is "auto".
+  names = fieldnames (s.properties);
+  n = strncmp (cellfun (@fliplr, names, "uniformoutput", false), "edom", 4);
+  n = (n | strcmp (names, "activepositionproperty"));
+  names = [names(!n); names(n)];
+  if (strcmp (s.type, "axes"))
+    n_pos = find (strcmp (names, "position") | strcmp (names, "outerposition"));
+    if (strcmp (s.properties.activepositionproperty, "position"))
+      names{n_pos(1)} = "outerposition";
+      names{n_pos(2)} = "position";
+    else
+      names{n_pos(1)} = "position";
+      names{n_pos(2)} = "outerposition";
+    endif
+  endif
+  ## Reorder the properties with the mode properties coming last
+  s.properties = orderfields (s.properties, names);
+
   ## create object
   if (strcmp (s.type, "root"))
     h = 0;
--- a/scripts/set/powerset.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/set/powerset.m	Sun Dec 23 13:00:02 2012 -0500
@@ -19,11 +19,17 @@
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {} powerset (@var{a})
 ## @deftypefnx {Function File} {} powerset (@var{a}, "rows")
+## Compute the powerset (all subsets) of the set @var{a}.
 ##
-## Return a cell array containing all subsets of the set @var{a}.
+## The set @var{a} must be a numerical matrix or a cell array of strings.  The
+## output will always be a cell array of either vectors or strings.
 ##
+## With the optional second argument @code{"rows"}, each row of the set @var{a}
+## is considered one element of the set.  As a result, @var{a} must then be a
+## numerical 2D matrix.
+##
+## @seealso{unique, union, setxor, setdiff, ismember}
 ## @end deftypefn
-## @seealso{unique, union, setxor, setdiff, ismember}
 
 function p = powerset (a, byrows_arg)
 
@@ -31,7 +37,7 @@
 
   if (nargin == 2)
     if (! strcmpi (byrows_arg, "rows"))
-      error ('powerset: expecting third argument to be "rows"');
+      error ('powerset: expecting second argument to be "rows"');
     elseif (iscell (a))
       warning ('powerset: "rows" not valid for cell arrays');
     else
@@ -40,6 +46,9 @@
   elseif (nargin != 1)
     print_usage ();
   endif
+  if (iscell (a) && ! iscellstr (a))
+    error ("powerset: cell arrays can only used for character strings");
+  endif
 
   if (byrows)
     a = unique (a, byrows_arg);
@@ -50,7 +59,7 @@
   endif
 
   if (n == 0)
-    p = [];
+    p = {};
   else
     if (n > 32)
       error ("powerset: not implemented for more than 32 elements");
@@ -77,8 +86,12 @@
 endfunction
 
 
-%!test
+%!shared c, p
 %! c = sort (cellstr ({ [], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]}));
 %! p = sort (cellstr (powerset ([1, 2, 3])));
-%! assert (p, c);
+%!assert (p, c);
+%! c = sort (cellstr ({ [], [1:3], [2:4], [3:5], [1:3; 2:4], [1:3; 3:5], [2:4; 3:5], [1:3; 2:4; 3:5]}));
+%! p = sort (cellstr (powerset ([1:3;2:4;3:5], "rows")));
+%!assert (p,c);
+%!assert (powerset([]), {});  # always return a cell array
 
--- a/scripts/testfun/test.m	Thu Nov 01 15:01:20 2012 -0400
+++ b/scripts/testfun/test.m	Sun Dec 23 13:00:02 2012 -0500
@@ -173,8 +173,15 @@
       __ret1 = "";
       __ret2 = -1;
     else
-      if (exist (__name) == 3)
+      ftype = exist (__name);
+      if (ftype == 3)
         fprintf (__fid, "%s%s source code with tests for dynamically linked function not found\n", __signal_empty, __name);
+      elseif (ftype == 5)
+        fprintf (__fid, "%s%s is a built-in function\n", __signal_empty, __name);
+      elseif (any (strcmp (__operators__ (), __name)))
+        fprintf (__fid, "%s%s is an operator\n", __signal_empty, __name);
+      elseif (any (strcmp (__keywords__ (), __name)))
+        fprintf (__fid, "%s%s is a keyword\n", __signal_empty, __name);
       else
         fprintf (__fid, "%s%s does not exist in path\n", __signal_empty, __name);
       endif